Knowledge Guide
HomeSystem DesignMicroservices Patterns

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:

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:

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.

diagram
diagram

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:

TimeActionWrite store (committed)Event on busRead store order_summaryQuery returns now
0 msCommand AddLineItem(1001, WIDGET-42, qty 2, $12.50)stock 50≥2 OK → insert item; total 0 → $25.00; COMMITLineItemAdded v1 (offset 5567)— (row not created yet)empty / 404
15 msProjector consumes v1unchangedupsert → items 1, total $25.00, v=1total $25.00 ✓
120 msCommand AddLineItem(1001, GADGET-9, qty 1, $40.00)total $25.00 → $65.00; COMMITLineItemAdded v2 (offset 5581)still items 1, total $25.00, v=1total $25.00 — STALE
140 msProjector consumes v2unchangedupsert → items 2, total $65.00, v=2total $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:

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

When to use it — and when NOT to

Reach for CQRS when concrete signals appear:

Trade-offs vs. named alternatives:

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


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.

🪜 Hint ladder (no spoilers)

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.
🎨 Explain the approach visually

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.
🔍 Review my solution

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.
🔁 Drill the pattern

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.

📝 My notes