What is a CQRS read model in a microservice system?

In a CQRS microservice system, the write side accepts commands, enforces invariants, and records what happened as events. The read model is a separate store shaped for specific queries and populated from those events. Treat it as a disposable cache. The events are the source of truth. If a read model is lost or corrupted, you delete it and rebuild it from the event stream. If you cannot rebuild it, it has quietly become a second source of truth, and most of the benefit is gone.

Teams adopt read models for three reasons:

  • Read/write asymmetry. Many services handle far more reads than writes. A separate read store lets you index, denormalize, and scale reads without touching the write model's consistency rules.
  • Query-specific shapes. A "customer order history" screen wants one flat document, not five normalized tables joined at request time.
  • Cross-service views. A read model can consume events from orders, payments, and shipping to answer questions that no single service owns.

Backend and platform teams with heavy or highly varied read patterns benefit most.

The flow:

  1. A command updates the write model, which emits an event.
  2. The event is appended to a stream at a stream position, a monotonically increasing offset.
  3. An event handler receives each event and applies it to the read store. A projection is the full set of handlers that maintains one read model.
  4. The projection persists a checkpoint, the last stream position it processed, so it can resume after a restart.
  5. A query API serves reads from the read store.
   client                                         client
     | command                                       ^ results
     v                                               |
+-----------------------+                  +-----------------------+
| Command API           |                  | Query API             |
+-----------------------+                  +-----------------------+
     |                                               ^
     v                                               | reads
+-----------------------+                  +-----------------------+
| Write model           |                  | Read store            |
| enforces invariants   |                  | query-shaped, can be  |
+-----------------------+                  | deleted and rebuilt   |
     | emits event                         +-----------------------+
     v                                               ^
+-----------------------+                            | apply
| Event stream          |                  +-----------------------+
| (source of truth)     |   events after   | Projection            |
| pos 1 2 3 4 5 6 7 ... |----------------->| handler: OrderPlaced  |
+-----------------------+   checkpoint     | handler: OrderPaid    |
     ^                                     | handler: Shipped      |
     | events from                         +-----------------------+
     | orders, payments,                         |             ^
     | shipping                             save |             | load on
                                                 v             | restart
                                           +-----------------------+
                                           | Checkpoint: pos 5     |
                                           +-----------------------+

Commands update the write model and append events to the stream. A projection's event handlers read events after its saved checkpoint, apply them to a disposable read store, and save the new stream position, and the query API serves reads from that store.

How do you design a read model from the query instead of the events?

Begin with the query, not the event catalogue. For each screen or API call, write down its filter, sort order and returned fields, then shape one table or document to match. If the order history page filters by customer and sorts by date, key the view by customer and store date-ordered rows that already hold the display fields. Reads become key lookups. The join work moves to write time, where it happens once per event instead of once per request.

One event stream can feed several narrow views, such as a customer order history, a warehouse pick list and a daily revenue rollup. Each view has its own handlers and checkpoint, so you can rebuild or drop one without touching the others.

Aspect Narrow per-query views One generic view
Read path Single lookup, no joins Filters and joins at query time
Schema change Affects one consumer Affects every consumer
Rebuild scope One view Everything
Writes per event One per subscribed view One

When a view needs data owned by another service, subscribe to that service's events and copy only the fields the query displays, such as a customer's name rather than the whole customer record. Events across streams arrive in no guaranteed order. If an order event arrives before the matching customer event, insert a placeholder row with the customer ID and an empty name, then fill it when the customer event lands. You now depend on another team's event contract, so read only the fields you use and ignore unknown ones.

Every extra view adds storage and write amplification. A single customer rename must update every row that copied that name, across every view that stores it.

How do you write idempotent projections and event handlers?

Split each projection into two layers. The core is a pure function that takes the current view state and one event and returns the new view state. It does no database calls, reads no clock, and makes no network requests. Because of that, you can test it with event fixtures: load a recorded sequence of events, fold them through the function, and assert on the final state. A replayed event should produce the same result as the original.

