Course contents

10. Software Architecture Lesson 8 of 10

Event Sourcing

Store events instead of state: append with expected versions, rebuild by replay, keep loads fast with snapshots, and build read models with projections.

18 minAdvanced10 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • An append-only stream of events per aggregate is the source of truth; state is a fold over it.
  • Commands read the stream, decide, and append with an expected version, so concurrent writers conflict cleanly.
  • Replay is deterministic: it rebuilds state after a restart and answers “what was it at time T?”.
  • Load cost grows with stream length; snapshots or periodic stream closing keep it bounded.
  • Projections build read models from the event feed; any read model can be rebuilt from position 0.
  • Events are forever: plan for versioning (upcasters), erasure (crypto-shredding) and lagging read models.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

Event sourcing stores every change to an entity as an event, appended to that entity's stream, instead of overwriting its current state. AccountOpened, Deposited(100), Withdrew(30) are the record; balance = 70 is computed from them. The ordered, append-only log is the source of truth. Current state, read models and caches are all derived from it.

Why it exists

A state table remembers only the latest value. Questions such as "how did we get here?", "what was the balance on 1 March?" or "which orders would the new rule have flagged last year?" need history that a state table has thrown away. Audit tables and change logs try to recover it, but they are secondary copies that can drift from the truth. Event sourcing makes the history the primary data, so audit, temporal queries and new read models come from the same place, and events are natural integration points for the rest of the system.

How it works

Streams and events. Each aggregate (account, order) has a stream identified by its id. Events are immutable, named in the past tense in the domain's language (see DDD), and carry the data of what happened. The store also keeps a global order (a position across all streams) for subscribers.

Handling a command. Load the stream, fold the events into state (Apply(event) for each), run the business rules, and append new events with the expected version the decision was based on. If another writer appended in the meantime, the store rejects the append (optimistic concurrency) and the command is retried on fresh state.

public sealed class Account
{
    public decimal Balance { get; private set; }
    public long Version { get; private set; } = -1;

    public static Account Rehydrate(IEnumerable<object> events)
    {
        var account = new Account();
        foreach (var e in events) account.Apply(e);
        return account;
    }

    private void Apply(object e)
    {
        Balance = e switch
        {
            Deposited d => Balance + d.Amount,
            Withdrew w  => Balance - w.Amount,
            _           => Balance,
        };
        Version++;
    }

    public Withdrew Withdraw(decimal amount) =>
        amount <= Balance ? new Withdrew(amount) : throw new InvalidOperationException("Insufficient funds");
}

// Handler: load, decide, append with the expected version (store API varies:
// KurrentDB/EventStoreDB take an expected revision/StreamState, Marten has
// AppendOptimistic or an expected version on Append).
var account = Account.Rehydrate(await store.ReadStreamAsync(id, ct));
var @event = account.Withdraw(cmd.Amount);
await store.AppendAsync(id, expectedVersion: account.Version, new[] { @event }, ct);

Snapshots. For long streams, periodically store the folded state with its version. Loading becomes "latest snapshot + events after it". Snapshots are a cache; they can be discarded and rebuilt. An alternative is to keep streams short by design, e.g. closing an accounting period and opening a new stream with the carried-over balance.

Projections. Subscribers read the global event feed, update read models (tables, documents, search indexes) and store a checkpoint. Because the history is complete, a new projection can start from position 0 and build a read model that includes the past. This is CQRS fed by the event store, with the same eventual consistency.

Versioning. Event schemas evolve. Old events stay as they were written; readers either handle all versions or use upcasters that convert old versions to the current shape on read. Additive changes (new optional fields) are easiest; renaming or splitting events needs care, sometimes a copy-and-transform migration into new streams.

When to use it

  • The history itself has business value: ledgers, payments, orders, insurance claims, workflows.
  • Audit requirements demand a complete, tamper-evident record of changes.
  • You need temporal queries or the ability to build new views over past data.
  • The domain is naturally described as a sequence of events (event storming produces them anyway).

