CQRS and Event Sourcing
Separate read and write models, and store state as a log of events, for domains that truly need it.
Advanced · about 6 hours · difficulty 5/5
Learn first: Domain-Driven Design, Transactions, ACID and Isolation
These two patterns often appear together but are independent. Both are powerful and both add real complexity, so treat them as tools for specific problems.
CQRS
Command Query Responsibility Segregation splits the write model (commands that change state and enforce rules) from the read model (queries shaped for screens). The read side can be a denormalized table, a cache or a search index that is updated when the write side changes.
- Useful when reads and writes have very different shapes or loads, such as a dashboard aggregating data that is written in small transactions.
- A light version is common and cheap: separate query functions that bypass the domain model and read straight from optimized views.
- The heavy version, with separate databases, means reads are eventually consistent with writes.
Event sourcing
Instead of storing only the current state (balance = 70), you store every event that led to it (Deposited 100, Withdrew 30) in an append-only event store. Current state is derived by replaying events, usually accelerated with snapshots and projections (read models built from the event stream).
- Gains: a complete audit trail, the ability to rebuild read models or answer new questions about the past, and natural integration events.
- Costs: event schema evolution (old events live forever), harder queries, eventual consistency, and a steep learning curve.
When to use them
Finance, ledgers, compliance-heavy domains, collaborative editing and complex workflows. For a typical CRUD API, an audit log table plus well-designed queries gives most of the benefit.
Related
The transactional outbox pattern reliably publishes events after a database write without two-phase commit.
You are ready to move on when you can build a small event-sourced bank account with a projection for the current balance and explain how you would change an event's shape later.
Key concepts
- Commands vs queries
- Separate read models
- Event store and append-only logs
- Projections and snapshots
- Event versioning and upcasting
- Eventual consistency in the UI
- Transactional outbox
Mini project
Implement an event-sourced wallet: commands append events to a Postgres table, a projection maintains balances, and a rebuild script regenerates the projection from scratch.
Check yourself
What problem does event sourcing solve that a simple audit log table does not, and what new problem does it create?
Free resources
- CQRS (Martin Fowler)
- Event Sourcing (Martin Fowler)
- CQRS pattern (Microsoft Learn)