CQRS and event sourcing

Separate read models, projections, replay, snapshots, and the operational weight of keeping events forever.

10 min read🔀 Distributed Data Patterns

Two ideas that arrive together and should be evaluated apart. CQRS says the model that handles writes and the model that serves reads can be different objects, and often should be. Event sourcing says the write model's state can be the log of what happened rather than a row that overwrites itself. The first is cheap and often right; the second is expensive and occasionally right; and a surprising amount of the industry's regret comes from buying both when it wanted the first.

CQRS: a write model and a read model

The order aggregate that enforces the rules — can this be cancelled, is the total right, did the stock reservation succeed — is the wrong shape for the order-history page, which wants the customer's name, a status label, three product thumbnails and the delivery date, from four tables, sorted, paged. Serving that page from the write model is either a fetch-join tangle or the N+1 problem the JPA course showed; serving it from a read model built for the page is one indexed query:

sql
CREATE TABLE order_summary (           -- the read model: one row per order, exactly the page's columns
    order_id      BIGINT PRIMARY KEY,
    customer_name TEXT, status_label TEXT, thumbnails JSONB, delivered_on DATE, total_paise BIGINT
);

Writes go through the aggregate and its repository; reads go through a query service that knows nothing about invariants and everything about the page. The two can be tables in the same database (the honest starting point), a table and a materialised view, or a relational store and Elasticsearch — the pattern says nothing about how many stores, only that the shapes differ.

