Course contents

10. Software Architecture Lesson 7 of 10

CQRS

Split the write model from read models, watch the read side lag behind and serve stale data, and learn how to give users their own writes and when to skip CQRS.

16 minIntermediate8 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Commands change state through a write model that enforces the rules; queries read models shaped for each screen.
  • Read models are updated from events after the write commits, so they lag behind.
  • Projection lag fails silently: no errors, just older answers. Monitor backlog age and checkpoints.
  • Return versions from commands so a user’s next query can wait for, or bypass to, their own write.
  • Start with separate command and query code over one database; add separate stores only when reads and writes truly diverge.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

Command Query Responsibility Segregation (CQRS) uses one model to change data and another model to read it. Commands ("place order", "change address") go to a write model that validates input and enforces business rules. Queries go to one or more read models built for the screens and APIs that need them: denormalised, pre-joined, possibly in a different store. The name extends Bertrand Meyer's command-query separation (CQS) from methods to whole models; Greg Young and Udi Dahan popularised it around 2010.

Why it exists

Reads and writes rarely look alike. Writes touch one aggregate and must be correct; reads join many entities and must be fast. Reads often outnumber writes 10:1 or 100:1. One normalised model makes the expensive reads compete with the important writes for the same connections and locks, and forces every screen's query shape onto the domain model. Separating them lets each side be shaped, stored and scaled for its own job.

How it works

  1. A command arrives (PlaceOrder). The command handler loads the aggregate from the write store, runs the rules and commits.
  2. The change is published as an event (OrderPlaced), ideally through a transactional outbox so the event and the commit cannot diverge.
  3. A projector (projection handler) consumes events and updates one or more read models: a row per order list entry, a document per customer page, a search index.
  4. A query reads the read model directly, with no business logic in the way.

Read models are disposable: because they are derived from the write side, you can drop one and rebuild it by replaying events (or re-running a query over the write store). The read side is eventually consistent: between the commit and the projection there is a window in which a query returns the previous state.

Levels of CQRS. Not all-or-nothing:

  • Code-level: separate command and query handlers over one database (in .NET often MediatR-style handlers, or plain classes); queries may use Dapper or SQL views. No lag.
  • Same database, separate read tables updated in the same transaction or by triggers/materialised views. Little or no lag, limited independence.
  • Separate read stores updated asynchronously from events. Full independence, real lag.
// Command side: rules and one aggregate per transaction
public async Task<long> Handle(ChangeAddress cmd, CancellationToken ct)
{
    var order = await _db.Orders.SingleAsync(o => o.Id == cmd.OrderId, ct);
    order.ChangeAddress(cmd.Address);                          // invariants live here
    _db.Outbox.Add(OutboxMessage.From(new AddressChanged(order.Id, cmd.Address, order.Version + 1)));
    await _db.SaveChangesAsync(ct);                            // order + outbox, one transaction
    return order.Version;                                      // let the caller wait for this version
}

// Query side: no domain model, just the shape the screen needs
public Task<OrderSummary?> Handle(GetOrderSummary q, CancellationToken ct) =>
    _readDb.QuerySingleOrDefaultAsync<OrderSummary>(
        "select * from order_summaries where order_id = @Id and version >= @MinVersion", q);

When to use it

  • Read and write workloads differ strongly in volume, shape or scaling needs.
  • Screens need data from many aggregates or contexts (dashboards, search, feeds).
  • The write model has rich rules you want to keep free of query concerns.
  • You already use event sourcing: the event store is a poor query engine, so read models are needed anyway.

When not to

  • CRUD screens where reads and writes have the same shape.
  • Small systems where one database comfortably serves both.
  • Domains where users must see every change immediately everywhere and you cannot design around lag.
  • Teams not yet comfortable operating queues, replays and lag monitoring.

Trade-offs

Choice You gain You pay
Separate read store Fast, screen-shaped queries; scale reads independently Eventual consistency, a second store, projection code
Asynchronous projections Commands stay fast; read side can fail without blocking writes Lag, stale reads, replay tooling
Synchronous read-table updates No lag Slower commands; a failing read table fails writes
Many read models Each screen gets the perfect shape More projections to maintain and rebuild

Alternatives

  • Read replicas: copies of the same model; scale reads without new query shapes. Also lag (see database replication).
  • Caching: cache-aside on the hot queries; cheap, but same shapes and invalidation issues.
  • Materialised views / indexed views in the database: precomputed joins without a separate pipeline.
  • Search engine as a secondary index: effectively a single read model for search, fed by change data capture.

