Event-sourced bank account
An account aggregate whose state comes only from replaying events, an event store with optimistic concurrency and a repository that saves only new facts. Queries about past state come for free.
A cooperative bank must answer not only "how much is in the account" but also "how much was there on 3 March at 2 p.m." and "who changed it and when". A table with a balance column cannot tell – every update overwrites the past. With event sourcing the source of truth is a sequence of events (AccountOpened, MoneyDeposited, MoneyWithdrawn, AccountClosed), and the current state is the result of replaying them.
Task
The
BankAccountaggregate:open(id, owner)creates the account by recordingAccountOpened;- the commands
deposit(amount),withdraw(amount)andclose()first check the rules and then record an event: apply it to the state and add it to the uncommitted list; - errors in this order:
Account is closed,Amount must be positive,Insufficient funds,Balance must be zero to close; a rejected command records nothing; - applying an event (
apply) validates nothing – it only changes state and incrementsversion(the number of applied events); fromHistory(events)rebuilds the state from history – with no uncommitted events;uncommittedEvents()returns a copy,markCommitted()clears it.
InMemoryEventStore– one append-only stream of events per account:append(streamId, events, expectedVersion)appends only when the stream has exactlyexpectedVersionevents, otherwise it raises a concurrency error (ConcurrencyError/ConcurrencyException, in GoErrConcurrency);load(streamId)returns a copy of the stream (empty when it does not exist).
AccountRepository(store):save(account)appends only the uncommitted events with the expected version = the account's version minus the number of new events, then marks them committed;load(id)rebuilds the account; an empty stream is the errorAccount not found: <id>.
Among other things the tests check that a history with an old overdraft (a withdrawal bigger than the balance, allowed before the rules changed) replays without errors, that past state comes from replaying a prefix of the stream, and that two parallel saves of the same account end with a conflict. Names per language: from_history, uncommitted_events, ValueError/LookupError (Python); GetUncommittedEvents, IsClosed, KeyNotFoundException (C#); NoSuchElementException (Java); in Go the functions Open, FromHistory, methods returning error and lower-case messages.
Topics: CQRS, Event Sourcing
Related articles
- Event sourcing: store the facts, not just the latest state
State as a sequence of immutable events: streams, rehydration by folding, optimistic concurrency, projections, snapshots and event versioning. An aggregate and an event store in C# (Marten), TypeScript, Java, Go and Python.