CQRS
medium 30 minCQRS means Command Query Responsibility Segregation.
Video lesson · Chapter 1 of 5
The ticket printer and the departures board
Theory
Read or listen first. About 2 min.
What it is
CQRS splits a system by responsibility. A command asks for a change: create this order, cancel that subscription. A query asks a question and changes nothing. Commands and queries use different models of the same business.
The write model is small and strict. It checks the rules and saves what happened. The read model is wide and simple. It holds answers that are ready to show, already joined and counted. Something in between, usually events, carries each change from the first to the second.
Why it exists
One model for both jobs is often a bad fit for both. Rules want small normalised tables and short transactions. Screens want a customer name, ten items and a total in one read. As the product grows, one side makes the other slow and complicated.
Many systems also read far more often than they write. With two sides, each can be scaled, stored and tuned on its own. The price is more parts and answers that may be slightly old, so it belongs only where those problems are real.
A short history
5 December 2005
Martin Fowler writes about command query separation and credits the term to Bertrand Meyer's book "Object Oriented Software Construction": a method either changes something or answers a question.
12 December 2005
Fowler publishes "Event Sourcing": keep every change as a sequence of events.
November 2010
Greg Young's "CQRS Documents" is uploaded. It treats commands, queries, and events as a storage mechanism.
14 July 2011
Fowler publishes a note on CQRS. The note credits Greg Young as the first source, and warns that for most systems it adds risky complexity.
Words to know
- Command
- A request to change state, named after an intent.
- Query
- A question that changes nothing.
- Aggregate
- A small group of objects that is changed as one and protects its rules.
- Domain event
- A fact in the past, such as OrderCreated. It never changes.
- Projection
- Code that turns events into a read model.
- Read model
- Data shaped for one kind of question. Also called a view.
- Event sourcing
- Storing the events as the truth, instead of the current state.
- Projection lag
- How far a read model is behind the writes.
How it works
Step through the idea, or press Play.
Command. Check the rules, change the write model
Understand it
Start here
The quest book and the posters
A village keeps its quests in one big book. A single clerk writes in it and checks every rule. If all adventurers had to read that book, the queue would never end. So two posters on the wall show the same quests, arranged the way people ask for them.
The posters can be torn down and drawn again from the book. The book cannot be drawn from a poster.
The idea
Two sides and an arrow between them
Commands above, queries below
Commands
Change state: create, update, cancel. Aggregates enforce the business rules.
Queries
Read and never modify. They use read models for fast answers.
Events
Published after a successful command. They update the read models.
Eventual consistency
A read model may be slightly behind. This is the trade for speed and scale.
Write side
What happens to a command
- 1
The command arrives
CreateOrder with a user, items and a total.
- 2
The handler checks it
It validates the input, checks permission and loads the right aggregate.
- 3
The aggregate decides
It checks the business rules, applies the logic and returns events.
- 4
Events are saved, then published
They are stored together in one transaction. OrderCreated is now a fact.
A command, step by step
Good commands
- Names that show intent: CreateOrder, ApproveApplication, CancelSubscription
- Immutable once created
- Based on a task the user does
- Validated before processing
- Return nothing, an id, or a version
Weak commands
- UpdateOrder with thirty optional fields
- Commands that return a full screen of data
- Rules hidden in the user interface
- Changing the read model directly
Read side
Read models and projections
The same order on both sides
| Write model, normalised | Read model, ready to show |
|---|---|
| Orders: id, user, total, status | Order view: id, user name |
| Order items: order, product, quantity | Items with name, quantity and price |
| Products: id, name, price | Total, status, created, shipping address |
| Read models | Projections |
|---|---|
| Already joined for one kind of question | Subscribe to events and update a view |
| Many views of the same data | Safe to run twice for the same event |
| Can be rebuilt if the history is kept | Can replay from the start to fill a new view |
One event, three views
Keep them in step
Three ways to synchronise
| Way | How | Good | Bad |
|---|---|---|---|
| Synchronous | Update the view in the same transaction | Immediately consistent | Slower writes, tight coupling, same database |
| Event-driven | Publish events; handlers update views | Loose coupling, scales | Eventual consistency |
| Scheduled | Copy or recompute at intervals | Simple | Minutes or hours behind |
Which one?
Living with lag
Handle eventual consistency
In the interface
- Show the change at once and confirm later
- Show a "processing" state
- Keep the new item in the client's cache
- Poll, or use WebSocket, for updates
In the backend
- Read your own writes: wait until the view reached your version, or read the write side
- Give each event a version and reject older ones
- Keep causal order: one partition per aggregate
- Resolve conflicts with a rule you wrote down
Read your own write
How late is a view?
Often together
Event sourcing is a separate choice
With event sourcing the events are the truth, and the current state is computed from them. It fits CQRS well, because you need views anyway. But CQRS works with ordinary tables too, and event sourcing has its own costs.
| CQRS with tables | CQRS with event sourcing | |
|---|---|---|
| Truth | Current rows | All events |
| History | Only if you add it | Complete |
| Rebuild a view | From the tables | Replay the events |
| Hard part | Publishing changes reliably | Changing event formats, deleting personal data |
Why snapshots exist
Decide
When it is worth it
Good fit
- Far more reads than writes
- Several views of the same data
- Reads and writes that must scale apart
- Event-driven systems
- Many people working on the same data
- Rich business rules
Poor fit
- Simple create, read, update, delete apps
- Screens that must be exact the moment after a write
- Small teams without time for more moving parts
- Simple data where a direct query is fine
- Decisions on prices or bids taken from a stale view
Grow into it
What you pay and what you get
| Amount | Why | |
|---|---|---|
| Development effort | High | Events, versions and eventual consistency |
| Operations effort | High | More stores, a broker, lag to watch |
| Scaling | Large gain | Each side on its own |
| Query speed | Large gain | No joins at read time |
Around it
Neighbours
With a database per service no join crosses the services, so a read model that listens to several of them is a common answer. The change itself may need a saga. How services talk is in microservice communication.
Summary
The whole topic in one minute.
CQRS uses one model to change and another to ask. Commands go to an aggregate that guards the rules and emits events. Projections turn the events into read models that answer queries without joins.
Read models are normally eventually consistent, so plan for lag: show the writer their own change, tell users when data is processing, and monitor the delay. Make projections idempotent and rebuildable. Event sourcing is a separate choice. Start with one model, then add a read model where a real query hurts.
- Commands change, queries ask, and each has its own model.
- Aggregates guard the rules and emit events.
- Projections build views; they must be idempotent and rebuildable.
- Views lag: plan for reading your own writes.
- Event sourcing is optional. Use CQRS where it pays, not everywhere.