When not to

  • CRUD data where only the latest value matters (settings, reference data, profiles).
  • Teams new to DDD and CQRS; event sourcing amplifies modelling mistakes, because bad events are permanent.
  • Systems that need ad-hoc queries over current state without building projections.
  • Where hard deletion of data is a core requirement and cannot be designed around.

Trade-offs

Choice You gain You pay
Events as source of truth Full history, audit, temporal queries, new views from the past Projections for every query; versioning forever
Optimistic concurrency on streams No locks while deciding; clean conflicts Retries under contention on hot streams
Snapshots Bounded load time for long streams Snapshot versioning and invalidation
Short streams (closing the books) No snapshots needed Modelling effort; cross-period queries need projections
Asynchronous projections Fast appends, independent read models Lagging, eventually consistent reads

Alternatives

  • State storage + audit log/history table: simpler; history is secondary and may drift.
  • Temporal tables (SQL Server system-versioned tables, PostgreSQL extensions): row history without changing the programming model, but rows, not domain events.
  • Change data capture: emits row changes from a normal database as a stream for others to consume.
  • Transactional outbox: publishes domain events from a state-stored model without making them the source of truth.

Failure modes

  • Unbounded streams. Load time grows with every event; without snapshots or stream closing, commands slow down until the store saturates (the lesson's simulation shows it).
  • CRUD events. AccountUpdated { ...all fields } captures no intent; you get event sourcing's cost without its benefit.
  • Breaking schema changes. Changing an event's meaning in place corrupts every replay. Version events; never reuse names for new meanings.
  • Non-idempotent projections. At-least-once delivery replays events into read models; without checkpoints or version checks, totals are counted twice.
  • Personal data in events. Makes erasure requests hard; design for crypto-shredding or references.
  • Hot streams. One stream written by many concurrent users produces constant version conflicts; split the aggregate.

In production

Choose a store with per-stream optimistic concurrency and a global subscription: KurrentDB (formerly EventStoreDB), Marten on PostgreSQL in .NET, or a relational table with a unique (stream_id, version) constraint. Keep events small and meaningful, version them explicitly, and test upcasters. Monitor projection lag and rebuild time; build new projection versions alongside the old and switch when caught up. Snapshot only when measurements show long loads. Publish integration events for other services separately from internal domain events, so internal changes don't break consumers.

Common misconceptions

  • "Event sourcing is the same as event-driven architecture." EDA is about services communicating through events; event sourcing is a persistence model inside one service. Either can exist without the other.
  • "You need Kafka for event sourcing." Kafka lacks per-entity streams with optimistic concurrency on append; it is commonly used to distribute events, rarely as the event store for aggregates.
  • "Replay means re-running side effects." Replay rebuilds state; side effects (emails, payments) must not be repeated, which is why handlers that cause them are kept out of the fold.
  • "Event sourcing requires CQRS with separate databases." It requires projections for queries, which may live in the same database.

Interview angle

Explain the loop: load stream → fold → decide → append with expected version. Then cover the hard parts unprompted: snapshots for long streams, projections and their lag, idempotent projectors with checkpoints, event versioning with upcasters, GDPR via crypto-shredding, and the distinction from event-driven integration. Mention where you would not use it.

Model assumptions

Most of this lesson is a scripted illustration: appends, stream reads, version conflicts, projections and replays are scripted packets over scenery nodes, not simulated. Two steps (Long stream, Snapshots) and the challenge run on the simulation engine: commands arrive as a Poisson stream; the account service has 64 workers and 3 ms of work per command; the event store has 8 connections, and the time to load a stream and append is modelled as one query of 6 ms (short stream), 150 ms (5,000 events) or 8 ms (snapshot plus tail), lognormal with cv 0.3. Commands waiting more than 500 ms for a connection fail. Real stores read streams in pages and cache hot streams; the numbers are illustrative orders of magnitude, not benchmarks.

The lesson as textEvery step of the simulation, written out.
  1. 1. Store what happened, not just the result

    A classic system stores the current state: one row, balance = 70. Each update overwrites the last; how we got to 70 is gone (unless someone kept an audit table).

    An event-sourced system stores the events instead, in order, in an append-only stream per account: AccountOpened, Deposited 100, Withdrew 30. The events are the source of truth; the balance is derived from them. Here a new deposit is recorded by appending one more event: nothing is updated, nothing is deleted.

    This lesson is mostly a scripted illustration: packets show the protocol between the service and the event store. Two later steps run on the simulation engine.

    Scene: The event store holds the account’s stream: AccountOpened, Deposited 100, Withdrew 30. A deposit command appends a fourth event, Deposited 50, and the store acknowledges it.

    Key idea: In event sourcing the append-only log of events is the source of truth; current state is a derived value.

  2. 2. Load by replaying, then append

    A command, “withdraw 20”, needs the current balance to check the rule “no overdraft”. The service reads the stream (four events), folds them into state (0 → 100 → 70 → 120), decides the withdrawal is allowed and appends Withdrew 20 as event 5.

    The append carries the version it was based on: *expected version 4*. In .NET with EventStoreDB/KurrentDB that is the StreamState/expected-revision argument; with Marten, AppendOptimistic or an expected version on Append. The store accepts the append only if the stream is still at version 4.

    Scene: The service reads the four events of the stream, folds them into a balance of 120, accepts the withdrawal and appends Withdrew 20 as event 5 with expected version 4. The store acknowledges.

    Key idea: Every command is: read the stream, rebuild state, decide, append new events with the expected version.

  3. 3. Two writers, one stream

    A branch clerk and an ATM both act on the account at the same moment. Both read the stream at version 5 and both try to append event 6.

    The clerk’s append arrives first and succeeds: the stream is now at version 6. The ATM’s append still says *expected version 5*, so the store rejects it (red). The ATM service reloads the stream, now with the clerk’s event in it, re-checks the rule against the new balance and appends again as event 7.

    This is optimistic concurrency on the stream: no locks are held while deciding, and a lost race costs one reload. Scripted illustration.

    Scene: The account service and the ATM service both append to the same stream expecting version 5. The account service’s append succeeds; the ATM’s is rejected with a version conflict. The ATM reloads the six events and appends successfully as event 7.

    Key idea: The expected version on append turns a race between writers into a clean conflict that the loser retries.

  4. 4. State is rebuilt, never lost

    The account service restarts with nothing in memory. It does not need a backup of the balance: it replays the stream from the first event and arrives at exactly the same state, because applying the same events in the same order is deterministic.

    Replay also answers questions a state table cannot: *what was the balance last Tuesday?* (replay up to that event), *why is it 87?* (read the events), *what would the new fee rule have charged?* (replay with different code). The stream doubles as a complete audit log.

    Scripted: seven events stream back to the service.

    Scene: After a restart the account service reads all seven events from the stream and folds them back into the same balance.

    Key idea: Replaying the events always yields the same state, and replaying up to a point gives the state at that time.

  5. 5. Replaying 5,000 events on every command

    Years later a busy merchant account has 5,000 events. Every command still reads the whole stream before it can decide, about 150 ms of event-store time each.

    At 60 commands per second the store needs more time than its 8 connections have (8 ÷ 0.15 s ≈ 53 per second). Commands wait for a connection, P95 latency climbs into the hundreds of milliseconds and commands that wait more than 500 ms fail.

    This step runs on the simulation engine; the stream length is modelled as the store’s time per command.

    Scene: Sixty commands per second each replay a 5,000-event stream. The event store is saturated, commands queue for connections, P95 latency reaches hundreds of milliseconds and some commands fail.

    Key idea: Load cost grows with stream length. Long-lived streams make every command slower.

  6. 6. Snapshots bound the replay

    Every few hundred events the service saves a snapshot: the folded state at a known version (balance 1,840 @ v5000). A command now loads the latest snapshot and replays only the events after it, a dozen instead of 5,000: about 8 ms.

    The store has headroom again, the queue disappears and P95 drops well below 100 ms. Snapshots are a cache, not a source of truth: if one is missing or its format changes, delete it and replay from the events.

    Many teams avoid the need altogether by keeping streams short (“closing the books”: an AccountingPeriodClosed event starts a new stream with the opening balance). Simulated.

    Scene: A snapshot store holds the folded state at version 5000. Each command loads the snapshot and replays only the few newer events; the event store has headroom, nothing fails and P95 latency is well under 100 ms.

    Key idea: A snapshot is a cached fold at a version; load it, then replay only the tail.

  7. 7. Projections turn events into read models

    The event store is great at “give me stream X” and poor at “all accounts overdrawn in March”. For queries, projections subscribe to the store’s global event feed and build read models: a balances table, a statement per month.

    Each event flows from the store to the projector, which updates every read model that cares about it and records its checkpoint (the last position it processed). This is CQRS fed by the event store; read models lag slightly behind, as the CQRS lesson shows.

    Scripted: three new events flow to both read models while simulated commands keep running at a lower rate.

    Scene: A projector reads new events from the event store and updates two read models, a Balances view and a Statements view, recording its checkpoint after each event.

    Key idea: Projections subscribe to the event stream and maintain read models; their checkpoint says how far they have read.

  8. 8. A new read model, built from history

    Fraud analysts want a new view: unusual withdrawal patterns per account, including the past. With a state table that history would be gone. Here the projector simply starts a new projection at position 0 and replays every event ever stored into the new read model, then keeps going with live events.

    The same trick fixes a buggy projection: correct the code, drop the read model, replay. On a large store that takes time, so production systems build the new version alongside the old one and switch queries over when it has caught up.

    Scripted: the replay is a fast burst of historical events into the new view.

    Scene: A new Fraud signals view is added. The projector replays every historical event from position 0 into it in a fast burst, then continues with live events.

    Key idea: Read models are disposable: any new one can be built from the full history by replaying from position 0.

  9. 9. Events are forever: the costs

    An event, once stored, is a fact you cannot quietly edit. That has consequences:

    - Schema evolution. Deposited v1 had only an amount; v2 adds a currency. Old events stay v1, so readers need upcasters (convert v1 to v2 on read) or must handle every version, forever. - Deleting personal data. GDPR erasure conflicts with an immutable log. Common answers: keep personal data outside the events, or encrypt it per person and delete the key (*crypto-shredding*). - Querying needs projections, and projections bring eventual consistency. - Modelling effort. Good events need domain understanding (see DDD); events that mirror table updates (AccountUpdated) give the cost without the benefit.

    Scripted illustration.

    Scene: The event store holds two versions of the Deposited event; the account service upcasts old versions when reading. Personal data is erased by deleting the person’s encryption key.

    Key idea: Event sourcing trades simple updates for an immutable history; versioning, erasure and projections are the price.

  10. 10. What to remember about event sourcing

    The event stream is the source of truth; state is a fold over it. Commands read, decide and append with an expected version, so concurrent writers conflict cleanly. Snapshots keep loading fast for long streams. Projections build read models from the event feed, and any of them can be rebuilt by replay.

    In return you take on event versioning, data-erasure strategies and eventually consistent queries. Use it where history, audit and temporal questions are worth that: ledgers, orders, workflows. Not for a settings table.

    Scene: The full setup: clients, account service with snapshots, the event store, and a projector feeding Balances, Statements and Fraud signals read models.

    Key idea: Event sourcing keeps every change as an immutable fact: powerful history, paid for in versioning and projections.