Failure modes

  • Silent lag. A slow or stuck projector produces no errors, only older answers. In the lesson, stale reads multiply while the error rate stays at zero.
  • Lost or duplicated events. Publishing without an outbox can drop events (read model never updates); at-least-once delivery means projectors must be idempotent (track the last applied event position or version per read model).
  • Out-of-order events. Projections that assume order break when partitions or retries reorder events; key by aggregate and check versions.
  • Read-your-writes surprises. Users save, reload and see the old value, then save again.
  • Rebuild pain. A new read model over years of history can take hours to project; plan for parallel rebuild and cut-over.

In production

Make projectors idempotent and checkpointed. Expose projection lag as a metric (oldest unprocessed event age, checkpoint gap) and alert on it. Return the new version from commands; let queries accept a minimum version and wait briefly, or route a user to the write side right after their write. Keep read models disposable and rebuildable; version their schemas so a new projection can be built alongside the old one. Use an outbox (or CDC) between the write store and the broker.

Common misconceptions

  • "CQRS requires event sourcing." No. A relational write model plus an outbox works fine. Event sourcing usually implies CQRS, not the other way round.
  • "CQRS means two databases." Separate code paths over one database are already CQRS, without lag.
  • "Eventual consistency means minutes of staleness." Typical lag is milliseconds to seconds; the point is that it is non-zero and unbounded under failure.
  • "CQRS is an architecture for the whole system." It is a pattern for a bounded context, applied where it pays.

Interview angle

Use CQRS when you can name the asymmetry: "90% reads, joins over five tables, feed shaped per user". Draw command → write store → outbox → broker → projector → read store ← query service, then volunteer the consistency story: lag, stale reads, how you monitor it, how users see their own writes (versions, waiting, sticky routing), idempotent projectors, rebuilds by replay. Saying you would start with separate handlers over one database shows judgement.

Model assumptions

