CQRS + Event Sourcing
Intent
Separate the model that handles writes from the model that serves reads, and persist state changes as an immutable sequence of events that is the source of truth.
When It Helps
- Reads and writes have very different shapes — complex transactional writes versus fast, denormalized queries.
- Audit history matters: you must answer not just the current state but how it got there.
- Rebuilding views, replaying history, or deriving new projections from past facts is valuable.
Structure
flowchart LR Clients -->|commands| Write[Write Model] Write --> Log[(Event Log: immutable, append-only)] Log --> Projector[Projectors] Projector --> R1[(Read Model: Orders View)] Projector --> R2[(Read Model: Search Index)] Clients -->|queries| R1 Clients -->|queries| R2
Deployment unit: write side, projectors, and read stores deploy as separate units fed by the same log. Communication: commands flow into the write model; events flow out of the log into projectors; queries never touch the write model directly. Data ownership: the event log is the authoritative truth; read models are disposable projections that can be rebuilt from it at any time.
Rules
- All state changes append immutable events to the log — never update or delete past events in place.
- The write model validates commands; the read models serve queries; neither does the other’s job.
- Projectors must be replayable: any read model can be dropped and rebuilt solely from the event log.
- Event schema evolution is additive — old events stay readable so replays keep working.
Illustrative Snippet
Illustrative pseudocode — not runnable.
# sketch: commands -> events -> projections
command: PlaceOrder(cart) -> write model validates -> append:
events: [order.initiated, order.paid, order.shipped]
projector order-view:
on order.initiated -> insert row {status: pending}
on order.paid -> update row {status: paid}
on order.shipped -> update row {status: shipped}
query: get_order(id) reads order-view (never the log directly)
rebuild: drop order-view, replay events 1..N -> identical view
Basic Recap
CQRS separates command handling from query models, and event sourcing stores each accepted state change as an immutable event. The write model enforces invariants and appends events; projectors derive disposable read views from the log. Replays support audits, historical reconstruction, and new queries without changing the original decisions. This power brings eventual consistency, schema evolution, and projection operations.
Complex Scenario
A bank disputes service must explain every status transition while serving both agent timelines and high-volume customer summaries. Commands append events with an expected aggregate version, and separate projectors maintain a summary database and a search index. A new regulatory view should be buildable from the same history. Customer screens may read a projection, but dispute decisions always go through the write model.
flowchart LR
Agents["Dispute agents"] --> Commands["Command API and write model"]
Commands --> Version{"Expected version matches?"}
Version -->|yes| Log[("Immutable dispute event log")]
Log --> SummaryProjector["Summary projector"]
Log --> SearchProjector["Search projector"]
Log --> RegulationProjector["Regulatory projector"]
SummaryProjector --> SummaryDB[("Customer summary DB")]
SearchProjector --> Search[("Case search index")]
RegulationProjector --> AuditView[("Regulatory timeline view")]
Customers["Customer queries"] --> SummaryDB
Agents --> Search
Failure walkthrough. The summary projector crashes on an unknown legacy event while commands continue appending. Customer balances remain stale, retries of the same event block its partition, and a traffic spike makes the lag visible as contradictory agent and customer screens. Mitigate with additive event upcasting, idempotent projector checkpoints, quarantine plus an alerted replay procedure, and read responses that expose projection freshness; rebuild the fixed projection into a new store before switching queries atomically.
Edge cases — concurrent commands use optimistic version checks, command retries need deterministic idempotency, and event ordering is guaranteed per aggregate rather than across every dispute. Memory pressure during replay requires batched checkpoints instead of loading the full log into one process.
Sketch (illustrative pseudocode, not runnable):
command AcceptEvidence:
key: dispute_id + command_id
precondition: aggregate_version == expected_version
on_success: append EvidenceAccepted{event_version: 3, ...}
on_version_conflict: reload_and_reject_or_revalidate
projector customer-summary:
batch_size: 500
checkpoint: transactional_with_projection_rows
on legacy EvidenceAccepted.v1:
upcast_to_v3(defaults_from_original_payload)
on unrecognized_event:
stop_partition_and_alert
read customer-summary:
return {summary, projected_through, freshness}
never_claim: authoritative_current_write_state
Trade-offs
- Benefit: read/write scaling and a complete audit trail — queries stay fast on tailored views while every state change remains replayable history.
- Benefit: temporal insight — past states can be reconstructed and new views derived without migrating the write path.
- Cost: two models to maintain plus projector lag — reads are eventually consistent and debugging spans commands, log, and projections.
- Cost: event-schema and storage discipline — the immutable log grows forever and needs versioning, retention, and replay tooling.
When to Use / When Not to Use
Use when:
- Reads and writes scale or evolve differently; audit/replay matters.
Avoid when:
- Simple CRUD with one model sufficing — the split adds cost.
Anti-pattern / Failure Mode
- Misuse: Applying CQRS to every aggregate, duplicating models with no scaling need.
- Review signal: Event log with no schema evolution plan.
Failure Modes / Trade-offs
- Event log as mutable database: teams patch history to fix projections, destroying the audit guarantee. Corrections should be new facts with a clear relationship to earlier events.
- Leaky event schema: serialized class internals become permanent public history, making refactoring hazardous. Use explicit business schemas and tested upcasters.
- Read-your-write surprise: a command returns success but an immediate query shows the old view. Return the new version, use a command result view, or apply bounded consistency waiting only where required.
- Complexity trade-off: independent read shapes and complete history are valuable, but every feature now touches commands, events, upcasters, projections, and replay tooling.
History review. Event payloads should record business facts and decision context, not secrets copied from request bodies; immutability makes careless sensitive data especially durable.
Projection review. Track lag per projection and partition, test rebuilds routinely, and keep projector code versioned alongside the read schema it produces.
Command review. Validate invariants against the aggregate’s replayed state and reject stale expected versions explicitly rather than overwriting another agent’s decision.
- Privacy trade-off: deletion requests may require crypto-shredding or separate personally identifiable data because rewriting an immutable history is not an acceptable erasure strategy.
- Storage trade-off: snapshots can shorten replay but add another versioned artifact and never replace the events needed for a new projection.
- Operations trade-off: read stores are disposable in theory only when replay capacity, backfill traffic, cutover, and correctness checks have been rehearsed.
Constraint-based use / avoid
| Constraint | Recommendation |
|---|---|
| Compliance requires attributable, reconstructable decision history | Use immutable events with access controls, schema governance, and tested retention rules. |
| Reads and writes have sharply different scale and query shapes | Use tailored projections and scale them separately from command validation. |
| Users require immediate globally consistent reads after every write | Avoid asynchronous projections on that path, or provide a synchronous read-your-write mechanism. |
| Small team with ordinary CRUD and no audit or replay requirement | Avoid event sourcing; current-state persistence is much cheaper to operate. |
| Storage budget cannot retain indefinite history | Use cautiously: define lawful archival and snapshot policies without silently deleting required audit facts. |
Related Patterns
- Event-Driven — shares events and brokers, but this pattern adds read/write separation and a persistent log as truth; event-driven alone is only about async delivery.
- Microservices — a service can adopt CQRS internally while still exposing a normal API to other services.
- Modular Monolith — a module can use event sourcing for its own state without distributing the whole system.
- Event Sourcing (#51) and CQRS (#52) — principle summaries.
- Event-Driven Payments — replayable payments exercise.