AlgoViz

CQRS

medium 30 min

CQRS means Command Query Responsibility Segregation.

Video lesson · Chapter 1 of 5

The ticket printer and the departures board

0:00 / 3:20

Theory

Read or listen first. About 2 min.

What it is

CQRS splits a system by responsibility. A command asks for a change: create this order, cancel that subscription. A query asks a question and changes nothing. Commands and queries use different models of the same business.

The write model is small and strict. It checks the rules and saves what happened. The read model is wide and simple. It holds answers that are ready to show, already joined and counted. Something in between, usually events, carries each change from the first to the second.

Why it exists

One model for both jobs is often a bad fit for both. Rules want small normalised tables and short transactions. Screens want a customer name, ten items and a total in one read. As the product grows, one side makes the other slow and complicated.

Many systems also read far more often than they write. With two sides, each can be scaled, stored and tuned on its own. The price is more parts and answers that may be slightly old, so it belongs only where those problems are real.

A short history

  1. 5 December 2005

    Martin Fowler writes about command query separation and credits the term to Bertrand Meyer's book "Object Oriented Software Construction": a method either changes something or answers a question.

  2. 12 December 2005

    Fowler publishes "Event Sourcing": keep every change as a sequence of events.

  3. November 2010

    Greg Young's "CQRS Documents" is uploaded. It treats commands, queries, and events as a storage mechanism.

  4. 14 July 2011

    Fowler publishes a note on CQRS. The note credits Greg Young as the first source, and warns that for most systems it adds risky complexity.

Words to know

Command
A request to change state, named after an intent.
Query
A question that changes nothing.
Aggregate
A small group of objects that is changed as one and protects its rules.
Domain event
A fact in the past, such as OrderCreated. It never changes.
Projection
Code that turns events into a read model.
Read model
Data shaped for one kind of question. Also called a view.
Event sourcing
Storing the events as the truth, instead of the current state.
Projection lag
How far a read model is behind the writes.

How it works

Step through the idea, or press Play.

Step 1 of 3

Command. Check the rules, change the write model

Understand it

Start here

The quest book and the posters

A village keeps its quests in one big book. A single clerk writes in it and checks every rule. If all adventurers had to read that book, the queue would never end. So two posters on the wall show the same quests, arranged the way people ask for them.

One book to write, two posters to read
By townBy rewardQuest bookA new quest

The posters can be torn down and drawn again from the book. The book cannot be drawn from a poster.

The idea

Two sides and an arrow between them

Commands above, queries below

Users send commands to the command side, a box with a handler and a write database. Events go through an event broker to a projection in the query side, which fills a read database. A query handler in the same box answers the users' queries from the read database.
Commands never touch the read database, and queries never touch the write database.
  • Commands

    Change state: create, update, cancel. Aggregates enforce the business rules.

  • Queries

    Read and never modify. They use read models for fast answers.

  • Events

    Published after a successful command. They update the read models.

  • Eventual consistency

    A read model may be slightly behind. This is the trade for speed and scale.

Write side

What happens to a command

  1. 1

    The command arrives

    CreateOrder with a user, items and a total.

  2. 2

    The handler checks it

    It validates the input, checks permission and loads the right aggregate.

  3. 3

    The aggregate decides

    It checks the business rules, applies the logic and returns events.

  4. 4

    Events are saved, then published

    They are stored together in one transaction. OrderCreated is now a fact.

A command, step by step

The version check stops two commands from changing the same aggregate at once.

Good commands

  • Names that show intent: CreateOrder, ApproveApplication, CancelSubscription
  • Immutable once created
  • Based on a task the user does
  • Validated before processing
  • Return nothing, an id, or a version

Weak commands

  • UpdateOrder with thirty optional fields
  • Commands that return a full screen of data
  • Rules hidden in the user interface
  • Changing the read model directly

Read side

Read models and projections

The same order on both sides