The I/O wrapper around the core handles delivery. Most brokers deliver at least once, so the same event will sometimes arrive twice. Store the last applied sequence number for each aggregate or stream, and skip any event at or below it. Write the view update and the new checkpoint in one local SQL transaction. If they commit separately, a crash between the two writes leaves the view and the checkpoint out of sync.

Ordering is only guaranteed per aggregate, and only if you route events by aggregate ID (partition key) or read from per-stream positions. When an event's sequence number skips ahead, you have three options:

  • Buffer it until the missing event arrives.
  • Reject it so the broker redelivers it later.
  • Reprocess the stream from the last checkpoint.

None of this gives you exactly-once processing end to end. The transaction protects only your database. If a handler sends email, a retry sends that email again. Move side effects to a separate consumer that has its own deduplication key.

Finally, upcast old event versions to the current shape before the event reaches the handler. Deserialize leniently and ignore unknown fields, so that a producer adding a field does not break consumers that don't use it.

import json, sqlite3

def apply(state, event):
    # Pure core: no DB, no clock, no network. Same (state, event) -> same result.
    s = dict(state)
    if event["type"] == "OrderPlaced":
        s.update(status="placed", total=event["data"]["total"])
    elif event["type"] == "OrderShipped":
        s["status"] = "shipped"
    return s  # unknown event types leave the view unchanged

def test_fold_fixture():
    events = [{"type": "OrderPlaced", "data": {"total": 40}},
              {"type": "OrderShipped", "data": {}}]
    state = {}
    for e in events:
        state = apply(state, e)
    assert state == {"status": "shipped", "total": 40}

class GapDetected(Exception): pass

def handle(conn, event):
    # I/O edge. conn = sqlite3.connect(path, isolation_level=None) so BEGIN/COMMIT are explicit.
    agg, seq = event["aggregate_id"], event["seq"]
    conn.execute("BEGIN IMMEDIATE")
    try:
        row = conn.execute("SELECT last_seq, state FROM order_view WHERE id = ?", (agg,)).fetchone()
        last_seq, state = (row[0], json.loads(row[1])) if row else (0, {})
        if seq <= last_seq:  # redelivered duplicate: already applied
            conn.execute("ROLLBACK"); return "skipped"
        if seq != last_seq + 1:  # gap: caller decides to buffer, nack, or replay
            raise GapDetected(f"{agg}: expected {last_seq + 1}, got {seq}")
        new = apply(state, event)
        # View state and checkpoint (last_seq) commit together or not at all.
        conn.execute("INSERT INTO order_view (id, last_seq, state) VALUES (?, ?, ?) "
                     "ON CONFLICT(id) DO UPDATE SET last_seq = excluded.last_seq, state = excluded.state",
                     (agg, seq, json.dumps(new)))
        conn.execute("COMMIT"); return "applied"  # no email here: a retry would resend it
    except Exception:
        conn.execute("ROLLBACK"); raise

A pure projection function with a fixture-driven test, wrapped by a SQLite handler that skips duplicates, detects sequence gaps, and commits the view update and checkpoint in one local transaction.

How do you rebuild and replay a read model safely?

Never rebuild a read model in place. Replay from the start of the stream into a new, versioned target, such as order_summary_v3 next to the live order_summary_v2, with its own checkpoint. The live projection keeps serving reads while the new one catches up, so a bug in the new logic never reaches users.

Once v3 is within a few seconds of the stream head, run both projections in parallel and compare them. A reconciliation query can compare row counts per status between the two tables and against the source of truth, the write service's own database. Then sample a few hundred random IDs and diff their fields. A count mismatch usually means a dropped or duplicated event. A field mismatch usually means a logic change you intended or a regression you did not.

When the results agree, switch reads atomically. One way is to point a stable view or alias, order_summary, at v3 in a single transaction. Another is to flip a config flag that the query service reads. Keep v2 running for a while so rollback is just switching the alias back.

This is also how you deploy changes to projection logic or schema. Any change that alters existing rows ships as a new version and a replay, not as an in-place migration.

