Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 57 ยท Architectural and Modern Patterns

CQRS: Command Query Responsibility Segregation

Learn CQRS: split the write model from the read model, keep them in sync with events, and know the costs. Includes a runnable order example with a projection.

Most applications start with one model. A Product class validates input, saves to a table, and is also what the screens read from. That works well until the two jobs pull in different directions. Writes want strict rules, small transactions and normalized tables. Reads want fast, flat, pre-joined data shaped exactly like each screen: a dashboard row, a search result, a report. Every compromise that serves one job makes the other worse.

CQRS (Command Query Responsibility Segregation) answers by using two models: one for commands (change something) and one for queries (ask something). They can share a database, or each can have its own. This lesson builds the idea from the small principle underneath it up to a runnable example, and is honest about when it is too much.

CQS first: the small principle

Bertrand Meyer's Command-Query Separation (CQS) is a rule for single methods: a method either does something and returns nothing, or answers something and changes nothing. Asking a question should not change the answer.

JavaScript
// A command: changes state, returns nothing useful.
cart.addItem("book", 2);

// A query: returns data, changes nothing.
const total = cart.total();

A method like stack.pop() breaks CQS on purpose (it removes and returns), and that is fine; CQS is a guideline for clarity, not a law. CQRS lifts the same idea from methods to whole models: the code that handles commands and the code that handles queries are separate classes, often separate objects, sometimes separate services.

What CQRS looks like

flowchart LR
    UI["Client"] -->|"command: PlaceOrder"| CH["Command handler"]
    CH --> WM["Write model<br/>(rules, invariants)"]
    WM --> WS[("Write store")]
    WM -->|"event: OrderPlaced"| PR["Projection"]
    PR --> RS[("Read store<br/>(flat, query-shaped)")]
    UI -->|"query: OrdersByCustomer"| QH["Query handler"]
    QH --> RS

Commands go through the write model, which enforces the rules and publishes events; a projection turns those events into a read store that queries use directly.

The pieces:

  • Command: a message that expresses intent in the language of the business, such as PlaceOrder or CancelOrder. It can be rejected. It returns success or failure, not data.
  • Command handler: loads what it needs, applies the business rules in the write model, saves, and publishes what happened.
  • Write model: a model optimized for correctness. It holds the invariants (stock cannot go negative) and ignores how screens want data.
  • Query and query handler: a request for data, answered without side effects, straight from a store shaped for that question. There is no business logic and no domain objects, often just a dictionary or a SQL view.
  • Read model (projection): a denormalized copy built from the changes in the write side.

Because the read side contains no rules, you can scale it, cache it and reshape it freely. Because the write side ignores presentation, its model stays small and focused on behavior.

A runnable example

The example uses in-memory stores to show the flow. The write side validates and emits events. A projection keeps a read model of "totals per customer". Queries never touch the write model.

Node.js Commands, events and a read model

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The two rejected commands changed nothing, and the read side only ever saw the three accepted orders. The query is a plain lookup: no joins, no loops over orders, no domain objects.

Keeping the two sides in sync

When both models share one database, a projection can be a SQL view or an indexed table updated in the same transaction, and the read side is always current. When the read model lives in a different store (a search index, a cache, a document database), it is updated by events. That brings eventual consistency: for a short moment after a command succeeds, a query may still return the old data.

Node.js Eventual consistency in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Plan for this lag instead of fighting it. Common techniques: the command returns the new id so the client can show the result it already knows; the UI shows "processing" for a moment; the client reads from the write side for the user's own just-written data; or the system reads the read model but waits for a version number to catch up. Projections must also be idempotent, because a broker may deliver the same event twice.

CQRS and Event Sourcing

The two are often mentioned together, but they are independent. CQRS is about splitting models. Event Sourcing is about how the write side stores its data: as a list of events instead of current state. Event sourcing makes projections natural, since the events already exist, and that is why they pair well. You can use CQRS with an ordinary relational write store, and you can use event sourcing without separate read models.

When CQRS pays off, and when it does not

Use it when:

  • Reads and writes have very different load or shape, for example a few writes and thousands of dashboard reads per second.
  • Several screens need very different views of the same data.
  • The write rules are complex enough that a clean write model is worth protecting.
  • You already have event-driven integration and need read models for other services.

Skip it when:

  • The application is a simple create-read-update-delete form over tables. Two models double the code and add lag for no benefit.
  • The team is small and the domain is not yet understood. You can start with CQS inside one model and split later.
  • The business needs every read to reflect every write instantly, and you cannot tolerate lag.

Costs to weigh: more classes, more moving parts, harder debugging across the lag, and the need to rebuild a read model when its shape changes. Apply CQRS to the part of the system that needs it, not to the whole application. A common middle path is one database with a normalized write schema and a few read-only views or tables for heavy screens.

If you cannot say in one sentence which screen or load problem CQRS solves for you, you probably do not need it yet.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the rule of Command-Query Separation (CQS)?

    CQS is a per-method guideline: asking a question should not change the answer. CQRS applies the same split to whole models.
  2. 2. In CQRS, what does the read model contain?

    The read model is a denormalized, query-shaped store. The rules live on the write side.
  3. 3. A user places an order, then immediately reloads their order list and does not see it yet. What is the most likely cause in a CQRS system with a separate read store?

    When the read store is updated through events, there is a short delay between a successful command and the updated query result.
  4. 4. Which statement about CQRS and Event Sourcing is correct?

    CQRS splits read and write models; Event Sourcing stores changes as events. Either can be used without the other.
  5. 5. For which project is CQRS most likely a poor choice?

    For plain CRUD, two models only add code and lag. CQRS earns its cost when reads and writes truly differ.

Summary

  • CQS says a method either changes state or returns data; CQRS applies that split to whole models.
  • Commands go to a write model that enforces rules; queries go to a read model shaped for the screen.
  • A projection builds the read model from changes, usually by events, so reads can lag slightly (eventual consistency).
  • Make projections idempotent and design the UI for the lag.
  • CQRS is independent of Event Sourcing, though they combine well.
  • Use it where reads and writes truly differ; keep simple CRUD simple.

Next lesson: Event Sourcing.