Bookmarks

CQRS — command query responsibility segregation

A design pattern that splits a system’s operations into commands that change data and queries that read it — with a separate model for each side.

Also: CQRS pattern

checked 8 Nov

All terms

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

SideCommands (writes)Queries (reads)
What they dochange state: create an order, transfer moneyreturn data and change nothing
Modeldomain aggregates with business rules and invariantsflat objects shaped for specific screens and reports
Storagea schema optimised for writesmaterialised 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

Verified 8 Nov

Not to be confused with

what it is mixed up with and how it differs

  • event sourcing

    CQRS separates the write and read models, while event sourcing stores state as a chain of events; they are often used together, but each also works on its own.

In depth in the references

where the topic is covered in detail