Lesson 21 of 28Domain-driven design
Event Sourcing and CQRS in Depth
Separate write and read models, build an event store with optimistic concurrency, run and rebuild projections, and version events safely.
A fintech support ticket says: "The customer's balance shows 2,000 but they swear it was 10,000 yesterday and they made no withdrawal." With a normal accounts table you have one number and a shrug. With an event-sourced ledger you can list every change, who made it, when, and from which ATM, then show the balance at any moment in the past. That is why ledgers, payment systems and audit-heavy products reach for event sourcing, and why its partner pattern CQRS comes up in system design rounds. You met both ideas briefly in Event-Driven Architecture. This lesson is the version you can build, run and defend in a design review, including when not to use them.
CQRS on its own, the common case
Start without events. CQRS (command query responsibility segregation) only says: the model you write through and the model you read from can be different.
The write side is your aggregate from the tactical DDD lesson: an Order with rules, saved in normalised tables. The read side is whatever the screens need. The "My orders" page wants order number, date, total, item count, status and the first product image, sorted by date, for one customer. Getting that from the write model means joining orders, lines, products, shipments and payments on every page view.
So you keep a read model shaped for that page:
CREATE TABLE order_summaries (
order_id TEXT PRIMARY KEY,
customer_id TEXT NOT NULL,
placed_at TIMESTAMPTZ NOT NULL,
status TEXT NOT NULL,
item_count INTEGER NOT NULL,
total_cents BIGINT NOT NULL,
thumbnail TEXT
);
CREATE INDEX ON order_summaries (customer_id, placed_at DESC);There are three common ways to keep it current, from simplest to most decoupled:
- Same transaction. The command handler updates
order_summariesalongside the write tables. Always consistent, but the write side now knows about every screen. - Database view. A materialized view (Postgres
CREATE MATERIALIZED VIEW ... ; REFRESH MATERIALIZED VIEW CONCURRENTLY) rebuilt on a schedule. No code, but stale between refreshes. - Events. The aggregate raises
OrderPlaced,OrderShippedand so on through the outbox, and a projector updates the read model. Writes stay clean and you can add new read models later, at the cost of eventual consistency.
None of these require event sourcing. Most teams that say "we use CQRS" mean exactly this: a normal database for writes and one or more denormalised read models, often in a different store (a search index in OpenSearch, a cache in Redis, a reporting table).
Event sourcing: the log is the database
Event sourcing goes further. You do not store the current state at all. The events are the source of truth, and current state is computed by folding them, as you saw in Event-Driven Architecture. Each aggregate instance has its own stream (account-42), and each event in it has a version number: 1, 2, 3 and so on.
The schema is small. The unique constraint does the heavy lifting:
CREATE TABLE events (
global_position BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
stream_id TEXT NOT NULL,
version INTEGER NOT NULL,
type TEXT NOT NULL,
data JSONB NOT NULL,
metadata JSONB NOT NULL DEFAULT '{}', -- user id, correlation id, causation id
recorded_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (stream_id, version)
);Writing works like this:
- Load the stream and fold it. You now know the state and the last version, say 2.
- Run the command against that state. The aggregate decides and returns new events (or refuses).
- Append with an expected version: insert the new events as versions 3, 4, and so on. If someone else already wrote version 3, the unique constraint fails, and you have a concurrency conflict. Reload and retry.
This is optimistic concurrency from the tactical lesson again, but you get it from an INSERT instead of an UPDATE ... WHERE version = ?. Events are only ever appended. No row is updated or deleted, which makes the store simple to replicate and audit.
metadata is easy to skip and painful to miss later. Record who caused the event, the request or correlation id that ties a whole user action together, and the causation id (which event or command caused this one). When a support ticket arrives, those fields are your investigation.
A running event-sourced account
Here is the whole loop on SQLite: an append-only store, an expected-version check, and two ATMs racing for the same money.
Press Run (⌘ Enter) to see what happens.ATM B did everything right in memory: it saw 10,000 and approved 8,000. Its append failed because version 3 already existed. On retry it saw the true balance and refused. The rule "no overdraft" held without a single lock.
Projections: building read models from events
An event store is great for writes and terrible for "show all accounts over 1,000". Queries go to projections: read models built by a projector that reads events in global order and updates tables.
Withdraw 2,500 from acc-1
The details that matter in production:
- Checkpoints. Each projection stores the last global position it handled. After a restart it continues from there. Commit the checkpoint in the same transaction as the read-model change, or make every handler idempotent.
- Rebuilding. Because the events are the truth, a read model is disposable. Found a bug in the projection? Added a column? Delete the table, reset the checkpoint to zero, and replay. Big systems rebuild into a new table in the background and switch over when it catches up, so users never see a half-built model.
- Ordering gaps. On Postgres, identity values are handed out when a row is inserted, not when the transaction commits. Transaction A can take position 41, transaction B position 42, and B commits first. A projector that reads 42 and saves it as the checkpoint will never see 41. Event store products handle this for you. On plain Postgres, common fixes are to read only up to positions older than all in-flight transactions (using
pg_snapshot_xmin, as some libraries do) or to serialise appends. Check how your library handles it before trusting position checkpoints.
Press Run (⌘ Enter) to see what happens.The rebuilt table is identical to the incremental one. That is the property to test: replaying from zero must give the same result as processing live. If it does not, your projection depends on something other than the events, such as the current time or a lookup in another table that has since changed.
You need to add a withdrawals column to a projection in production without downtime. Order the steps.
- Tap the steps below in the right order.
Living with projection lag
Eventual consistency becomes a product problem the moment a user clicks "Save" and the list does not show their change. Ways teams handle it:
- Return the result from the command. The command already knows the new state, so the UI updates optimistically from the response instead of re-reading.
- Wait for a version. The command returns version 3. The UI (or an API layer) polls the read model until it reports version 3 or a short timeout passes. This gives read-your-own-writes for the user who made the change.
- Say so. "Your transfer is processing" is honest and often fine. Banks have done this for decades.
- Read the aggregate for critical screens. The account owner's own balance page can load the stream directly; only lists and search use projections.
Monitor lag as a metric (head position minus checkpoint, or seconds behind) and alert on it. A stuck projector looks like "the site lost my data" to users.
Snapshots for long streams
A busy account might have 50,000 events. Folding all of them on every command is slow. A snapshot stores the folded state at some version, and loading becomes "latest snapshot, then only the events after it".
What does this print?
snapshot = {"version": 100, "balance": 4000}
events = [
(99, "Deposited", 500),
(100, "Withdrew", 300),
(101, "Deposited", 1000),
(102, "Withdrew", 2500),
]
balance = snapshot["balance"]
for version, kind, cents in events:
if version <= snapshot["version"]:
continue
balance += cents if kind == "Deposited" else -cents
print(balance)Snapshots are a cache, not a source of truth. You can delete them all and lose nothing but speed. Take one every N events (often a few hundred), or when loading gets slow, and include the snapshot schema version so a code change can invalidate old ones. Many teams never need snapshots: if streams stay short (an order has 10 to 30 events in its life), skip them. Long streams are often a sign the aggregate is too big or should be split by period, such as one stream per account per month.
Versioning events without rewriting history
Events are stored forever and must never be edited in place, because the whole value is that history is trustworthy. But your code changes. Strategies, from most to least common:
- Weak schema / tolerant reader. Only add optional fields, and readers ignore fields they do not know and default fields that are missing. Handles most changes.
- Upcasting. When reading, transform old event shapes into the current shape in code, before the aggregate or projector sees them. The stored bytes stay old.
- New event type. A meaning change gets a new name (
FundsDepositedalongside the oldDeposited), and handlers support both for a while. - Copy and transform. For a big restructure, write a new store by migrating every event, then switch over. Rare, expensive, and a last resort.
Press Run (⌘ Enter) to see what happens.Match each change to the versioning strategy that fits best.
Deleting personal data
"Never delete history" collides with privacy law. Under GDPR a user can ask to be erased, and you cannot edit events. The common answers:
- Keep personal data out of events. Store a
customer_idin the event and the name and address in a normal table you can delete from. - Crypto-shredding. Encrypt personal fields in events with a per-user key kept in a separate key store. To erase the user, delete the key. The events remain, but that data is now unreadable.
Decide this before the first event is written. Retrofitting it onto millions of events is a project in itself, and in regulated companies the legal and security teams will want to review the design.
When to use it, and when not to
Event sourcing has real costs: every query needs a projection, eventual consistency reaches the UI, events must be versioned forever, the team needs new skills, and fixing bad data means writing compensating events instead of an UPDATE. Debugging "why is this value wrong" moves from one row to a stream and a projector.
It pays off when:
- History is the product or a legal need: ledgers, payments, trading, insurance claims, medical records.
- Audit and "why" questions are frequent and expensive to answer today.
- Many read models from the same facts: dashboards, search, notifications, analytics, all built from one stream.
- Collaborative or long-running workflows where knowing who did what, in which order, drives the logic.
It is the wrong choice for most CRUD: a CMS, an admin panel, a settings page. A middle ground many teams take is a normal state-based model plus an audit log or outbox events: you get history for the parts that need it without making events the source of truth.
Tooling: KurrentDB (formerly EventStoreDB) is a dedicated event store database. Marten turns Postgres into an event store for .NET. Axon is the main framework in the Java world. For Python and TypeScript, small libraries (such as eventsourcing for Python or Emmett for Node) or a plain Postgres table like the one above are common. Check each project's current docs for status and licensing before choosing.
- CQRS
- Separating the model used for writes from the models used for reads, often with denormalised read tables kept current by events.
- event store
- An append-only table or database of events, grouped into streams, with a unique stream and version pair for concurrency.
- expected version
- The stream version a writer last saw; the append fails if another writer has added events since.
- projection
- A read model built by processing events in order, which can be deleted and rebuilt by replaying from the start.
- checkpoint
- The last global event position a projection has processed, saved so it can resume after a restart.
- snapshot
- A cached copy of an aggregate's folded state at a given version, so loading only replays later events.
- upcasting
- Transforming old event shapes into the current shape when reading, without changing stored events.