System design · Read models, event logs, projections and replay
CQRS and event sourcing explained
CQRS gives writes and reads separate models, so each side gets the schema and store it needs. Event sourcing keeps every change as an immutable event and rebuilds state from that log. They pair well and cost a lot: lag between models, replays and event versioning. Use them where reads and writes truly differ or the history matters.
Updated · 5 min read
The short version
- CQRS splits the model that changes data from the models that answer queries, so each side gets the schema and store that suits it.
- Event sourcing stores every change as an immutable event and derives current state by replaying them.
- Read models update asynchronously, so a user can read a value older than their own write.
- Projections must be idempotent and replayable, because you will rebuild them after bugs and new reports.
- Most CRUD services need neither.
Clarifying questions to ask first
- How different are the read and write shapes? (Assume writes touch one order, while dashboards join orders, payments and shipments.)
- How stale may a read be? (Assume the order list can lag a second, but a user who just paid must see it.)
- Is the history itself a requirement? (Assume audit needs every payment state change, with who and when.)
- What are the rates? (Assume a steady 500 order events a second and 40,000 reads a second.)
Separate the write model from the read model
CQRS (command query responsibility segregation) gives commands and queries different models. A command such as PlaceOrder goes to a write model that checks the rules and records the change. Queries read from read models built for the screen that asks: a flat order summary table, a search index, a counter in Redis.
The split pays off when the two sides fight. The normalised schema that keeps writes correct makes the dashboard join five tables, and every index added for the dashboard slows every write. The price is a second model to keep in step, and a delay between them.
Event sourcing: the log is the record
With event sourcing the write side keeps no current row. It appends events such as OrderPlaced and PaymentCaptured to one stream per order, and rebuilds the order by folding its events in sequence. Events are never updated; a mistake is fixed by appending a correcting event, as in an accounting ledger.
Two commands can race on the same order. Append with an expected version: the store accepts the events only if the stream is still at the version the command read, and the loser retries on fresh state.
def place_order(store, order_id, command):
stream = f"order-{order_id}"
events, version = store.read_stream(stream)
order = fold(Order.empty(), events)
new_events = order.place(command)
store.append(stream, new_events, expected_version=version)Long streams get slow to fold. Save a snapshot every few hundred events and replay only what follows it.
Projections and the lag users notice
A projection reads the event log in order and updates a read model. It runs asynchronously, so read models trail the log by milliseconds normally and by minutes during a backlog or rebuild. Track projection lag as a first class metric.
The user who just paid and sees "unpaid" is the classic bug. Show the state the command returned, or make the read wait until the projection passes the event's position. Projections get events at least once, so store the last applied position in the same transaction as the read model update and skip anything at or below it.
Replays, versions and erasure
Replay is how you add or repair a read model: start a new projection at position zero and switch reads once it catches up. At a steady 500 events a second the log grows by 43.2 million events a day, about 15.8 billion a year. A projection applying 20,000 events a second needs about 9 days to replay that year, so plan for read model snapshots or parallel replay by stream.
Events outlive the code that wrote them. Version them and convert old shapes on read (upcasting). Immutability also collides with erasure requests: keep personal data out of events, or encrypt it with a key per user and delete the key.
When to skip both
Most services are CRUD plus a few reports, and a read replica or a materialised view fixes the read side for far less. Martin Fowler's article on CQRS warns that for most systems it adds risky complexity.
The patterns are independent. CQRS works with a plain database and an outbox to publish changes. Event sourcing without read models means querying by replaying streams, which works for one order and fails for any list.
Where it's used
- The precomputed home timelines in Twitter's timeline are a read model: fan out on write so a read is one lookup.
- Every status change in UPI payments goes to an append-only events table that reconciliation reads.
- A stock exchange matching engine replays its sequenced input log from a snapshot to rebuild the book after a crash.
Common traps
- Event sourcing a CRUD settings page. You pay for replay, versioning and lag, and get history nobody reads.
- Reading your own write from a projection and showing stale state.
- Projections that aren't idempotent. A redelivered event double counts a total.
- Saving to the database and publishing to a broker as two steps. A crash between them loses the event.
- Putting personal data straight into immutable events.
Follow-up questions interviewers ask
- "How do two buyers not both get the last item?" Append with an expected version; the second append fails and retries on fresh state.
- "How do you add a new report a year in?" A new projection replayed from position zero, read only after it catches up.
- "Is the event store just Kafka?" Not by default. It is the system of record, read per stream and kept forever, with a version check on append.
Frequently asked questions
What is CQRS?
+
Command query responsibility segregation: separate models for changing data and for reading it. Each side can use its own schema and store, at the cost of keeping read models in step.
What is the difference between CQRS and event sourcing?
+
CQRS splits reads from writes. Event sourcing stores changes as an append-only log of events instead of current rows. Each works without the other.
Is event sourcing eventually consistent?
+
The write side is consistent per stream, because each append checks the expected version. Read models built by asynchronous projections are eventually consistent.