Polski

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.

hard · typescript · javascript · python · csharp · java · go · 40 XP

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

  1. The BankAccount aggregate:

    • open(id, owner) creates the account by recording AccountOpened;
    • the commands deposit(amount), withdraw(amount) and close() 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 increments version (the number of applied events);
    • fromHistory(events) rebuilds the state from history – with no uncommitted events;
    • uncommittedEvents() returns a copy, markCommitted() clears it.
  2. InMemoryEventStore – one append-only stream of events per account:

    • append(streamId, events, expectedVersion) appends only when the stream has exactly expectedVersion events, otherwise it raises a concurrency error (ConcurrencyError/ConcurrencyException, in Go ErrConcurrency);
    • load(streamId) returns a copy of the stream (empty when it does not exist).
  3. 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 error Account 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