Sub topic 14
Event sourcing and CQRS: related but separate ideas
This chapter assumes you know what an event is, how a broker delivers it, and why consumers see data with some delay (eventual consistency). Two patterns often appear next to event-driven systems and get confused with them and with each other: event sourcing and CQRS. Neither requires the other, and neither requires a broker.
Event sourcing: events as the source of truth
Most systems store current state. An account row holds balance = 125, and each update overwrites the previous value. Event sourcing stores the sequence of events instead: AccountOpened, Deposited(100), Deposited(25). The current state is computed by replaying those events in order.
The event log is append-only. You never edit or delete a past event. To correct a mistake, you append a new event, such as DepositReversed.
events = [
{"type": "AccountOpened", "account": "acct-1"},
{"type": "Deposited", "amount": 100},
{"type": "Deposited", "amount": 25},
{"type": "Withdrawn", "amount": 40},
]
def balance_from(events):
balance = 0
for e in events:
if e["type"] == "Deposited":
balance += e["amount"]
elif e["type"] == "Withdrawn":
balance -= e["amount"]
return balance
print(balance_from(events)) # 85What you gain is a full history, the ability to rebuild state after a bug fix, and the ability to build new views from old events. What you pay is more work to query current state, and a need to keep old event formats readable forever (see the schema chapter).
Do not confuse this with ordinary event-driven messaging. A system can publish events to a broker while storing state in normal tables. That is event-driven but not event-sourced. Here the event store is the database.
CQRS: separate models for writing and reading
CQRS stands for Command Query Responsibility Segregation. It splits a system into two sides:
- The command side validates commands and changes state.
- The query side serves reads from a model shaped for the screens or APIs that need it.
The two sides can share one database, or use different ones. When they use different stores, something must copy changes from the write side to the read side. Events are a natural way to do that, and the read side is then eventually consistent.
read_model = {} # account -> balance, shaped for fast lookup
def project(event):
acct = event["account"]
delta = event["amount"] if event["type"] == "Deposited" else -event["amount"]
read_model[acct] = read_model.get(acct, 0) + delta
for e in [
{"type": "Deposited", "account": "acct-1", "amount": 100},
{"type": "Withdrawn", "account": "acct-1", "amount": 40},
]:
project(e)
print(read_model["acct-1"]) # 60The function project is a projection: it turns events into a read-friendly view. You can have many projections from one stream, and you can rebuild any of them by replaying events.
How they relate
Event sourcing and CQRS fit together well, because an event store is awkward to query directly and projections solve that. But you can use CQRS with plain tables, and event sourcing with a single read path.
| Pattern | Question it answers | Needs the other? |
|---|---|---|
| Event sourcing | How do we store state? | No |
| CQRS | How do we separate writes from reads? | No |
Common errors
- Adopting both patterns by default. Each adds cost, so use one only when its benefit is clear, such as audit history or very different read and write shapes.
- Expecting reads to reflect a write instantly when the read model is updated asynchronously.
- Editing past events instead of appending corrections.
- Replaying events through handlers that have side effects, such as sending emails again.
Exercise
A team stores orders in normal tables and publishes an order.placed event to a broker after each change. Is this event sourcing? Why or why not?
Show answer
No. The tables hold the source of truth, and the events are notifications about changes. In event sourcing, the append-only event log is the source of truth, and current state is derived by replaying it.
Exercise
Your read model is built by a projection from an event stream, and a bug made it show wrong totals. How does an event-sourced design help you fix it?
Show answer
Fix the projection code, discard the read model, and replay the stored events through the corrected projection to rebuild it. The events are unchanged, so the rebuilt view is correct.