Reads and writes are usually loaded differently: an online shop’s catalogue is browsed far more often than orders are placed, and screens need data in a shape the write model does not have. CQRS suggests keeping the two sides apart: writes and reads each have their own models and their own optimisations.
Where the term comes from
The split grew out of Bertrand Meyer’s CQS principle, formulated in the book “Object-Oriented Software Construction”: an object’s method either changes state or returns data, but never both at once. Greg Young proposed applying this separation to the system as a whole, and Martin Fowler, who first heard about the pattern from Young, described CQRS on his site in 2011.
How commands and queries work
| Side | Commands (writes) | Queries (reads) |
|---|---|---|
| What they do | change state: create an order, transfer money | return data and change nothing |
| Model | domain aggregates with business rules and invariants | flat objects shaped for specific screens and reports |
| Storage | a schema optimised for writes | materialised views, a cache and a search index |
The separation also works in a single application with a single database: it is enough to keep command handlers and queries in different modules. The full version means separate storage: commands write to the primary database, and events from it update the read model, such as a search index. The two sides can then be scaled independently, and the storage is chosen to suit each side’s job — writes in a relational database, for example, and reads in a document one. The read model lags behind writes by the delivery time: a reader may not see a change that has just been made straight away.
When to use it
CQRS pays off where the two sides diverge sharply: many users read and change the same data at the same time, writes and reads need different data structures, or the load is worth scaling separately. It is applied to individual bounded contexts, not to the system as a whole. The price is noticeable complexity: a second set of models, event delivery between the sides and eventual consistency. For most systems this complexity does not pay off.
Sources
the term is written from these pages- Martin Fowler — CQRS (bliki)martinfowler.com/bliki/CQRS.html(opens in a new tab)
- Martin Fowler — Command Query Separation (bliki)martinfowler.com/bliki/CommandQuerySeparation.html(opens in a new tab)
- Azure Architecture Center — CQRS patternlearn.microsoft.com/en-us/azure/architecture/patterns/cqrs(opens in a new tab)
Verified 8 Nov