CQRS and Event Sourcing
CQRS (Command Query Responsibility Segregation) separates the model used to update data from the model(s) used to read it. Event sourcing stores every change to the state of a system as an immutable sequence of events, rather than storing only the current state.
The two are often used together but are independent. CQRS was described by Greg Young, building on Bertrand Meyer’s command-query separation principle.
The problem
A single data model has to serve two masters. Writes need to enforce business rules and consistency; reads need to be fast, varied and shaped for each screen or report. As a system grows, the one model ends up being a poor compromise for both, and read and write load can’t be scaled independently.
Separately, a database that stores only the current state has forgotten how it got there, which matters for audit, debugging and answering new questions about the past.
The solution
CQRS: commands go to a write model that validates them and records the change. Read models (often several, each optimised for a particular query) are updated from those changes, usually asynchronously via events. In the cloud, the write side might be a relational or key-value store, with read models in a search index, a cache or a denormalised table.
Event sourcing: instead of updating a row, append an event (ItemAddedToBasket, BasketCheckedOut) to an event store. Current state is derived by replaying events, or from snapshots. Any number of read models can be rebuilt from the event history at any time.
When to use it
- Read and write workloads are very different in shape or scale.
- The domain is genuinely complex and benefits from a write model focused purely on business rules.
- A full audit history is a requirement (finance, healthcare, regulated domains).
- You expect to need new views of historical data that you can’t anticipate today.
Trade-offs
These are powerful patterns with real costs, and we’ve seen them applied where a simple CRUD application would have been far better:
- Eventual consistency between the write and read sides, which the business and the UI have to accept.
- Complexity: more moving parts, more infrastructure and more concepts for the team to learn.
- Event versioning: events are stored forever, so changing their shape needs careful, versioned evolution.
- Replays take time as histories grow, which is why snapshots exist.
Most systems don’t need CQRS. The ones that do really need it.
Use the architectural profile: if data processing and functional complexity are low, these patterns will slow you down. Apply them to the parts of a system where complexity is genuinely high, not to the whole thing. See also Event-Driven Architecture.