CQRS: separate models for writing and reading
Two questions, two models
Section titled “Two questions, two models”Most systems answer questions and accept changes with the same model: the same tables, the same objects. That works until the two jobs pull apart. The screen that lists a customer’s orders wants one flat row per order, with the customer’s name, the total and the status. The code that places an order wants to validate rules across customers, products, stock and prices, in tables shaped to avoid duplicated facts.
CQRS, Command Query Responsibility Segregation, splits the one model into two. Martin Fowler, who credits Greg Young with the idea, puts it as using a different model to update information than the model used to read it. Commands change the data. Queries return it and never change it.
Mental model. One kitchen can cook the dishes and also answer “what is on table 7?”, but a restaurant that is busy gives the second job to a board that is kept up to date: cooking changes the state of the kitchen, and the board is built from it, in the shape the waiters need.
The Azure Architecture Center adds a point about naming. A command should carry a business intent, such as “book hotel room”, rather than a low-level update such as “set the reservation status to reserved”. The command is what the write model validates.
The same screen, two models
Section titled “The same screen, two models”Say the orders screen reads from a write model of five normalised tables: orders, order lines, customers, products and addresses. Showing one row of the list means joining all five. The read model keeps one flat row for each order.
| Write model (normalised) | Read model (one row per order) |
|---|---|
orders, order_lines, customers, products, addresses |
order_summaries(order_id, customer_name, placed_at, status, total, item_count, first_item_title) |
| Validates the rules, protects consistency | Answers the screen with a lookup by key |
| Shaped to avoid duplicated facts | Shaped for the question, with duplicated facts on purpose |
This is the denormalisation of the databases module, made into a part of the design: a read model is a materialized view, a prepared set of answers that is cheaper to read than to compute. The cost of a duplicated fact is that someone must keep it right, and that is the job of the arrow from the write side to the read side.
Two ways to build it
Section titled “Two ways to build it”Separate models over one store. The code is split into command handlers and query handlers with their own models, but both use one database. The read side can be a set of views or tables updated in the same transaction as the write. There is no lag. You get clearer models and queries that fit their screens, and you do not get independent scaling.
Separate stores, kept in step by events. The write model publishes an event when it commits, and a projection on the read side applies it to its own store. The read store can then use a different technology, a document or search store for example, and scale on its own. The Azure Architecture Center notes the catch: you cannot normally put a message broker and a database in one distributed transaction, so use a transactional outbox to save the change and the event together, and make the projection idempotent.
Fowler adds that in a CQRS system the two sides are often split into separate services that communicate through events. That is the event-driven lesson at work, and it is also why CQRS is so often confused with it. CQRS is not event sourcing either: you can have two models without a log of events, and the next lesson takes the log on its own.
Numbers for the orders screen
Section titled “Numbers for the orders screen”Say there are 10,000,000 orders. The screen is read 2,000 times a second and orders are placed 20 times a second, a ratio of 100 to 1.
- Size. A read row of about 0.5 KB makes the read model
10,000,000 × 0.5 KB, which is 5 GB. The cost of the second copy is real, and small beside the write model. - Read capacity. If one read node can serve 500 lookups a second, 2,000 reads a second need
2,000 / 500, which is 4 nodes. The write side carries 20 a second and is not touched. This is the scaling benefit that Fowler and the Azure Architecture Center name: read and write load scaled separately, which helps most when reads far outnumber writes. Read replicas of one database would also scale the reads. What the separate model adds is the shape. - Rebuilding. A read model is derived, so it can be dropped and rebuilt from the write side. If a projection applies 5,000 rows a second, 10,000,000 orders take
10,000,000 / 5,000, which is 2,000 s, or about 33 minutes. Ten projection workers in parallel take 200 s. Planning for a rebuild is part of owning a read model.
What it costs: a read side that lags
Section titled “What it costs: a read side that lags”When the stores are separate, the read model is updated after the write. Say the projection catches up about 200 ms after a commit, and the page redirect after “place order” takes 100 ms. The customer lands on My orders, and the new order is not in the list. Nothing is wrong: the read side is eventually consistent, as the Azure Architecture Center says. Say the 99th percentile of the delay is 2 s, a made-up figure. Then 1 order in 100 stays out of the list for more than 2 s.
This is the read-your-writes problem of the stale reads lesson, and there are three common ways to handle it.
- Answer from the write. The command’s reply returns the new order, and the page shows it without asking the read side.
- Read the user’s own recent changes from the write side for a short time after a change.
- Wait for a version. The command returns a version number, and the query waits until the read model has reached it, or gives up after a limit.
Each puts extra logic somewhere. The point is that the page must be designed knowing that the lag exists.
The second cost is duplicates and failures in the projection. A projection that adds each order’s amount to a day’s total will double-count a 40-euro order that is delivered twice, and the total is 40 wrong until someone notices. A projection that writes one row per order id, replacing it if it exists, gives the same result however many times the event arrives. This is the idempotent consumer again.
Check your understanding: CQRS
This quiz needs JavaScript to check your answers.
When it pays, and when it does not
Section titled “When it pays, and when it does not”Fowler is cautious. CQRS is suited to complex domains, and for most systems, he says, it adds risky complexity: many systems fit a CRUD mental model and should be built that way, and most of the cases he has met were not good ones. He advises using it on specific parts of a system, a bounded context in the vocabulary of domain-driven design, and not on the whole. If a few demanding queries are the problem, a reporting database that offloads them is simpler.
The Azure Architecture Center lists the cases where it fits: collaborative environments where many users change the same data, task-based interfaces, systems where read performance must be tuned apart from writes, especially when reads far outnumber writes, and evolving systems. It lists one case where it does not: when the domain and the rules are simple and a CRUD interface is enough.
A reasonable test is to ask three questions. Do reads and writes have clearly different load or shape? Can the user of this screen live with a delay of the kind described above? And is there a team that can run a second model and its projection? If the answer to any is no, one model is the better design.
The trade-off in one place
Section titled “The trade-off in one place”CQRS is not one of the four options of the explorer, but the same framework applies.
- Decision. Use one model to change data and another to read it, in one process over one store or in separate stores.
- Why? Reads and writes often differ in load and in shape, and a model that has to serve both is more complex than two that each serve one.
- Benefits. Read and write scaled apart. A read model shaped for the screen, with simple queries. Security applied separately to commands and to queries.
- Costs. Two models to build and keep in step, a projection to run, and the work of designing screens for a delay.
- Failure modes. The read model lags or falls behind. A duplicate event is applied twice. A bug leaves the read model wrong until it is rebuilt.
- Scaling limitations. The write side is unchanged, and the projection must keep up with its rate. A rebuild of a large read model takes time.
- Alternative. One model with read replicas or a reporting database, when the shape of the data is the same and only the read load is high.
What happens if the projection falls behind?
Section titled “What happens if the projection falls behind?”A bulk import writes 600,000 orders in 10 minutes, which is 1,000 a second. Normally the projection applies 5,000 rows a second and keeps up easily. Say that during the import it is slowed to 800 a second, because the database is also building an index. It falls behind by 1,000 − 800, which is 200 a second, and after the 10 minutes it is 120,000 events behind. The newest order reaches the read model after 120,000 / 800, which is 150 s, so support staff who look at it see statuses that are more than two minutes old. The write side is fine the whole time.
Nothing here corrupts data: the write model is still the source of truth, and the read model can be rebuilt. But a team that does not watch the lag of the projection finds out from its users. The rebuild of 33 minutes is the worst case to plan for, and the reason to keep the projection fast and idempotent.
- CQRS uses one model to change data (commands) and another to read it (queries). It is separate from event sourcing and does not need a broker.
- Two ways to build it: separate models over one store, with no lag, or separate stores kept in step by events, with a lag and the outbox and idempotency that come with it.
- For 10,000,000 orders read 2,000 times a second and written 20 times a second, the read model is 5 GB, needs 4 nodes at 500 reads a second, and rebuilds in about 33 minutes (200 s with ten workers).
- The read side lags: a 200 ms catch-up against a 100 ms redirect leaves the new order out of the list, and the page must answer from the write, read the write side, or wait for a version.
- Fowler advises caution: use it on a bounded context where reads and writes truly differ, not on a system whose model is plain CRUD.
Your progress
Built by GhaziAlibi.
© ShardCraft. All rights reserved.