PatternChapter II · Styles & patterns · Building block 6 of 8

CQRS

CQRS separates models for changing state from models for reading. Both sides may be organised in accordance with their task.

  1. Command and QueryChanges command, query only reads.
  2. ProjectionTransfers changes to the read view.
  3. Subsequent reading viewShow new stands later.

Context

Why this is important

A universal model carries strict writing rules and convenient overviews poorly at the same time. Bertrand Meyer separated commands and queries as CQS; Greg Young coined CQRS. CQRS starts small, already with separate methods. The history as a storage form is its own building block, event sourcing.

This building block explains separate writing and reading models. For a complete event history as a storage form, see Event Sourcing.

At a glance · Write and read path separately

Commands run through the write model into the write memory, a projection fills the read memory, from which queries read through the read model.
Shop example · Stages of separation

How far apart are you?

Order checks status transitions in the writing model. The customer service reads a flat overview with payment, shipping and invoice number.

This is how you read the picture

  1. Command and Query At each level, the track "Change" with command and the track "Read" with query.
  2. Projection Stage 3: Box “projection” between writing model and read memory.
  3. Subsequent reading view According to the command: customer service shows “paid”, writing model “shipped”.

A model, but commands and queries are separate methods.

Changes

  1. Commander
  2. Order model
  3. Database

Read more

  1. Questions
  2. Order model
  3. Database
Additional parts
None
Delay
None
Reading form
Reading form fits partly

Change commands, read queries only. Both use the same order model; the reading form remains that of the writing model.

Choose a level; on level 3 Trigger a command and see when the reading view will follow.

Same order B-1042 in two models

Same order B-1042 in two models
FieldWriting model OrderReading customer service
IdentityB-1042B-1042 With customer name
Order linesP-7, quantity 2, agreed price, rulesshort list: 2 x cup, 49,90 €
Statusallowed transitions, e.g. B. ConfirmedTotal legible status
Payment and dispatchonly references, e.g. B. P-731merged status, invoice number
ChangesCommand with validationNo business change
Updateis immediately writtenFollows the writing model after a while
Compare per line: The writing model protects rules, the reading view shows the finished.

Benefits & limitations

Helps if:

  • Separate models can express different requirements for write rules and query shapes.
  • Separately measured read and write loads can be optimised independently through suitable models.
  • A read model combines information for queries while the write invariant remains in the change model.

Boundaries

  • For simple queries, two models double the maintenance burden; start with level 1.
  • The read view may be stale; authoritative decisions such as cancellation must use the write model's state. See Consistency.
  • Projections must be rebuildable; test rebuilding and reconciliation.

In practice

  1. Separate command and query contracts according to their effect. Commands check rules and change state; queries read a tailored view and receive no writing responsibility.
  2. Introduce separate models gradually and measure which access patterns benefit. A separate data store is an additional operational decision; CQRS can also use shared storage.
  3. Show a projection's freshness and make rebuilding it testable. Event Sourcing addresses historical storage; Consistency Models describes visibility.
Read the detailed explanation

A Command requests a state change and is checked against business rules. A Query reads information without changing state. CQRS separates these responsibilities and lets each model reflect its own task.

The separation can start within one module and database. A projection or separate data store is an additional choice that needs its own update and rebuild rules. Read models may lag behind the write model; their freshness is part of the visible contract.

Event Sourcing makes an event history the write-side source of truth. CQRS can instead use separate read and write models with ordinary state storage. Consistency Models describes the freshness of a read view.

Check your understanding

Test yourself in three stages

  1. ReadingCheck in the picture

    Stage 3, command triggered, projection not yet run: What show writing model and reading view customer service for B-1042?

    View the solution with justification

    The writing model shows “sent”, the reading view still “paid”. It is obsolete until the projection has passed through.

  2. ApplyingTransferred to a new situation

    The customer service wants to see the invoice number in the overview. Which side do you add?

    View the solution with justification

    The Read Page: Add field in the Read view and adjust the projection. The writing model remains unaffected as long as no business rule needs the number.

  3. EvaluateWeighing an alternative

    A team immediately jumps to stage 3, although reading and writing of the order are very similar. How do you rate that?

    View the solution with justification

    Advantage: free reading form and separate scaling. Disadvantage: projection, read memory, delay and reconstruction must be maintained. Recommendation: for similar forms with stage 1 start and only further separate when there is a demonstrable need.

Explore further

These optional deepenings complement the learning goal of this page.

API Composition

API Composition queries several responsible services at runtime and combines their responses to answer a query. A prepared read model instead holds a projected view updated before the request. Runtime composition avoids another projection but may make response time and availability depend on several services. A read model speeds up specific queries but requires update and rebuild rules. Both approaches can fulfil CQRS read contracts.

For testingCompare query paths. Choose a specific shop overview, identify its required sources and compare runtime composition with a precomputed read model. Record response time, failure behaviour, freshness guarantees and the effort needed to update or rebuild it.