How-To Guide

How to Implement CQRS

Separate the write and read models: write to a normalized model, project to a read model, keep them eventually consistent, and query the read side.

On this page

  1. Introduction
  2. Separate the write model from the read model
  3. Project from the writes to the reads
  4. Accept and design for the eventual consistency
  5. Keep the read models rebuildable
  6. Test the projection, the lag, and the rebuild
  7. Common pitfalls
  8. Conclusion

Introduction

A single model that serves both the writes and the reads is often a compromise: it has the invariants the writes need and the joins the reads need, and neither is optimal. CQRS separates them: a write model tuned for the changes and their invariants, and one or more read models tuned for the queries. The write model publishes the changes, and a projection updates the read models, so each side is shaped for its workload.

This tutorial implements CQRS: separate the write and read models, project from the writes to the reads, accept the eventual consistency, and test the projection and the lag. The examples use a normalized write model and a denormalized read model, and the design applies to any system with very different read and write loads.

Separate the write model from the read model

The write model is normalized for the changes: it holds the entities, their relationships, and their invariants, so a write is a small, consistent change. The read model is denormalized for the queries: it holds the data in the shape the read needs, often pre-joined or pre-aggregated, so a read is a single lookup. Each model is free to be shaped for its workload.

The write model is the source of truth, and the read model is derived from it. Never write to the read model directly as a source; update it only by projecting from the write model. This keeps the truth in one place and the read model rebuildable, so a change to the read shape is a re-projection rather than a migration of the truth.

-- write model: normalized, holds the invariants
orders(id, customer_id, status, created_at)
order_items(id, order_id, sku, qty, price)

-- read model: denormalized for the query, pre-joined and pre-summed
order_summary(order_id, customer_name, item_count, total, status)

Project from the writes to the reads

A projection consumes the changes from the write model and updates the read model. The write side publishes an event per change, and the projection applies it to the read shape: an OrderPlaced adds a summary row, an OrderItemAdded increments the item count and the total. The write transaction does not do the read-shaped work, so it stays small and fast.

The projection is asynchronous, which is what makes the read model lag. It can be a consumer of the events, or a job that reads the change log. It must be idempotent, because the events can be redelivered, and it must handle the events in the per-entity order, so the read model reflects the sequence. The projection is the read side’s own logic, separate from the write side’s.

async function project(event) {
  switch (event.type) {
    case 'OrderPlaced':
      await readDb.query(
        'INSERT INTO order_summary (order_id, customer_name, item_count, total, status) VALUES ($1,$2,0,0,$3)',
        [event.payload.orderId, event.payload.customerName, 'placed'],
      );
      break;
    case 'OrderItemAdded':
      await readDb.query(
        'UPDATE order_summary SET item_count = item_count + 1, total = total + $2 WHERE order_id = $1',
        [event.payload.orderId, event.payload.price * event.payload.qty],
      );
      break;
  }
}

Accept and design for the eventual consistency

The read model lags the write, so a read right after a write may not reflect it. This is the trade of CQRS: the reads are fast and query-shaped, at the cost of a brief staleness. The design must accept it and handle it, not pretend it does not exist, because a user who writes and immediately reads may see the old state.

For the user’s own action, read the write model or the source that is immediately current, and show the user their confirmed change. For a read that tolerates the lag, such as an analytics view, read the projection. A common pattern is to read the write model for the entity the user just changed and the projection for everything else, so the user’s own view is current while the broad views catch up.

# read-after-write: read the entity from the write model (current), not the projection
# broad reads (lists, analytics): read the projection (eventually consistent)
# tell the user their change is confirmed even if a list lags

Keep the read models rebuildable

A read model is derived, so it can be rebuilt from the write model. This is a strength: when the read shape changes, rebuild the projection rather than migrate the truth, and when a projection is buggy, fix it and reproject. The ability to rebuild is why the read model can be denormalized and multiple read models can coexist.

Keep more than one read model for the queries that differ: a list view, a search index, an analytics cube. Each is projected from the same write events, each shaped for its query. A new read need is a new projection, not a change to the write model, which keeps the write side stable as the read needs evolve.

Test the projection, the lag, and the rebuild

Test that a write projects to the read model with the expected shape, by writing and asserting the read row. Test that the read model catches up after the projection processes the events. Test that the read-after-write path reads the write model so the user’s own change is current. Test that the read model can be rebuilt from the write model unchanged, by dropping it and reprojecting.

# write, project, then read: assert the read model reflects the write
node scripts/write-order.mjs
node scripts/run-projection.mjs
node scripts/read-summary.mjs --id 1     # assert the read row matches the write
# drop the read model and reproject: assert it matches

Common pitfalls

Using one model for both and compromising on both, writing to the read model as a source, a non-idempotent projection that double-applies on a redelivery, ignoring the lag so a read-after-write shows stale data, and a read model that cannot be rebuilt so a shape change is a migration are the recurring mistakes. The separated models, a derived read model, an idempotent ordered projection, a read-after-write path to the truth, and a rebuildable read model address them.

Conclusion

CQRS separates the write and read models so each is shaped for its workload. Keep the write model as the truth with the invariants, project the changes to one or more read models, accept and design for the lag, and keep the read models rebuildable. Self-check by writing, projecting, and reading the read model, and by rebuilding it from the write model unchanged. Then the writes are consistent and the reads are fast, each in its own shape.

Sources: Martin Fowler: CQRS, Microsoft: CQRS pattern, Microservices.io: CQRS.

FAQ

When does CQRS pay off?
When the read and write workloads are very different, such as many reads with complex queries and few writes with strict invariants. Separating them lets each model be tuned for its workload. For a simple CRUD service, the separation adds complexity without the benefit.
Do I need events for CQRS?
No, but events make the projection clean. The read model can be updated from the events the write side publishes, which decouples the projection from the write transaction. Without events, the projection reads the write model and subscribes to changes, which is also possible but couples them more.

Related Examples