Skip to main content
← CONCEPTS / SOFTWARE DESIGN & ARCHITECTURE
An end-to-end domain learning journey

CQRS &
Event Sourcing.

CQRS separates write-side command validation from read-side query projections, while Event Sourcing persists every state transition as an immutable append-only log of domain events rather than overwriting current rows.
Start the journey7 sections· Last modified Oct 23, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

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.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Event-Driven Architecture (EDA)
Event-driven architecture (EDA) decouples producers and consumers by broadcasting immutable state-change facts through an asynchronous message broker or durable event log.
Full walkthrough · 7 stages
01
STAGE 01 · WHAT IT ISL4 · FUNDAMENTALS

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.

Write / Read Split

Event-Sourced Command Path & Asynchronous Read Projections

Command HandlerHydrate + check invariantsAppend-Only Event LogexpectedVersion CASPostgres Read ViewIdempotent projectionElasticsearch / OLAPDenormalized search

The append-only event log is the single source of truth; read projections tail it asynchronously without locking the write path.

02
STAGE 02 · WHY WE NEED ITL4 · FUNDAMENTALS

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.

Read-Your-Own-Writes

Optimistic Concurrency & Stream-Version Watermark

ClientCommand AggEvent StoreRead Projection1. POST Transfer(expectedVersion=41)2. Append TransferSettled (v42)3. 200 OK { streamPosition: 42 }4. Async tail v42 (idempotentupsert)5. GET ?minVersion=42 (wait/read)

Passing streamPosition=42 from command response to query read prevents stale UI flashes during async projection lag.

Engineering Decision Framework
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.
Decision Exercise · Make the Call

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.

03
STAGE 03 · WHERE IT IS USEDL5 · APPLIED DESIGN

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.

ChoiceWhat it buysWhat it costs
Use: Financial Ledgers, Healthcare & ComplianceStructurally 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.
04
STAGE 04 · HOW IT IS MANAGEDL5 · APPLIED DESIGN

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.

Lifecycle & Failure Recovery

How to manage Snapshots, Idempotent Projections & Upcasters

admitsucceedbudget exceededInitializedProcessingInvariant MetDegraded Fallback
-- 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.
05
STAGE 05 · ALTERNATIVESL6 · SCALE & TRADE-OFFS

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.

Request & State Flow

Alternatives: CRUD vs. CQRS-Only vs. Full Event Sourcing

CallerService EntryCore ProcessorState Store1. Submit bounded request2. Apply domain invariant3. Persist or read state4. Return verified response
ChoiceWhat it buysWhat 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.
06
STAGE 06 · PRODUCTION ARCHITECTUREL7 · STAFF / PRINCIPAL

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).

Aggregate Lifecycle

Event-Sourced Command & Projection State Machine

Invariants pass + CASStale expectedVersionReload & retryHYDRATINGLoad snapshot + tailAPPENDEDexpectedVersion CASCONFLICTRetry on version mismatc

Optimistic concurrency on expectedVersion serializes conflicting writes to the same aggregate stream without distributed locks.

07
STAGE 07 · PROBLEMS SOLVED & FURTHER DEEP DIVEL7 · STAFF / PRINCIPAL

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 · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

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?

Recommended Learning Flow