Volume 6 · Chapter 3 — Enterprise Application Architecture and Design Patterns
CQRS and Event Sourcing
3.1 Introduction
Command Query Responsibility Segregation (CQRS) separates the model thatchangesstate from the model thatreadsit. The insight is that the two have fundamentally different needs: writes must enforce invariants and are usually normalised and transactional, while reads want denormalised, query-optimised shapes tailored to each screen. Event Sourcing is a complementary - but independent - pattern in which the source of truth is an append-only log of everything that happened, and current state is derived by replaying those events. You can adopt CQRS without Event Sourcing, and vice versa; combining them is powerful but adds real complexity.
3.2 CQRS Fundamentals
flowchart LR
Client["Client"] --> API["API"]
API -- "Command" --> WM["Write Model (aggregates)"]
WM --> WDB[("Write DB (normalised)")]
WM -- "events / projections" --> RDB[("Read DB (denormalised)")]
API -- "Query" --> QM["Query Model (thin)"]
QM --> RDB The command side accepts intent, loads an aggregate, enforces rules, and persists changes. The query side executes read-optimised queries against a model shaped for display, often bypassing the domain entirely and projecting straight to a DTO.
3.3 Commands and Handlers
public sealed record TransferMoneyCommand(Guid From, Guid To, decimal Amount);
public sealed class TransferMoneyHandler
: IRequestHandler<TransferMoneyCommand>
{
private readonly IAccountRepository _accounts;
private readonly IUnitOfWork _uow;
public async Task Handle(TransferMoneyCommand cmd, CancellationToken ct)
{
var from = await _accounts.GetByIdAsync(new(cmd.From), ct);
var to = await _accounts.GetByIdAsync(new(cmd.To), ct);
from!.Withdraw(Money.Usd(cmd.Amount));
to!.Deposit(Money.Usd(cmd.Amount));
await _uow.SaveChangesAsync(ct);
}
}
3.4 Queries and Read Models
public sealed record GetStatementQuery(Guid AccountId) : IRequest<StatementDto>;
public sealed class GetStatementHandler
: IRequestHandler<GetStatementQuery, StatementDto>
{
private readonly IReadDbConnection _read; // Dapper / raw SQL, no aggregates
public async Task<StatementDto> Handle(GetStatementQuery q, CancellationToken ct) =>
await _read.QuerySingleAsync<StatementDto>(
"SELECT * FROM StatementView WHERE AccountId = @id",
new { id = q.AccountId });
}
3.5 Benefits and Costs of CQRS
| Benefit | Cost / Risk |
|---|---|
| Reads and writes scale independently | Two models to keep in sync |
| Query models tailored per screen | Eventual consistency between write and read |
| Write model stays focused on invariants | More moving parts and operational overhead |
3.6 Event Sourcing Fundamentals
In an event-sourced aggregate, you never store the current state directly. Instead you store the ordered facts -AccountOpened,MoneyDeposited,MoneyWithdrawn- and rebuild state by folding over them. This gives a complete, immutable audit trail for free and lets you answer questions you did not anticipate when you designed the schema.
public sealed class Account // event-sourced aggregate
{
public AccountId Id { get; private set; }
public Money Balance { get; private set; } = Money.Zero;
private readonly List<object> _pending = new();
// Rebuild from history.
public static Account Rehydrate(IEnumerable<object> history)
{
var a = new Account();
foreach (var e in history) a.Apply(e);
return a;
}
public void Withdraw(Money amount)
{
if (amount > Balance) throw new InsufficientFundsException();
Enqueue(new MoneyWithdrawn(Id, amount)); // decide -> emit event
}
private void Enqueue(object e) { Apply(e); _pending.Add(e); }
private void Apply(object e) // evolve state from an event
{
switch (e)
{
case AccountOpened o: Id = o.Id; Balance = o.Opening; break;
case MoneyDeposited d: Balance += d.Amount; break;
case MoneyWithdrawn w: Balance -= w.Amount; break;
}
}
}
3.7 Rehydration and the Event Store
The event store is append-only. Loading an aggregate means reading its event stream and folding it; saving means appending new events with an expected version for optimistic concurrency.
sequenceDiagram autonumber participant H as CommandHandler participant ES as Event Store participant Agg as Account (rehydrated) participant Proj as Projection Worker participant Read as Read Model H->>ES: read stream "account-123" ES-->>H: [AccountOpened, MoneyDeposited] H->>Agg: Rehydrate(history) H->>Agg: Withdraw(50) Agg-->>H: pending [MoneyWithdrawn] H->>ES: append MoneyWithdrawn (expectedVersion=2) ES-->>H: ok (version=3) ES--)Proj: new event published Proj->>Read: update balance projection
3.8 Snapshots
For aggregates with thousands of events, replaying from the beginning becomes slow. Asnapshotstores the state at version N so rehydration loads the snapshot plus only the events after it. Snapshots are an optimisation, never the source of truth.
3.9 Projections and Event Replay
Projections transform the event stream into read models. Because the log is the source of truth, you can build a brand-new projection at any time by replaying history - which is how event sourcing lets you answer new questions and fix buggy read models by rebuilding them from scratch.
3.10 CQRS with .NET and MediatR
In .NET, CQRS is commonly implemented with a mediator (MediatR or a hand-rolled dispatcher). Commands and queries become messages; pipeline behaviours add validation, logging, and transactions in one place.
builder.Services.AddMediatR(cfg =>
cfg.RegisterServicesFromAssembly(typeof(TransferMoneyHandler).Assembly));
builder.Services.AddScoped(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
builder.Services.AddScoped(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>));
When should CQRS be used - and when should it not?
Use CQRS when read and write workloads diverge in shape, volume, or scaling needs: high read traffic with complex screens over a transactional write model, or a domain complex enough that a single model serves neither side well. Avoid it for simple CRUD, where one model and a repository are simpler and the eventual-consistency and dual-model overhead buy nothing. A pragmatic middle ground is “CQRS-lite”: keep one database but split command and query code paths, using thin read queries (Dapper) alongside a rich write model.
Does CQRS require two databases and eventual consistency?
No. CQRS is about separating the command and querymodels, not mandating separate storage. Many systems run CQRS against a single database - the write model uses aggregates, the read model runs tailored SQL over the same tables or over indexed views, and both are strongly consistent. You only take on a separate read store and eventual consistency when you need independent read scaling or radically different read shapes. Treat the second database as an optimisation you add when metrics justify it.
How do you handle the eventual consistency gap where a user writes then immediately reads stale data?
Several techniques: return the new state directly from the command response so the UI can update optimistically without re-querying; have the client read its own write from the write model for a short window; or use versioned reads where the client passes the expected version and the read side waits (or the UI shows a “processing” state) until the projection catches up. The key is to design the user experience around the gap rather than pretend it does not exist - and to keep projection lag low and observable.
How do you deal with event schema versioning in Event Sourcing?
Events are immutable and live forever, so you must evolve them without breaking old ones. Common strategies: only make additive, backward-compatible changes; use upcasters that transform an old event version into the new shape as it is read; or use weak serialisation (tolerant readers) that ignore unknown fields and default missing ones. For larger changes you introduce a new event type and keep applying both. Never rewrite history in place - that destroys the audit guarantee that justified event sourcing in the first place.
What are the real challenges of Event Sourcing at scale?
The hard parts are rarely the happy path. You must handle event versioning and upcasting as the model evolves, manage unbounded stream growth with snapshots and archiving, design idempotent projections that can be rebuilt safely, and cope with eventual consistency in every read. Debugging shifts from “inspect the row” to “replay the stream.” Tooling and operational maturity matter: you need good observability into projection lag, replay tooling, and a team that understands the model. Because of this cost, I reserve full event sourcing for subdomains where the audit trail and temporal queries are genuinely valuable - ledgers, trading, compliance - and use simpler persistence elsewhere.
How would you introduce CQRS/ES into an existing monolith without a big-bang rewrite?
Incrementally and by subdomain. I’d pick one bounded context where the read/write divergence or audit need is strongest, and start with CQRS-lite: split the code paths while keeping the shared database, adding tailored read queries. If a subdomain truly needs the audit trail, I’d introduce event sourcing behind the aggregate’s repository interface so the rest of the system is unaffected, then build projections into the existing read tables. I’d add a projection worker and monitor lag before moving any traffic. The strangler-fig approach lets the team learn the operational model on a low-risk context before expanding.
How do you guarantee that an event is both persisted and published exactly once?
The classic trap is a dual write - saving to the database and publishing to a broker in two separate operations, which can partially fail. The robust solution is thetransactional outbox: within the same database transaction that appends the event, you also insert a row into an outbox table. A separate relay process reads the outbox and publishes to the broker, marking rows as sent. Consumers must still be idempotent because the relay guarantees at-least-once delivery. This turns “exactly once” into “atomically recorded, at-least-once delivered, idempotently consumed,” which is what is actually achievable in a distributed system.
3.11 Banking Enterprise Scenario
A payments platform models the ledger with event sourcing: every debit and credit is an immutable event, giving auditors a perfect history and enabling temporal queries (“what was this balance at midnight?”). Command handlers rehydrate account aggregates from their streams, enforce funds rules, and append new events through a transactional outbox. Projection workers build denormalised read models - a fast balance view and a statement view - which the query side serves with plain SQL. When the team needs a new report, they add a projection and replay history, no schema migration required.
Chapter Revision Notes
- CQRS separates command and query models; it does not require two databases.
- Event Sourcing stores facts and derives state by folding events.
- Snapshots optimise rehydration; the event log stays the source of truth.
- Projections build read models and can be rebuilt by replay.
- Use an outbox for reliable event publishing; make consumers idempotent.
- Reserve full CQRS/ES for subdomains where they pay for their complexity.