Two limits apply:

  • Retention: Replay only works if the stream is retained and complete. If retention has expired or early history was never published, backfill from a snapshot of the owning service's data before replaying the remaining events.
  • Capacity: A full replay reads the entire event store and writes heavily to the target database. Throttle the rebuild, batch the writes, and schedule it so it doesn't starve the live projection.
-- PostgreSQL. order_summary_v3 was rebuilt by replay next to the live v2.
-- orders_source: a read-only copy (snapshot or foreign table) of the write service's data.

-- 1. Row counts per status: v2 vs v3 vs source of truth.
SELECT COALESCE(s.status, v2.status, v3.status) AS status,
       s.n AS source_n, v2.n AS v2_n, v3.n AS v3_n
FROM (SELECT status, count(*) AS n FROM orders_source GROUP BY status) s
FULL OUTER JOIN (SELECT status, count(*) AS n FROM order_summary_v2 GROUP BY status) v2
  ON v2.status = s.status
FULL OUTER JOIN (SELECT status, count(*) AS n FROM order_summary_v3 GROUP BY status) v3
  ON v3.status = COALESCE(s.status, v2.status)
WHERE s.n IS DISTINCT FROM v3.n OR v2.n IS DISTINCT FROM v3.n;  -- empty result = counts agree

-- 2. Field-level diff on a random sample of IDs.
WITH sample AS (
  SELECT order_id FROM order_summary_v2 ORDER BY random() LIMIT 300
)
SELECT o.order_id, o.status, n.status AS v3_status,
       o.total_cents, n.total_cents AS v3_total_cents
FROM sample
JOIN order_summary_v2 o USING (order_id)
LEFT JOIN order_summary_v3 n USING (order_id)            -- NULLs here = missing in v3
WHERE n.order_id IS NULL
   OR (o.status, o.total_cents, o.item_count)
      IS DISTINCT FROM (n.status, n.total_cents, n.item_count);

-- 3. Atomic read switch: the query service only ever reads the stable view name.
-- PostgreSQL DDL is transactional, so readers see either v2 or v3, never neither.
BEGIN;
DROP VIEW IF EXISTS order_summary;
CREATE VIEW order_summary AS SELECT * FROM order_summary_v3;
COMMIT;