Write model, normalisedRead model, ready to show
Orders: id, user, total, statusOrder view: id, user name
Order items: order, product, quantityItems with name, quantity and price
Products: id, name, priceTotal, status, created, shipping address
The read model repeats data on purpose. Copying the product name means that the view keeps the name at the time of the order.
Read modelsProjections
Already joined for one kind of questionSubscribe to events and update a view
Many views of the same dataSafe to run twice for the same event
Can be rebuilt if the history is keptCan replay from the start to fill a new view

One event, three views

Each view keeps its own position in the stream of events. One may lag while the others are current.

Keep them in step

Three ways to synchronise

WayHowGoodBad
SynchronousUpdate the view in the same transactionImmediately consistentSlower writes, tight coupling, same database
Event-drivenPublish events; handlers update viewsLoose coupling, scalesEventual consistency
ScheduledCopy or recompute at intervalsSimpleMinutes or hours behind
Event-driven is the usual choice. Change data capture is a way to produce the events from the database log, and it runs continuously.

Which one?

Living with lag

Handle eventual consistency

In the interface

  • Show the change at once and confirm later
  • Show a "processing" state
  • Keep the new item in the client's cache
  • Poll, or use WebSocket, for updates

In the backend

  • Read your own writes: wait until the view reached your version, or read the write side
  • Give each event a version and reject older ones
  • Keep causal order: one partition per aggregate
  • Resolve conflicts with a rule you wrote down

Read your own write

Give the wait a short limit. After it, answer from the write side or show "processing".

How late is a view?

lag=events waitingevents handled per second−events arriving per second=9,000500−200=30 s\text{lag} = \frac{\text{events waiting}}{\text{events handled per second} - \text{events arriving per second}} = \frac{9{,}000}{500 - 200} = 30\ \text{s}
The time to catch up after a pause. If events arrive faster than they are handled, the lag grows without end.

Often together

Event sourcing is a separate choice

With event sourcing the events are the truth, and the current state is computed from them. It fits CQRS well, because you need views anyway. But CQRS works with ordinary tables too, and event sourcing has its own costs.

CQRS with tablesCQRS with event sourcing
TruthCurrent rowsAll events
HistoryOnly if you add itComplete
Rebuild a viewFrom the tablesReplay the events
Hard partPublishing changes reliablyChanging event formats, deleting personal data

Why snapshots exist

2,000 events×0.05 ms=100 ms100×0.05=5 ms with a snapshot every 1002{,}000\ \text{events} \times 0.05\ \text{ms} = 100\ \text{ms} \qquad 100 \times 0.05 = 5\ \text{ms with a snapshot every 100}
Assume 0.05 ms to apply one event. A snapshot saves the state now and then, so that at most 100 events must be replayed.

Decide

When it is worth it

Good fit

  • Far more reads than writes
  • Several views of the same data
  • Reads and writes that must scale apart
  • Event-driven systems
  • Many people working on the same data
  • Rich business rules

Poor fit

  • Simple create, read, update, delete apps
  • Screens that must be exact the moment after a write
  • Small teams without time for more moving parts
  • Simple data where a direct query is fine
  • Decisions on prices or bids taken from a stale view

Grow into it

Use it in the part that needs it, never for the whole system at once.

What you pay and what you get

AmountWhy
Development effortHighEvents, versions and eventual consistency
Operations effortHighMore stores, a broker, lag to watch
ScalingLarge gainEach side on its own
Query speedLarge gainNo joins at read time

Around it

Neighbours

With a database per service no join crosses the services, so a read model that listens to several of them is a common answer. The change itself may need a saga. How services talk is in microservice communication.

Summary

The whole topic in one minute.

CQRS uses one model to change and another to ask. Commands go to an aggregate that guards the rules and emits events. Projections turn the events into read models that answer queries without joins.

Read models are normally eventually consistent, so plan for lag: show the writer their own change, tell users when data is processing, and monitor the delay. Make projections idempotent and rebuildable. Event sourcing is a separate choice. Start with one model, then add a read model where a real query hurts.

  • Commands change, queries ask, and each has its own model.
  • Aggregates guard the rules and emit events.
  • Projections build views; they must be idempotent and rebuildable.
  • Views lag: plan for reading your own writes.
  • Event sourcing is optional. Use CQRS where it pays, not everywhere.

Sources