What it costs is the thing that keeps the two in step: a projection that updates order_summary when an order changes. In one database it can be the same transaction. Across stores it is an event — the outbox from the last lesson — and then the read model is eventually consistent: a customer who cancels and refreshes may see the old status for a moment. That moment is a product decision, and "read your own writes" (route this user's next read to the write model, or return the new state from the command) is the usual answer for the cases that matter.

Projections

A projection is a consumer that folds events into a read model: OrderPlaced inserts the summary row, OrderShipped updates the label, OrderCancelled sets it and clears the delivery date. Three properties make one operational:

  • Idempotent, because the outbox relay is at-least-once. An upsert keyed on order_id handles a repeated OrderPlaced by doing nothing new.
  • Rebuildable: a projection is a derived table, and being able to drop it and replay every event into a fresh one is what lets you add a column, fix a bug in the folding logic, or build a second read model for a new page. That is the strongest argument for keeping events at all.
  • Tracked: it records how far through the stream it has got, so a restart resumes rather than replays, and a dashboard can show its lag.

Several projections from one stream is the normal shape: the summary table, the search index, the analytics warehouse, each a consumer, each rebuildable on its own.

Event sourcing: the log is the state

Under CQRS the write model still stores current state — an orders row, updated in place. Event sourcing replaces that row with the sequence of events that produced it: OrderPlaced, LineAdded, PaymentTaken, OrderShipped, appended to a per-aggregate stream and never modified. Loading the order means replaying its events through the aggregate; saving means appending the new ones with an optimistic concurrency check on the expected version, so two commands on the same order cannot both succeed:

java
List<Event> history = store.load("order-42");                 // events 1..n
Order order = Order.replay(history);                         // fold into state
List<Event> produced = order.cancel(reason);                  // the decision: returns events, mutates nothing
store.append("order-42", expectedVersion = history.size(), produced);   // fails if someone appended first

What you gain is real. A complete audit that is the system of record rather than a log beside it. Temporal queries — the order as it was on the 3rd — by replaying to a point. Rebuildable read models for free, since the events were never lost. And a domain model whose decisions are explicit: an aggregate that returns events is a pure function of history and command, which tests beautifully.

What you pay is also real, and it is paid every day the system runs. Events are forever: an OrderPlaced from 2024 with a field you have since renamed must still replay, so every event type is versioned and every old version has an upcaster, for as long as the stream exists. Queries are impossible against the store — "orders over 5000 last month" is a projection, always, which means CQRS is mandatory rather than optional. Deleting is a design problem: a GDPR erasure request against an immutable log is answered with crypto-shredding (encrypt each person's data with a per-person key and destroy the key), which is a system you now own. And the store itself — EventStoreDB, Axon Server, or a hand-built events table with (stream_id, version) unique — is infrastructure with its own failure modes.

Snapshots

An order with forty events replays in microseconds; an account with two million ledger entries does not. A snapshot is the aggregate's state at version n, stored beside the stream, so a load reads the snapshot and replays only events after n. Take one every few hundred events, or on a schedule; treat it as a cache, not a source — it can always be rebuilt from the events, and a change to the aggregate's shape invalidates every snapshot, which is fine precisely because they are disposable.

When not to

The honest test is the audit and temporal-query requirement. If the domain is a history — a ledger, an insurance claim, a trading position, a medical record — event sourcing matches the problem and the costs above are costs you were going to pay somehow. If the domain is current state that happens to change — a product catalogue, a user profile, most CRUD — then a row, an updated_at, and an audit table written by the same transaction give you the audit, and CQRS with an outbox gives you the read models, for a fraction of the operational weight.

The two decisions, separately: CQRS when a read shape and the write shape have diverged enough to hurt, which is common. Event sourcing when the history is the product, which is rare, and then all the way — a half-sourced system, with some aggregates as rows and some as streams, has both sets of costs.

Under the hood: folding a stream into state, and what a snapshot changes about that fold

"Loading means replaying its events through the aggregate," above, is a fold: state = events.reduce(applyEvent, initialState). It is worth being precise about what applyEvent is and is not, because conflating it with the code that decided to emit an event is where a lot of event-sourcing designs go wrong.

Deciding and applying are different functions with different contracts. The command handler that produces an event — order.cancel(reason) in the snippet above — can reject: it checks invariants, and if cancellation is not allowed it throws or returns nothing, no event is appended. applyEvent, the function the fold uses, never rejects. It receives an event that has already happened — it is a fact, appended and durable — and its only job is to update in-memory fields to match: case OrderCancelled c -> this.status = CANCELLED. There is no if that says no. An applyEvent that can throw on a well-formed, already-persisted event is a sign the validation logic leaked into the wrong function.

A projection is the same fold, aimed at a table instead of an object. A projection process subscribes to the stream — in a Kafka-backed system, typically a topic partitioned by aggregate id, so one consumer sees a given aggregate's events in the order they were appended — and for each event runs its own applyEvent that upserts a row instead of mutating a field. Two things make this correct under replay and restart, and they are the same two properties this lesson already named for projections in general, made concrete here: the upsert is keyed on the aggregate id so folding the same event twice leaves the row unchanged, and the projection durably records its own read position in the stream after each batch, so a restart resumes from where it left off rather than refolding from event zero. A crash between writing the row and recording the position causes exactly one small batch to be refolded — which the upsert already makes harmless.

A snapshot changes the fold's starting point, not its logic. A snapshot stored at version n is the result of events[0..n].reduce(applyEvent, initialState) — a plain blob of the aggregate's state, versioned the same way events are. Loading becomes: read the latest snapshot (if any), read only events with version greater than the snapshot's, and fold those onto the snapshot's state instead of the full history. This is arithmetic, not a different mechanism — fold(snapshotState, eventsAfter(snapshotVersion)) produces exactly the same result as fold(initialState, allEvents), which is precisely why a snapshot is safe to discard: it is a cached answer to a pure function, never a second source of truth, and a version mismatch (the aggregate's shape changed since the snapshot was taken) is handled by throwing the snapshot away and folding from zero, not by trusting stale shape.

Try it yourself

Fold a stream two ways and confirm a snapshot changes nothing but the work

A snapshot is only trustworthy if folding from it produces the exact answer a full replay would. Trace both.

java
int[] events = {50, 30, -20, 40, 50};   // a ledger's events, in order: deposits and a withdrawal
int snapshotAt = 2;                     // a snapshot was taken after folding events[0] and events[1]
 
int fullReplay = 0;
for (int e : events) fullReplay += e;
 
int snapshotBalance = 0;
for (int i = 0; i < snapshotAt; i++) snapshotBalance += events[i];
 
int fromSnapshot = snapshotBalance;
for (int i = snapshotAt; i < events.length; i++) fromSnapshot += events[i];
 
System.out.println("full replay: " + fullReplay);
System.out.println("snapshot after event " + snapshotAt + ": " + snapshotBalance);
System.out.println("replay from snapshot: " + fromSnapshot);

Before running it: fromSnapshot only replays three of the five events. Why must it still land on the same number as fullReplay, no matter where snapshotAt is set?

Misconceptions

  • "A snapshot is a second source of truth alongside the events, so it needs its own consistency guarantees." It is a cached, disposable answer to a pure fold over events that already exist — fold(snapshot, eventsAfter) and fold(initial, allEvents) are the same computation by construction. A snapshot that looks wrong is discarded and rebuilt from events; it is never reconciled against them as a peer.
  • "The function that folds an event into state validates the event, the same way the command handler validated the command." The fold runs against events that were already accepted and durably appended — it has no business rejecting them. Putting an if that can refuse a fact into applyEvent usually means a validation rule leaked out of the command handler, where it belongs, into code that is supposed to be incapable of saying no.

Sources

  • Martin Fowler, martinfowler.com — "Event Sourcing" and "CQRS" (the bliki entries that named both patterns for the wider industry).
  • Greg Young — talks and writing on event sourcing and CQRS, including the "CQRS Documents" write-up, an early and widely cited source for the pattern's practical shape.
  • Chris Richardson, microservices.io — the Event Sourcing pattern, including its discussion of snapshotting.
Progress is saved on this device and to your account when signed in.