-- Rollback: rerun step 3 pointing at order_summary_v2 (keep v2's projection running).

PostgreSQL queries that reconcile a replayed order_summary_v3 against the live v2 and the source of truth by per-status counts and a sampled field diff, then atomically repoint the stable order_summary view.

How should clients handle eventual consistency in CQRS read models?

When a user submits a form and the next page reads from a projection that hasn't caught up yet, they see the old state. The new order is missing from the list, or the renamed item still shows its old name. Many users conclude the action failed and submit again. That produces duplicate commands, so command handlers should deduplicate on a client-supplied request ID no matter which option below you choose.

There are three common ways to hide or bound the lag:

  • Expose the projection's position. Each query response includes the last event position or version the read model has applied. The client can compare it with what it expects and show a "still updating" hint instead of silently showing stale data.
  • Wait for read-your-writes. The command side returns the position of the event it just appended. The client sends that position with its next query, and the query side waits, with a timeout, until the projection reaches it.
  • Apply the change optimistically. The UI updates its local state as soon as the command is accepted and reconciles when fresh data arrives.
Option Added latency Complexity Guarantee
Position in responses None Low Staleness is visible, not prevented
Wait for command position Up to the projection lag Medium (position tracking, timeouts) Read-your-writes for that client
Optimistic UI None Medium (rollback on failure) Only the UI's local view of its own change

None of these makes a read model safe for decisions. A balance check before a withdrawal, or a stock check before a reservation, must run against the write model. A stale read there leads to the wrong decision being made, not just a confusing screen.

// Query side: wait (bounded) until the projection has applied the client's own write.
type Order = { id: string; status: string };

interface Projection {
  position(): number; // last event position applied to this read model
  getOrders(customerId: string): Promise<Order[]>;
}

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

export async function queryOrders(
  projection: Projection,
  customerId: string,
  minPosition?: number, // position the command side returned after appending the event
  timeoutMs = 2000,
) {
  const deadline = Date.now() + timeoutMs;
  // Poll until the projection catches up. On timeout, serve the data anyway; never block indefinitely.
  while (minPosition !== undefined && projection.position() < minPosition) {
    if (Date.now() >= deadline) break;
    await sleep(50);
  }
  // Read the position before the data, so the reported position never overstates what was read.
  const position = projection.position();
  return {
    orders: await projection.getOrders(customerId),
    position, // always expose how far the read model has got
    stale: minPosition !== undefined && position < minPosition, // UI shows "still updating"
  };
}

// Client flow: the command carries a request ID for deduplication, and the response returns the event position.
// const { position } = await (await fetch("/commands/place-order", {
//   method: "POST",
//   body: JSON.stringify({ requestId: crypto.randomUUID(), sku: "SKU-123", qty: 1 }),
// })).json();
// const view = await (await fetch(`/queries/orders?minPosition=${position}`)).json();

A query handler that gives read-your-writes by waiting, with a timeout, for the projection to reach the position returned by the command side, and that always reports its position and a stale flag so the UI can show the lag instead of hiding it.

How do you monitor projection lag, poison events and silent failures?

A projection is just another consumer, so monitor it like one. Track lag in two units. The first is position lag: the stream head's position minus the projection's checkpoint. The second is time lag: the age of the newest event at the head minus the age of the last event the projection applied. Position lag tells you how much work is queued. Time lag tells you how stale the data a user sees is. A burst of 50,000 events can look alarming in position terms while being only seconds behind in time. A quiet stream can also hide a projection that stopped an hour ago.

That second case is why you should alert on a stalled checkpoint, not only on a lag threshold. If the head advances and the checkpoint does not move for several polling intervals, the handler is stuck, even when absolute lag still looks small.

A poison event is an event the handler fails on every time it retries. Route it to a dead-letter path instead of blocking the stream forever. Record the event ID, stream position, handler version and the full error. With those four fields, you can fix the handler and replay exactly the affected events without guessing.

The more dangerous failures throw nothing. A handler that maps a field wrongly will advance its checkpoint cheerfully while writing bad data. To catch this, schedule reconciliation jobs. These can compare counts or totals against the write model, or rebuild a sampled set of entities and diff them against the live view.

Expose a health signal for each projection, such as healthy, lagging, stalled or degraded. Combine it with a rebuild path you have actually tested. During an incident or a schema change, you can then identify which view is wrong and rebuild only that one. Without both, you end up debugging the entire read side.

When should you avoid CQRS read models, and what are the alternatives?

A read model pays off when three conditions line up. Reads far outnumber writes. The query shape differs from how data is written, for example a dashboard that aggregates across aggregates. Or the view joins data owned by several services. In those cases, precomputing the answer moves cost from every read to each write, and the query store can scale on its own.

Avoid read models when the service is simple CRUD, reads and writes are roughly balanced, or users must see their own writes immediately with no exceptions. Also avoid them when events are not retained long enough to rebuild a view. Without that history, a corrupted projection can only be fixed by hand.

Alternative Consistency Best fit Main limitation
Indexed queries on primary DB Strong Single-service queries that one index can serve Read load competes with writes
Database read replica Replication lag Scaling the same query shapes No change in data shape
Materialized view in one DB Depends on refresh strategy Aggregations within one database Refresh cost, no cross-service data
Change data capture into query store Eventual Read models without changing the writer Couples to the table schema, not domain events
API composition at request time Fresh per call Low-volume cross-service views Latency and availability multiply across calls

Try these in roughly this order before you build a read model. Each one usually costs less to run.

Every read model is another consumer that you deploy, monitor, version alongside event schemas, and rebuild when it breaks. That cost recurs. Accept it only when the gains in query latency and independent scaling are measurable and needed now, not just expected.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to cqrs read model microservices, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.