The simulation is a simplified model, not a benchmark. Requests arrive as a Poisson stream; 10% are commands, and keys follow Zipf(1.0) over 40 orders, so a few orders are hot. Before the split: an API with 32 workers (5 ms) and one database with 10 connections, 35 ms per join query and 12 ms per command (lognormal, cv 0.4). After the split: the gateway routes writes to the command service (16 workers, 8 ms) and reads to the query service (16 workers, 20 ms) over a read model answering in ~4 ms. The command service commits, then publishes to a queue consumed by a projector (simulated messages). How far the read model trails the write model is modelled as asynchronous replication with a fixed delay (150 ms, later 2 s), drawn as the link between the two databases; a read is counted stale when its order had a write acknowledged that the read model had not yet applied. The single user's write-then-read sequences are scripted packets on top of the simulated traffic. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. One model serves reads and writes

    An orders system gets about 120 requests per second: one in ten is a command (place an order, change an address), nine in ten are queries (order lists, dashboards).

    Both go through the same API and the same normalised database. Commands are short (~12 ms). Queries are not: an order list joins orders, lines, customers and shipments, about 35 ms each. At this load the database is about 40% busy and everything succeeds.

    Scene: Users send 120 requests per second, 10% commands and 90% queries, to one Orders API backed by one database. The database is about 40% busy and nothing fails.

    Key idea: Reads and writes usually have different shapes and volumes, but a classic CRUD design serves both from one model.

  2. 2. Queries crowd out commands

    Traffic grows to 330 requests per second, almost all of it dashboards. The joins alone now need more connection time than the database has.

    Every connection is busy and requests wait for one. The API’s workers all end up waiting on the database, its own queue fills, and new requests are turned away with 503. The commands, a small and important minority, fail with them: they queue behind the reports. P95 latency triples.

    You could add indexes or replicas. But the deeper problem is that one model is shaped for neither job: normalised for safe writes, and therefore expensive to read.

    Scene: At 330 requests per second the database is saturated by queries. Requests wait for connections, the API’s workers fill up, P95 latency triples and some requests, commands included, are rejected.

    Key idea: When reads dominate and are shaped differently from writes, one model makes both compete for the same resources.

  3. 3. Separate the write model from the read model

    CQRS splits the two. An API gateway sends commands to a command service that owns the write model: it validates, enforces the rules and commits to the write database. It then publishes an event (OrderPlaced, AddressChanged) to a queue.

    A projector consumes those events and keeps a read model up to date: a denormalised table per screen, already joined, so a query is a ~4 ms lookup. Queries go to a query service that only reads it.

    Result: errors stop and P95 drops, at the same 330 requests per second. Each side can now be scaled, indexed and even stored differently (a relational write store, a document or search read store).

    Simulated. The read model’s delay behind the write model is modelled as asynchronous replication with a fixed lag (150 ms), shown on the link between the two databases.

    Scene: The gateway routes commands to the command service, which commits to the write database and publishes events to a queue; a projector updates a denormalised read model. Queries go to the query service, which reads the read model. At 330 requests per second nothing fails and latency drops.

    Key idea: CQRS: commands change state through the write model; queries read a separate model built for reading.

  4. 4. The read side is eventually consistent

    The read model is updated after the command commits: the event has to be queued, picked up and projected. For about 150 ms the two models disagree.

    Watch one user (scripted packets on top of the simulated traffic): they change an order, get a success response, and immediately reload the list. The query reaches the read model before the projection does, so the list still shows the old value. Then the update lands.

    The engine counts these as stale reads: queries for an order that had already been changed, answered from a read model that had not yet applied the change. Hot orders, written often, are stale most often.

    Scene: A user’s command commits and returns success; the event is still on its way through the queue and projector when the user’s next query reads the read model, which still has the old version. Shortly afterwards the projection applies the change. Some simulated reads are counted as stale.

    Key idea: In CQRS the read model lags the write model. A query right after a command may not see it.

  5. 5. The projector falls behind

    One second in, the projector slows down (a slow read store, a poison message, a deploy). Events pile up in the queue and the read model now trails the write model by about two seconds.

    Nothing fails and latency looks perfect, yet far more queries return stale data: the stale-read counter climbs while the error rate stays at zero. That is why projection lag needs its own monitoring: age of the oldest unprocessed event, or the gap between the write model’s last event position and the projector’s checkpoint.

    Simulated: the degraded projector is shown in amber; the read model’s delay is raised to 2 s.

    Scene: The projector slows down and events back up in the queue. The read model trails the write model by about two seconds; stale reads rise sharply while errors stay at zero and latency is unchanged.

    Key idea: Projection lag fails silently: no errors, just older answers. Measure it and alert on it.

  6. 6. Reading your own writes

    The projector is healthy again (lag back to ~150 ms). Users mostly don’t mind a slightly old dashboard, but they do mind not seeing their own change. Common fixes:

    - the command returns the new state or version (v42), and the UI shows that instead of re-querying; - the query carries the version and the query service waits until the read model has reached it (shown here: first read v41, short wait, second read v42); - for a few seconds after a write, that user’s queries go to the write model.

    All of them hide lag from the user who caused it, not from everyone else. Scripted packets on top of the simulated traffic.

    Scene: A command returns version 42. The user’s follow-up query asks for at least version 42; the query service reads version 41, waits until the projection lands, reads again and returns version 42.

    Key idea: Return versions from commands and let queries wait for (or bypass to) that version, so users always see their own changes.

  7. 7. When CQRS is not worth it

    Count what was added: a second data store, a queue, a projector, event contracts, lag monitoring, replay tooling for rebuilding read models, and a consistency model every developer and product owner must understand.

    That pays off when reads and writes really differ: very different volumes, screens that need data from many aggregates, a write model with rich rules. For a CRUD screen over a few tables it does not. Lighter steps come first: separate command and query code paths in one service (in .NET, e.g. MediatR-style handlers or plain classes) over one database, with read-optimised SQL views or Dapper queries for the heavy screens. No lag at all, most of the clarity.

    Scene: The extra components CQRS introduced are highlighted: the event queue, the projector and the separate read model, each adding operational cost.

    Key idea: CQRS is a trade: independent read and write models in exchange for eventual consistency and more moving parts. Start with separate code paths over one database.

  8. 8. What to remember about CQRS

    Commands go to a write model that enforces the rules; queries read read models shaped for each screen. Events carry changes from one to the other, so the read side is eventually consistent and its lag must be measured.

    Use it where reads and writes genuinely differ, give users their own writes back via versions, and don’t confuse it with event sourcing: CQRS works with an ordinary relational write model, and event sourcing works without separate read stores. They are often combined, not required together.

    Scene: The complete CQRS setup: gateway, command service with write database and event queue, projector, read model and query service, running at 330 requests per second with a short read-model lag.

    Key idea: Separate models for changing and for reading data: independent scaling and shapes, paid for with lag.