Course map

Topic 155 / Advanced

CQRS

Chapter 9.5 · Data Patterns and Evolution

What and why

Once a service's data is its own (→ 146), its read traffic and write traffic often have very different shapes — many simple reads of denormalized views, versus a smaller number of writes enforcing rich business rules — and forcing both through one model means every read pays for the write model's complexity, or every write pays for the read model's denormalization. CQRS (Command Query Responsibility Segregation) separates the write model (commands, business rules, source of truth) from one or more read models (queries, shaped for how they're actually read), kept in sync by events. Builds on: → 113 (event-driven architecture — the usual way the read model stays in sync).

Diagram

Write side                              Read side
──────────                              ─────────
Command ──► [Write model]               [Read model 1] (e.g., search-shaped)
            (enforces business          [Read model 2] (e.g., dashboard-shaped)
             rules, is the source             ▲
             of truth)                        │ events (→113) keep read
                  │                            │ models updated, asynchronously
                  └──── publishes events ──────┘

How it works

  1. Keep one write model that enforces all business rules and is the single source of truth for correctness.
  2. Model one or more read models separately, each shaped for a specific query need (search, a dashboard, a report) — denormalized, pre-joined, however the read is fastest.
  3. On every write, publish an event (→ 113) describing what changed.
  4. Each read model's own process consumes those events and updates its own storage — which can even be a different database technology suited to that read pattern (→ 62).
  5. Reads go straight to the read model, never through the write model — accept that the read model lags the write model by however long the event takes to arrive and apply (eventual consistency, → 129).
  6. Pair with event sourcing (→ 120) when the write model's own history, not just its current state, matters — but CQRS does not require it; a normal write model with a published change event is enough.

Practical example

(illustrative). An order-management write model enforces rules (can't cancel a shipped order, can't exceed inventory) and is the only place that rejects invalid commands. A separate "order search" read model, updated from OrderPlaced/OrderCancelled events, is a flat, denormalized table built purely for fast full-text and filter queries — it would be painful to query that same shape out of the normalized write model, and painful to enforce business rules against the denormalized shape.

When to use it

  • Use when: read and write workloads have genuinely different shapes or scaling needs, and one model is visibly straining to serve both (slow reports against a transactional schema, or a transactional model bloated with report-only fields).
  • Avoid when: one model serves both sides acceptably — which is most systems, most of the time; CQRS adds a second model, an event pipeline, and a staleness window to reason about.
  • Failure scenarios: the read model falling behind during an event backlog, so users see out-of-date data with no indication it's stale; treating CQRS as a default architecture rather than a response to a measured strain, multiplying complexity for no benefit.
  • Simpler alternative: a read replica (→ 72) or an indexed view against the same write model covers most "reads are slow" problems without a second model or an event pipeline — try that first.

Practice

(Pattern kind — implement minimal; 25 min, shared lab: Postgres + Kafka). Build a write model (a Postgres orders table with a create/cancel command) that publishes OrderPlaced/OrderCancelled to a Kafka topic. Build a separate read model: a consumer that maintains a denormalized order_search table (or a Redis hash) from those events. Confirm a query against order_search never touches the orders table, and measure the lag between a write and the read model reflecting it.

Done when you can state the actual measured lag between write and read-model visibility, not an assumed number.

Shared lab setup

Key takeaway

CQRS separates the write model from the read model(s), synchronized by events — justified only when read and write needs have genuinely diverged. Done when you can: decide, for a stated workload, whether CQRS or a simple read replica is the right fix. Used next in → 156 (strangler fig — another pattern for running two models side by side during migration).

References

A pattern language for microservices — see references.md.

Source directory

Search the guide