Sub topic 14
Event sourcing and CQRS: related but separate ideas
This chapter assumes you know the earlier chapters: what an event is, how a broker delivers it, why consumers must be idempotent, and what eventual consistency means. You should also be comfortable with database transactions and basic Python.
Event sourcing and CQRS often appear together in talks and diagrams, so many people treat them as one pattern. They solve different problems. You can use either without the other, and most systems that use events need neither.
Two definitions
Event sourcing is a way of storing state. Instead of keeping the current state of an entity in a row and overwriting it, you store the sequence of events that happened to it. The current state is computed by replaying those events.
CQRS (Command Query Responsibility Segregation) is a way of structuring a model. You use one model to handle commands, which change state, and a separate model to answer queries, which read state. The two models can use different code, different schemas, and even different databases.
| Question | Event sourcing | CQRS |
|---|---|---|
| What does it decide? | How state is stored | How reads and writes are separated |
| Core idea | Store the history, derive the state | Different models for writing and reading |
| Needs events? | Yes, they are the storage format | No, but events are a common way to feed the read side |
| Can be used alone? | Yes | Yes |
A system that uses CQRS with an ordinary relational write model is common. Its write side updates tables and publishes events through an outbox, and a projector builds a denormalized read table from those events. Nothing in it is event sourced.
Event sourcing: the working model
In a conventional design, a withdrawal runs UPDATE accounts SET balance = balance - 30. The old balance is gone. In an event-sourced design you append a withdrawn event to the account's stream. Nothing is updated or deleted.
The command side follows a fixed cycle:
- Load the events for one entity, called a stream (for example, all events for
acct-1). - Replay them to rebuild the current state.
- Check the business rules against that state.
- Append the new events, but only if no one else appended in the meantime.
Step 4 is optimistic concurrency. The writer says "append these events, expecting the stream to have N events." If the stream has more, the append fails and the command is retried or rejected. This replaces the row lock you would take in a conventional design.
from dataclasses import dataclass
@dataclass(frozen=True)
class Event:
type: str
data: dict
def apply(balance, event):
if event.type == "deposited":
return balance + event.data["amount"]
if event.type == "withdrawn":
return balance - event.data["amount"]
raise ValueError(f"unknown event type: {event.type}")
class EventStore:
def __init__(self):
self._streams = {}
def load(self, stream_id):
return list(self._streams.get(stream_id, []))
def append(self, stream_id, events, expected_version):
stream = self._streams.setdefault(stream_id, [])
if len(stream) != expected_version:
raise RuntimeError("concurrency conflict")
stream.extend(events)
class Account:
def __init__(self, history):
self.version = len(history)
self.balance = 0
for event in history:
self.balance = apply(self.balance, event)
def withdraw(self, amount):
if amount > self.balance:
raise ValueError("insufficient funds")
return [Event("withdrawn", {"amount": amount})]
store = EventStore()
store.append("acct-1", [Event("deposited", {"amount": 100})], expected_version=0)
account = Account(store.load("acct-1"))
new_events = account.withdraw(30)
store.append("acct-1", new_events, expected_version=account.version)
print(Account(store.load("acct-1")).balance) # 70Two things to notice. The business rule (insufficient funds) runs against state rebuilt from history, and the store never modifies an existing event. Events in an event-sourced store are the source of truth, not a notification sent after the fact.
What you gain
- A complete audit trail, because the history is the data.
- The ability to answer "what did the state look like last Tuesday?" by replaying up to that point.
- New read models built later from old events, which is hard to do when you only kept current state.
What it costs
- Replaying long streams is slow. Systems take periodic snapshots, which store the computed state at version N so replay starts from there.
- Events are permanent. A bug in what you recorded cannot be fixed by editing a row. You append a correcting event instead.
- Event schemas live forever, so the versioning rules from the schema chapter apply to your whole history, not only to messages in flight.
- Deleting personal data, for example under privacy law, conflicts with an append-only log. Teams work around it by encrypting personal fields per user and discarding the key, or by keeping personal data outside the events.
CQRS: the working model
CQRS starts from the observation that reads and writes often want different shapes. A write model protects invariants and is usually normalized. A read model serves screens and is often flat, denormalized, and shaped per view.
With CQRS you build the read side as a projection. A projection is a consumer that listens to events and updates a query-optimized store.
from collections import defaultdict
def project(events_by_stream):
"""Build a read model: current balance and transaction count per account."""
view = defaultdict(lambda: {"balance": 0, "transactions": 0})
for stream_id, events in events_by_stream.items():
for event in events:
row = view[stream_id]
sign = 1 if event.type == "deposited" else -1
row["balance"] += sign * event.data["amount"]
row["transactions"] += 1
return dict(view)
# Reusing the Event class from the previous example
history = {
"acct-1": [
Event("deposited", {"amount": 100}),
Event("withdrawn", {"amount": 30}),
],
}
print(project(history)) # {'acct-1': {'balance': 70, 'transactions': 2}}This code is a standalone sketch of the idea and needs the Event class from the previous listing. A production projector would run as a consumer of a broker. It would be idempotent, store its position in the event stream, and update a database table or search index.
Because the read side is fed asynchronously, it is eventually consistent. A user who submits a command and immediately queries may see old data. That is the same trade-off covered in the eventual consistency chapter.
Using them together
The combination is natural. The event store is a perfect source for projections, and CQRS gives you somewhere to answer queries, which a pure event store handles badly. Querying "all accounts with a balance over 1000" by replaying every stream is impractical.
Rebuilding is the main operational benefit. If you need a new view, you create a new projector and replay the full history into a new store. Switching over is a deployment step, not a data migration.
Common errors
- Treating them as a package. Teams adopt event sourcing to get CQRS, or the reverse. Decide on each separately, based on the problem it solves.
- Confusing event sourcing with publishing events. A service that stores state in a table and publishes
order.placedis not event sourced. The table is the source of truth there. - Querying the event store for reads. The event store is optimized for appending and loading one stream. Use projections for everything else.
- Non-deterministic replay. Applying an event must depend only on the event and prior state. If
applyreads the clock, calls another service, or generates random IDs, replay produces different results. Compute those values when handling the command and record them in the event. - Events shaped like table updates. An event named
AccountRowUpdatedwith changed columns carries no business meaning. PreferMoneyWithdrawn,AddressChanged, orOrderCancelled. - Ignoring read lag in the user interface. If a user submits a form and lands on a page that reads stale data, they think the action failed. Return the new state from the command, route to a page that waits for the projection, or show a pending marker.
- Using it everywhere. Both patterns add moving parts. Apply them to the parts of the system where history or divergent read shapes matter.
When each one is worth it
Consider event sourcing when the history has business value, such as ledgers, compliance records, or workflows where you must explain how a state came about. Consider CQRS when read and write loads or shapes differ sharply, or when many different views of the same data exist. If a plain table with an updated_at column and an audit log table meets your needs, use that.
Exercise
A team stores orders in a relational table. On every status change, they update the row and publish an order.status_changed event through an outbox. A new service builds a search index from these events. Is this event sourcing, CQRS, both, or neither? Explain.
Show answer
It is CQRS-style (a separate, event-fed read model for search) but not event sourcing. The source of truth is the orders table, and the events are notifications derived from it. In an event-sourced system the stored event stream would be the source of truth, and the order's state would be rebuilt by replaying it.
Exercise
In the event-sourced Account example, why does append take an expected_version, and what happens if two withdrawals run at the same time against the same account?
Show answer
expected_version implements optimistic concurrency. Both commands load the stream at the same version and validate against the same balance. The first append succeeds and the stream grows. The second append finds a different length and raises a concurrency conflict. That command must then reload the stream, re-check the rules against the new balance, and retry or be rejected. This prevents the two withdrawals from jointly overdrawing the account.