Volume 9 · Chapter 5 — Enterprise Application Architecture & System Design

CQRS and Event Sourcing

Goutham Mayaluri 8 min read .NETC#

5.1 Introduction

CQRS and Event Sourcing are advanced patterns that pay off in complex domains where reads and writes have divergent needs and a complete history matters. CQRS separates the write model (which enforces invariants) from the read model (which is optimized for queries); Event Sourcing makes the source of truth an append-only log of events rather than current state. They are independent - you can use either alone - and both add real complexity, so the architect’s job is to apply them only where the payoff is concrete.

5.2 CQRS: Two Models, Different Shapes

The insight behind CQRS is that the ideal model for changing state (normalized, transactional, invariant-enforcing) is rarely the ideal model for reading it (denormalized, query-shaped per screen). Separating them lets each be optimized and scaled independently. Note this does not require two databases - many systems run CQRS as split code paths over one store, adding a separate read store only when read scaling demands it.

flowchart LR
  Client --> API
  API -- "Command" --> WM["Write Model\n(aggregates, invariants)"]
  WM --> Store[("Event Store / Write DB")]
  Store -- "events" --> Proj["Projections"]
  Proj --> RM[("Read Model\n(denormalized per view)")]
  API -- "Query" --> RM

5.3 Event Sourcing: State as a Fold Over Events

An event-sourced aggregate stores not its current state but the ordered events that produced it, rebuilding state by folding over them. This yields a perfect audit trail for free, enables temporal queries (“what was the balance at midnight?”), and lets you build new read models by replaying history. The cost is genuine: event versioning, storage growth, eventual consistency, and a different debugging model.


public sealed class Account
{
    public Money Balance { get; private set; } = Money.Zero;

    public static Account Rehydrate(IEnumerable<object> history)
    {
        var a = new Account();
        foreach (var e in history) a.Apply(e);   // fold events into state
        return a;
    }

    private void Apply(object e) => Balance = e switch
    {
        Deposited d  => Balance + d.Amount,
        Withdrawn w  => Balance - w.Amount,
        _            => Balance
    };
}

5.4 Projections, Snapshots, and Replay

Projections transform the event stream into read models and, because the log is the truth, can be rebuilt at any time by replaying history - which is how you add new views or fix a buggy read model. Snapshots optimize rehydration of long streams by storing state at a version so you replay only later events. Replay is also a recovery and migration tool.

5.5 Reliable Publishing with the Outbox

When events must both persist and publish, the transactional outbox writes the event into an outbox table in the same transaction as the state change, and a relay publishes committed rows - making state and event atomic while delivery stays at-least-once (so consumers must be idempotent).

Senior Interview Question

When should you use CQRS, and does it require separate databases?

CQRS is worth it when reads and writes genuinely diverge - very different scaling needs, or read shapes so different from the write model that one model serves neither well, or a domain complex enough that separating command and query responsibilities clarifies the design. It is overkill for simple CRUD, where one model and a repository are simpler. Crucially, CQRS does not require two databases: it separates the command and querymodels, and many systems run both over a single database - a rich write model plus thin read queries (Dapper/SQL) against the same tables or indexed views, staying strongly consistent. You introduce a separate read store and eventual consistency only when you need independent read scaling or a radically different read shape. So I often start with “CQRS-lite” - split code paths, shared store - and add the second store as a later optimization justified by metrics.

Senior Interview Question

What does Event Sourcing give you, and what does it cost?

It gives you a complete, immutable history as the source of truth: a perfect audit trail for free (invaluable in finance and compliance), the ability to answer temporal questions about any past state, and the freedom to build new read models by replaying events - so you can serve questions you did not anticipate at design time and rebuild buggy projections from scratch. The costs are real and often underestimated: events are immutable and live forever, so you must handle schema versioning with upcasters or tolerant readers; storage grows unbounded and needs snapshots and archiving; the read side is eventually consistent with the write side; and debugging shifts from inspecting a row to replaying a stream, which demands new tooling and team maturity. Because of this, I reserve full event sourcing for subdomains where the audit trail and temporal capability are genuinely valuable - ledgers, trading, compliance - and use simpler persistence elsewhere.

Senior Interview Question

How do you handle the read-after-write consistency gap in CQRS?

When the read model is updated asynchronously from the write model, a user who just made a change may query and see stale data. I design the experience around the gap rather than pretend it does not exist. Options include returning the new state directly in the command’s response so the UI updates optimistically without re-querying; having the client read its own write from the write model for a short window; showing a “processing” state until the projection catches up; or passing an expected version on the read so the read side can wait or the UI can detect staleness. Operationally I keep projection lag low and observable so the window is small and alertable. The key is that eventual consistency is a UX design problem as much as a technical one, and the interface should acknowledge the brief inconsistency gracefully.

Principal Architect Question

How would you introduce CQRS/Event Sourcing into an existing system incrementally?

Incrementally and by subdomain, never as a big-bang rewrite. I pick one bounded context where the payoff is clearest - typically one needing an audit trail or with a strong read/write divergence - and start with the lightest step: CQRS-lite, splitting command and query code paths while keeping the existing shared database, which delivers clearer separation and tailored reads with almost no new infrastructure. If a subdomain genuinely needs the audit trail and temporal queries, I introduce event sourcing behind that aggregate’s repository interface so the rest of the system is unaffected, and build projections into the existing read tables, adding a projection worker and monitoring its lag before moving any real traffic. This strangler-style approach lets the team learn the operational model - event versioning, projection rebuilds, eventual consistency, idempotency - on one low-risk context, prove the value, and only then expand. I resist applying these patterns platform-wide, because their complexity is justified only in the subdomains where history and independent read scaling actually matter.

Principal Architect Question

How do you guarantee an event is both persisted and published reliably in an event-sourced system?

The failure mode to avoid is the dual write - saving the event to the store and publishing it to the broker as two separate operations, which can partially fail and leave state and downstream consumers inconsistent. The robust solution is the transactional outbox: within the same transaction that appends the event to the event store, I also insert an outbox record, so persistence and the intent to publish commit atomically or not at all. A separate relay process then reads committed outbox records and publishes them to the broker, marking them sent. Because the relay guarantees at-least-once delivery, downstream consumers must be idempotent - deduplicating by event id or using naturally idempotent operations - so a redelivered event does no harm. This turns the impossible “exactly once” into what is actually achievable: atomically recorded, at-least-once delivered, idempotently consumed. It preserves the event store as the single source of truth while ensuring no committed event is ever lost or phantom on the wire.

5.6 Banking Enterprise Scenario

A bank event-sources its ledger: every debit and credit is an immutable event, giving auditors a perfect history and enabling temporal balance queries. Command handlers rehydrate account aggregates from their streams (using snapshots for long-lived accounts), enforce funds rules, and append new events through a transactional outbox. Projection workers build denormalized read models - a fast balance view and a statement view - served on the query side with plain SQL. When a new regulatory report is required, the team adds a projection and replays history, no schema migration needed. Elsewhere in the platform, simpler subdomains use ordinary CRUD, because the team applies event sourcing only where its audit and temporal power justify the cost.

Chapter Revision Notes

  • CQRS separates write and read models; it does not require two databases.
  • Event Sourcing stores events as truth and folds them into state.
  • Projections build read models and can be rebuilt by replay; snapshots speed rehydration.
  • Design the UX around the read-after-write eventual-consistency gap.
  • Use the outbox for reliable publishing; make consumers idempotent.
  • Apply these patterns only to subdomains where their complexity pays off.