LESSON 21.2
Event sourcing and CQRS
Store the history of changes instead of the current state, build read models from it, and know when that's worth the complexity.
5 min read
Most databases store the current state: the balance is 120. Event sourcing stores what happened: opened, deposited 100, deposited 50, withdrew 30. The state is derived by replaying those events.
Event sourcing
- A command arrives: withdraw 30 from account 42.
- Load the account's events (or the latest snapshot plus later events) and rebuild its state.
- Check the business rules against that state. Balance 150, so the withdrawal is allowed.
- Append a MoneyWithdrawn event to the account's stream, expecting the version you loaded. If someone else appended first, retry.
Events are immutable facts named in the past tense. You never update or delete them; corrections are new events, such as a reversal.
What you gain
- A full audit trail for free, which is valuable in finance, healthcare and anywhere regulators ask who changed what and when.
- Time travel: rebuild state as of any moment to debug or answer questions after the fact.
- New read models from old history: a new report or projection can be built by replaying every event ever stored.
CQRS
Command Query Responsibility Segregation splits the write side from the read side:
The write model is small and focused on enforcing rules. Read models are denormalized for specific screens: an account summary in Postgres, a search view in Elasticsearch, a leaderboard in Redis. CQRS works without event sourcing (read models fed by CDC), but the two often go together.
What it costs
State-based (CRUD)
- Familiar
- Simple queries
- Easy schema changes
- History is lost unless you add audit tables
Pick it when: Most applications.
Event sourcing + CQRS
- Complete history
- Read models per use case
- Natural fit for event-driven systems
- Read models lag writes
- Event schemas are forever
- Steeper learning curve
- Replays and snapshots to manage
Pick it when: Domains where history is the product: ledgers, orders, collaborative documents.
Try it
Event-sourced Aggregate Service HLD
Build an event-sourced aggregate with snapshots and projections.