Design patterns and optimization · Intermediate

Separate command and query responsibilities with CQRS

Use an order and lagging list projection to reason about authority, replay, progress, rebuilding and independence from event sourcing.

Ask Logeia about this articleTry the three questionsReview your answers

Updated

On this page
  1. Separate update rules from query representation
  2. Distinguish command acceptance from projected query results
  3. Handle duplication and ordering in the projection
  4. Design rebuilding as its own operation
  5. Compare with a conventional CRUD design
  6. Separate responsibilities before distributing storage
  7. Solve the stale-cancellation exercise
  8. Ask Logeia about this articleCheck your understanding

Separate update rules from query representation

Committing an order requires inventory and state-transition rules, while a list screen may want a joined summary optimized for reading. CQRS separates the responsibility of accepting changes from representing query results. Read replication and consistency first. It can let business rules and display needs evolve independently, but does not inherently require separate microservices or databases. Start from the boundary the application actually needs.

Commit order-7 on the write side and update the order-list projection later. Acceptance can succeed while the list temporarily omits the order. Specify whether the user sees the accepted result directly, waits for a projection position or sees processing state. Model separation does not automatically provide strong read-after-write behavior. A useful design describes permitted visible lag and its resolution instead of assuming every successful command immediately appears in every query model.

Distinguish command acceptance from projected query results

A command such as cancellation validates a transition against authoritative state. A query answers what to display. A stale projection saying cancellation is possible cannot replace write-side validation, and another action can occur between display and command. Keep invariant enforcement at the boundary authorized to decide it. The read model is not automatically the source of truth for accepting changes.

A command response may carry operation identity, committed state and a projection position. A query model behind that position can explicitly report lag. Sleeping one second does not prove catch-up under variable delay. Define which history the position belongs to, especially across shards, and connect it to the consumer's committed progress. Merely attaching a number does not establish that the projection processed the corresponding event. The response and progress contracts must agree.

Handle duplication and ordering in the projection

When creation, payment and cancellation update a list, duplicated creation must not increment counts twice. Commit projection updates with their processed identity or position where the local store permits it. The outbox/inbox histories explain why replay occurs. Blindly overwriting with last-arrived content can let a delayed creation revert a cancelled order. Define the ordering unit and treatment of older updates.

A single global event order is not always required. Per-order sequence may suffice, while aggregates across several streams need a more complex progress representation. Include missing events, replay and schema evolution in the projection contract. Equal total counts do not prove every order state is correct. Validate representative entity states together with committed progress. The separation creates a maintenance responsibility, not merely a faster query table.

StageWrite sideRead side
Creation committedOrder accepted, position 10Position 9, not yet visible
Projection catches upPosition 10Position 10, accepted visible
Cancellation just committedCancelled, position 11Position 10, temporarily stale

Design rebuilding as its own operation

Build a new empty projection from authoritative state or retained history, catch up and switch readers only after an explicit readiness condition. A generation prevents exposing a half-built model. Reusing old processed IDs can mistakenly discard the history needed by the new destination. Separate projection reconstruction from live business effects so replay does not resend payments or notifications.

CQRS is independent of event sourcing. The write side can store conventional current rows while change propagation or recomputation builds queries. Using an event history as the source of truth adds separate retention and evolution obligations. CQRS alone does not promise reconstruction of every historical state. Name the source that can rebuild the projection, treatment of gaps and cost of rebuilding under live demand. A derivable model still needs a tested derivation and a safe cutover.

Compare with a conventional CRUD design

If reads and writes have similar shape and ordinary indexes or views suffice, an asynchronous projection can add needless lag and operational cost. Compare representation needs, update frequency, freshness and rebuild cost rather than read volume alone. Replication also multiplies authorization and deletion responsibilities. Deleted personal data must not remain indefinitely in a forgotten read model. Performance does not remove those product contracts.

Observe command completion, projection lag, replay, poison events, generation progress and query duration separately. Fast queries returning days-old state may not meet the objective. Verify one post-write user history and the permitted stale outcomes. The replica-lag lab is a deterministic reflection/waiting model, not a database or network performance test. A concrete projection implementation still needs verification against its actual storage and propagation mechanism.

Separate responsibilities before distributing storage

Write tables and query views can share one database while exposing different command and query responsibilities. A separate asynchronous store is not required from the first implementation. This can avoid introducing propagation lag and another recovery system before they are needed. Equal database location still does not mean every independent query uses one shared snapshot; verify transaction and view semantics for the actual calls. Test the same immediate post-write user example under the chosen boundary. The simplest adequate CQRS design is determined by representation and invariant needs, not by how many infrastructure components appear in its architecture diagram.

Solve the stale-cancellation exercise

A projection at position ten shows accepted while authoritative position eleven is already cancelled. The command must validate against write-side rules and handle repeated cancellation safely, not apply stale display state as authority. Where useful, distinguish the accepted command result from projection catch-up in the user experience.

Does CQRS require event sourcing? No. Current authoritative rows can supply projections; choosing an append-only historical source is another decision. The learning outcome explains what commits, what is derived, how it catches up and how it rebuilds. Continue to event sourcing for the additional responsibilities introduced when the history itself becomes the source of truth.

Reading and practice are recorded separately in this browser, for each language.

Learn this in order

Understand the systems behind the web · STEP 17

Choose a learning path