To keep the architecture evolvable without sacrificing reliability, use CQRS without Event Sourcing whenever read and write shapes diverge; adopt Event Sourcing only when an immutable audit log, temporal replay, or multi-projection architecture justifies handling eventual consistency and schema evolution.
TL;DR30-second simplified summary▾
Core Mechanics: CQRS (Command Query Responsibility Segregation) splits an application's data model into two paths: a Command side that validates business invariants and mutates state, and a Query side that reads pre-shaped, denormalized views.
Visual & Structural Flow: Depicts Event-Sourced Command Path & Asynchronous Read Projections (Command Handler -> Append-Only Event Log -> Postgres Read View -> Elasticsearch / OLAP); Optimistic Concurrency & Stream-Version Watermark (Client -> Command Agg -> Event Store -> Read Projection); Event-Sourced Command & Projection State Machine (HYDRATING -> APPENDED -> CONFLICT).
Trade-Offs & Production: Pick the simplest architecture that satisfies your audit, scaling, and consistency requirements. Never dual-write to Postgres and Kafka in separate calls—use a dedicated Event Store or the Transactional Outbox with Debezium CDC.
Failure Modes & Application: Explore how Transactional Outbox CDC, dual-write drift elimination, read-your-own-writes consistency, and event schema evolution support CQRS in production.
What are CQRS & Event Sourcing.
Why this matters: The mechanism: understand how CQRS & Event Sourcing works from first principles.
CQRS (Command Query Responsibility Segregation) splits an application's data model into two paths: a Command side that validates business invariants and mutates state, and a Query side that reads pre-shaped, denormalized views.
Event Sourcing changes how the Command side persists state. Instead of executing UPDATE accounts SET balance = 150, it appends immutable domain events (FundsReserved, TransferSettled) to an append-only log. Current state is the left-fold (reduce) of all events in that stream.
Event-Sourced Command Path & Asynchronous Read Projections
The append-only event log is the single source of truth; read projections tail it asynchronously without locking the write path.
Why we need CQRS & Event Sourcing (and Stale-Read Watermarks).
Why this matters: The problem: see what breaks without CQRS & Event Sourcing under real concurrency or scale.
Think of Why we need CQRS & Event Sourcing (and Stale-Read Watermarks) as the intuition layer for CQRS & Event Sourcing: The problem: see what breaks without CQRS & Event Sourcing under real concurrency or scale.
Traditional CRUD forces one normalized schema to serve both transactional invariant checks and complex reporting/search queries, causing lock contention and N+1 joins. However, decoupling write and read stores introduces projection lag (10–200 ms): returning streamPosition in the command response lets clients wait or fall back until the projection catches up.
Optimistic Concurrency & Stream-Version Watermark
Passing streamPosition=42 from command response to query read prevents stale UI flashes during async projection lag.
- Problem
- How to implement CQRS & Event Sourcing without hitting unbounded tail latency, state divergence, or operational fragility.
- Naive Solution
- Use a single unpartitioned path with unbounded retries and synchronous global coordination.
- Why It Fails
- Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
- Alternatives
- Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
- Engineering Decision
- To keep the architecture evolvable without sacrificing reliability, use CQRS without Event Sourcing whenever read and write shapes diverge; adopt Event Sourcing only when an immutable audit log, temporal replay, or multi-projection architecture justifies handling eventual consistency and schema evolution.
- Trade-Offs
- Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
When CQRS & Event Sourcing experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?
Double-Entry Payment Ledger (8,000 TPS)
Commands append FundsReserved and TransferSettled with expectedVersion checks, while async workers project into Postgres merchant dashboards and ClickHouse analytics without locking writes.
E-Commerce Search via Outbox + Elasticsearch
Separating the OLTP write model (Postgres + Transactional Outbox) from an Elasticsearch read projection cut OLTP CPU by 62% and reduced search p95 from 1.4s to 28 ms.
Where CQRS & Event Sourcing Fit (and Where CRUD Wins).
Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
Think of Where CQRS & Event Sourcing Fit (and Where CRUD Wins) as the intuition layer for CQRS & Event Sourcing: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
CQRS and Event Sourcing are orthogonal: you can use CQRS over a plain relational DB without Event Sourcing, and reserve Event Sourcing for domains that genuinely need an immutable audit log or temporal replay.
| Choice | What it buys | What it costs |
|---|---|---|
| Use: Financial Ledgers, Healthcare & Compliance | Structurally immutable audit trail of every state transition and business intent. | Requires event schema upcasters and crypto-shredding for GDPR erasure. |
| Use: Extreme Read/Write Asymmetry (100:1) | Write store stays append-only; read models use specialized Redis/Elasticsearch shapes. | Eventual consistency lag requires client-side `streamVersion` watermarks. |
| Avoid: Standard CRUD (Profiles, CMS, Simple Inventory) | Overwriting rows in PostgreSQL is far simpler and gives immediate strong consistency. | Event Sourcing adds unnecessary replay, snapshot, and upcasting complexity. |
How to manage Snapshots, Idempotent Projections & Upcasters.
Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.
1.
Optimistic Concurrency: Append events with expectedVersion so concurrent writers cannot overwrite invariants. 2. Periodic Snapshots: Snapshot aggregate state every 100–500 events so hydration latency stays bounded. 3.
How to manage Snapshots, Idempotent Projections & Upcasters
-- Idempotent projection checkpoint table in PostgreSQL
CREATE TABLE projection_checkpoints (
projection_name TEXT PRIMARY KEY,
last_stream_pos BIGINT NOT NULL
);
-- Inside projection consumer transaction:
INSERT INTO processed_events (event_id) VALUES (:event_id) ON CONFLICT DO NOTHING;
-- Only apply read-model UPDATE if 1 row was inserted above, then advance checkpoint.
Alternatives: CRUD vs. CQRS-Only vs. Full Event Sourcing.
Why this matters: The trade-off: compare competing approaches across latency, consistency, and operational cost.
Think of Alternatives: CRUD vs. CQRS-Only vs. Full Event Sourcing as the intuition layer for CQRS & Event Sourcing: The trade-off: compare competing approaches across latency, consistency, and operational cost.
Pick the simplest architecture that satisfies your audit, scaling, and consistency requirements.
Alternatives: CRUD vs. CQRS-Only vs. Full Event Sourcing
| Choice | What it buys | What it costs |
|---|---|---|
| Traditional CRUD (Single Model) | Zero projection lag; trivial schema migrations; minimal operational overhead. | Read/write lock contention under heavy analytics/search; loses state history. |
| CQRS + Transactional Outbox (State-Based) | Independent read stores (Elasticsearch/Redis) without immutable event-stream lock-in. | Eventual consistency on reads; no built-in temporal state replay. |
| Full CQRS + Event Sourcing (EventStoreDB) | Full temporal replay, auditability, and ability to spawn new read projections retroactively. | Requires upcasters for schema evolution, snapshots, and idempotent projection handlers. |
Production Architecture: Aggregate & Projection Lifecycle.
Why this matters: Production architecture: see how the components compose end to end under real load.
Think of Production Architecture: Aggregate & Projection Lifecycle as the intuition layer for CQRS & Event Sourcing: Production architecture: see how the components compose end to end under real load.
Never dual-write to Postgres and Kafka in separate calls—use a dedicated Event Store or the Transactional Outbox with Debezium CDC. Keep projection handlers strictly deterministic (no time.Now() or external HTTP calls during replay).
Event-Sourced Command & Projection State Machine
Optimistic concurrency on expectedVersion serializes conflicting writes to the same aggregate stream without distributed locks.
Problems solved & Related Concepts.
Why this matters: Applied problems: connect these internals to concrete system design and debugging scenarios.
Think of Problems solved & Related Concepts as the intuition layer for CQRS & Event Sourcing: Applied problems: connect these internals to concrete system design and debugging scenarios.
Explore how Transactional Outbox CDC, dual-write drift elimination, read-your-own-writes consistency, and event schema evolution support CQRS in production.
Practice: Make the trade-off yourself.
A user submits a command that updates their account balance and immediately refreshes the page, seeing their old balance because the async read projection is 120 ms behind. What is the cleanest fix?