Notesstream🌱 seedling
CQRS
Also: Command Query Responsibility Segregation · Read Model · Write Model · Projection
Use one model to change data (commands) and a different model, or several, to read it (queries). The read models are derived asynchronously from the write side, each shaped for the screen or API that queries it.
Why it exists
A model that enforces business rules on writes is rarely the shape that answers reads well. And replaying an event-sourced aggregate is a poor way to answer a list query.
How it works
- The command side validates commands against its rules and records the result: rows, or events with Event Sourcing.
- A projector consumes the changes (an event log or a Change Data Capture stream) and updates one or more read models, which are Materialized Views: denormalised, pre-joined, often in a different store.
- Queries go only to read models. Each side scales and evolves on its own.
- The projection is asynchronous, so reads are eventually consistent with writes.
Trade-offs
| Gains | Costs |
|---|---|
| read models shaped exactly for each query | two models, plus the projection code |
| independent scaling of reads and writes | stale reads right after a write |
| new read models added by replaying | more infrastructure and failure modes |
In practice
- Postgres plus CDC into Elasticsearch is CQRS without event sourcing, and probably the most common form of it.
- Read-after-write is handled by reading from the write model for a few seconds after a change, or by waiting until the projection reaches the write's log position (Read-Your-Writes Consistency).
Pitfalls
- Applying it to a whole system. It's widely advised for specific parts whose reads and writes really differ, since for most systems it adds risky complexity.
- Forgetting that a user who saves and reloads may not see their change.
Connections
- Part of
- Derived Data
- Learn first
- Materialized View
Recall
These cards are also in your review deck, scheduled with spaced repetition.