CQRS Pattern

One model for changing data, another for reading it. Know where the idea comes from, the three levels you can apply it at, and the consistency cost that comes with the second store.

Overview

Command Query Responsibility Segregation (CQRS) splits a system's model in two. Commands change state and return nothing; queries return data and change nothing. Instead of one set of classes that does both, the write side gets a model built for rules and validation, and the read side gets a model built for the shapes the screens need.

The name is Greg Young's. His *CQRS Documents* (2010) describe it as growing out of Bertrand Meyer's Command-Query Separation, a rule for single methods: a method either changes state or returns a value, never both. Young's step was to apply the split to whole objects, so that one object holds the commands and another holds the queries. Martin Fowler's 2011 bliki entry credits Young and adds a warning that most systems do not need it.

Interviewers bring CQRS up in two ways. In a design question they want to see whether you can name the trade-off (a read model that lags the write model) before they ask. In a low-level question they want the shape: a command handler, a query handler, and what carries changes from one side to the other.

From CQS to CQRS

The two ideas differ mainly in scale. Meyer's Command-Query Separation applies to one method, and its rule is that a method changes state or returns data, not both: account.deposit(10) returns nothing, and account.balance() changes nothing. It costs almost nothing. Young's CQRS applies to a whole model or service, and its rule is that commands go to a write model and queries to a read model: PlaceOrderHandler and OrderSummaryQuery are different classes, often with different data. Its cost is real, because there are now two models to keep in step.

Fowler keeps one exception to CQS worth quoting: popping a stack both changes it and returns a value, and that idiom is too useful to give up.

Interview questions

  • What problem does CQRS solve that a layered CRUD design cannot?
  • What are the trade-offs of CQRS?
  • Does CQRS require two databases or Event Sourcing?
  • A user places an order and refreshes at once. The order is missing. What do you do?
  • Commands should be task-based. What does that mean, and why does it matter?

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio