CQRS Pattern A Solution
CQRS works by keeping two separately-shaped copies of the same data: a normalized write model that accepts commands and enforces invariants inside a transaction, and one or more denormalized read models pre-shaped for specific queries, kept in sync asynchronously by publishing the write model's changes as events. Reads and writes can then be optimized, scaled, and even stored in different databases independently — at the price of the read side lagging the write side by a small window.
The name decomposes cleanly:
- Command — an instruction to change state (create / update / delete). "Add a line item to order 1001." It mutates and returns nothing meaningful.
- Query — a request to read state with no side effects. "Show me order 1001's summary." It returns data and changes nothing.
- Responsibility Segregation — the command path and the query path are handled by different code, different models, and (in full CQRS) different data stores.
CQS is the method rule; CQRS is the architecture
The underlying discipline is Command Query Separation (CQS), Bertrand Meyer's rule that every method is either a command (mutates state, returns void) or a query (returns a value, no side effects) — never both. That is a good habit at the method level, and the previous version of this page stopped there.
CQRS lifts that split from methods to whole models. Instead of one object model serving both reads and writes against one database, you build:
- A write model: normalized tables (or an aggregate) that exists to protect invariants — e.g. "order total must equal the sum of line items", "stock cannot go negative". Strongly consistent, transactional, rarely queried directly.
- One or more read models: denormalized, pre-joined, query-shaped projections — a flat
order_summaryrow, an Elasticsearch document for search, a Redis hash for a dashboard tile. Cheap to read, disposable, rebuildable.
Nothing reads the write model to answer a user query, and nothing writes the read model except the projector. The two are bridged by an event stream, which is why the read side is eventually consistent, not immediately.
Worked example: two line items on order 1001
A checkout service uses CQRS. The write store is normalized Postgres (orders, order_items) that guards the invariant orders.total = sum(order_items) and stock ≥ 0. The read store is a single denormalized order_summary row per order, built for the "my orders" screen. A projector consumes LineItemAdded events from Kafka. Follow the exact values as two commands arrive close together:
| Time | Action | Write store (committed) | Event on bus | Read store order_summary | Query returns now |
|---|---|---|---|---|---|
| 0 ms | Command AddLineItem(1001, WIDGET-42, qty 2, $12.50) | stock 50≥2 OK → insert item; total 0 → $25.00; COMMIT | LineItemAdded v1 (offset 5567) | — (row not created yet) | empty / 404 |
| 15 ms | Projector consumes v1 | unchanged | — | upsert → items 1, total $25.00, v=1 | total $25.00 ✓ |
| 120 ms | Command AddLineItem(1001, GADGET-9, qty 1, $40.00) | total $25.00 → $65.00; COMMIT | LineItemAdded v2 (offset 5581) | still items 1, total $25.00, v=1 | total $25.00 — STALE |
| 140 ms | Projector consumes v2 | unchanged | — | upsert → items 2, total $65.00, v=2 | total $65.00 ✓ (converged) |
The 120–140 ms window is the entire point of CQRS made visible: the write store is already correct at $65.00, but a query in that window reads the not-yet-updated read store and sees $25.00. There is no bug — it is the design. The projector applies events in order (v1 then v2) and idempotently (an upsert keyed by order id, guarded by the version number), so a redelivered v1 after v2 has landed is safely ignored rather than clobbering the newer total.
The sync mechanism — and where event sourcing fits
The hard part is reliably turning a committed write into an event. Publishing to Kafka after the DB commit is a dual write: if the process crashes between commit and publish, the event is lost forever and the read model is permanently wrong. The standard fixes:
- Transactional outbox: write the event into an
outboxtable in the same DB transaction as the state change. A separate relay reads the outbox and publishes. The commit is now atomic across state + event. - Change Data Capture (CDC): a tool like Debezium tails the DB's write-ahead log and emits an event per row change — no application code needed to publish.
Relationship to event sourcing (ES). They are often paired but are independent. ES makes the event log itself the source of truth — you store LineItemAdded, not a mutable orders row — and reconstruct current state by replaying events. With ES, CQRS read models are simply projections of that log, and rebuilding a read model means replaying from offset 0. But you can do CQRS without ES (a normal transactional write store + outbox, as above), and ES without CQRS (replay to serve reads too). Don't conflate them.
Pitfalls
- Dual-write data loss. Commit-then-publish without an outbox/CDC silently drops events on a crash; the read model diverges and no error is ever raised. Use a transactional outbox or CDC.
- Reading your own write. A user submits a command, the UI immediately re-queries, sees stale data (the 120 ms window), assumes it failed, and resubmits — creating a duplicate. Mitigate by returning the new state directly from the command, or routing that user's next read to the write store, or passing a version the read must reach.
- Non-idempotent projectors. Buses deliver at-least-once and can reorder. A projector that does blind
INSERTortotal += xwill double-apply on redelivery. Project with upserts keyed by id and guarded by an event version/sequence. - Expensive rebuilds. A projector bug means replaying the full history to regenerate the read model — potentially billions of events. Keep events immutable and projectors deterministic so replay is always possible.
- Silent schema drift. Add a field to the write model but forget the projector, and it simply never appears in reads — no error, just missing data.
- Applying it to plain CRUD. The most common failure is adopting CQRS where it isn't needed: you inherit two stores, a bus, and eventual-consistency bugs for zero benefit.
When to use it — and when NOT to
Reach for CQRS when concrete signals appear:
- The read shape genuinely diverges from the write shape — writes need normalized invariants, but reads need heavy joins, aggregations, full-text search, or geospatial lookups that fight that schema.
- Asymmetric load — reads outnumber writes by orders of magnitude, and you want to scale (or re-technology: SQL write, Elasticsearch read) each side independently.
- Many read shapes off one write model — a dashboard, a search index, and an export all want different projections.
- Complex, collaborative, invariant-heavy write domains where a task-based command model is cleaner than CRUD.
Trade-offs vs. named alternatives:
- vs. single-model CRUD (one DB, shared schema). CRUD gives you strong read-after-write consistency, one store, and far less code. You gain nothing from CQRS here except complexity. Prefer CRUD when the domain is simple and reads want the same shape as writes.
- vs. read replicas. Replicas scale read throughput of the same shape with almost no new code (still eventually consistent, but no model divergence, no projector, no bus). Choose replicas when you need more of the same query; choose CQRS when you need a differently shaped query.
- vs. materialized views inside one DB. A materialized view gives a denormalized read shape without a separate service or bus — simpler, but coupled to one DB engine and its refresh model. Prefer it when one database can hold both models and refresh latency is acceptable; go full CQRS when read and write must live in different systems.
Decision rule: choose CQRS when the read model must diverge in shape or technology from the write model and you can tolerate eventual consistency; prefer read replicas when you only need more read throughput of the same shape; prefer plain CRUD when the domain is simple — the two stores, the bus, and the consistency window are real, permanent costs, not free.
Takeaways
- CQS splits methods (command vs query); CQRS splits models and stores — a normalized write model for invariants, denormalized read models for queries, bridged by events.
- The consequence is eventual consistency: the read side lags the write side by a small window (the $25 vs $65 gap in the trace). Design the UI for it.
- Reliable sync needs a transactional outbox or CDC and idempotent, ordered projectors; skipping these silently corrupts the read model.
- It is real, permanent complexity — justified only when read and write shapes truly diverge or must scale independently. For simple CRUD or same-shape read scaling, CRUD or read replicas win.
Re-authored / Deepened for this guide. Sources: Martin Fowler, "CQRS" and "CommandQuerySeparation" (martinfowler.com); Greg Young's original CQRS and event-sourcing talks and papers; Microsoft Azure Architecture Center — "CQRS pattern" and "Transactional Outbox pattern"; Chris Richardson, Microservices Patterns (Manning) and microservices.io on CQRS, Event Sourcing, and the Transactional Outbox; Debezium documentation on change data capture.
🤖 Don't fully get this? Learn it with Claude
Stuck on CQRS Pattern A Solution? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **CQRS Pattern A Solution** (System Design). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **CQRS Pattern A Solution** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **CQRS Pattern A Solution**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **CQRS Pattern A Solution**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.