CQRS and Event Sourcing

Separating writes from reads with CQRS, storing state as events with event sourcing, aggregates and projections, snapshots, upcasting and GDPR, read-model consistency, when to use each pattern, and the tools.

On this page

Simple definition#

  • CQRS (Command Query Responsibility Segregation): use one model to change data (commands) and one or more different models to read it (queries).
  • Event sourcing: store every change as an immutable event, and derive current state by replaying them, instead of storing only the latest state.

They are often used together, but each works without the other.

The problem#

One model serving both writes and reads is a compromise. Writes need invariants and validation; reads need denormalised, fast, query-specific views such as search, dashboards and statements. Separately, many domains (ledgers, claims, trading) need the full history: what happened, when and why. A table that holds only “current balance” cannot answer that.

CQRS#

CQRS with event-driven read models · drawn with Archify · zoom, guided views, search and SVG/PNG export. © 2026 Samir Kumar Sahoo, all rights reserved. Open full screen ↗
  • Command side: handles intent (TransferMoney), loads the aggregate, enforces rules and stores the change.
  • Events flow (through the outbox or the event store) to projectors.
  • Read side: one read model per need, such as Elasticsearch or OpenSearch for search, Redis for hot lookups, a columnar store for analytics, or a SQL view for statements.

Levels of CQRS:

  1. Separate command and query classes on the same database (cheap and common).
  2. Separate read tables updated in the same transaction.
  3. Separate read stores updated asynchronously from events. This is eventually consistent.

Event sourcing#

State is a left fold over events
flowchart LR
    E1["AccountOpened<br/>v1"] --> E2["MoneyDeposited 100<br/>v2"] --> E3["MoneyWithdrawn 30<br/>v3"] --> E4["MoneyDeposited 50<br/>v4"]
    E4 --> S["Current state<br/>balance = 120, version 4"]

How a command works:

  1. Load the aggregate’s events (or the latest snapshot plus later events) and rebuild its state.
  2. Validate the command against that state.
  3. Append new events with optimistic concurrency (“expected version = 4”). On conflict, reload and retry.
  4. Publish the events to projections and other services.
// Aggregate (simplified)
class Account {
  private BigDecimal balance = BigDecimal.ZERO; private long version;

  List<Event> handle(Withdraw cmd) {
    if (balance.compareTo(cmd.amount()) < 0) throw new InsufficientFunds();
    return List.of(new MoneyWithdrawn(cmd.accountId(), cmd.amount()));
  }
  void apply(MoneyDeposited e) { balance = balance.add(e.amount()); version++; }
  void apply(MoneyWithdrawn e) { balance = balance.subtract(e.amount()); version++; }
}

Benefits#

  • A complete audit trail by construction, which regulators love.
  • Temporal queries: “what was the balance on 31 March?”
  • Rebuild or create read models by replaying events, including new ones you had not imagined.
  • A natural fit with event-driven integration.

Costs and hard parts#

Challenge Approach
Long event streams Snapshots every N events
Changing event schemas Upcasting (transform old events on read), versioned events, never edit history
Querying Always through projections; the event store is not for ad-hoc queries
Eventual consistency of reads Read-your-writes via version tokens, or query the write side for critical checks
GDPR / DPDP erasure Crypto-shredding: encrypt personal data per subject and delete the key; or keep PII outside events
Team learning curve Start with one bounded context where history matters

Read-model consistency#

After a command, the read model may lag by milliseconds to seconds. Options:

  • Return the new version from the command; the UI polls or waits until the read model reaches that version.
  • Optimistic UI: show the expected result immediately.
  • For critical decisions, read from the write model, never from a projection.

Tools#

Tool Notes
KurrentDB (formerly EventStoreDB) Purpose-built event store with streams and subscriptions
Axon Framework / Axon Server Java CQRS + event sourcing + sagas
Marten (.NET, on PostgreSQL), Eventuous Event sourcing on familiar databases
PostgreSQL event table events(stream_id, version, type, data, metadata) with a unique (stream_id, version)
Kafka Great for distributing events; poor as the only event store for aggregate loading (no efficient per-entity reads or optimistic concurrency)

When to use (and not)#

Use CQRS when… Use event sourcing when… Avoid when…
Read and write loads or shapes differ greatly Audit history is a core requirement (ledgers, claims, trading) Simple CRUD
Many specialised views of the same data You need temporal queries and replays The team is new to DDD and events, and the domain is not complex
You need to scale reads independently The domain is naturally event-based Strong consistency is needed everywhere on reads

Common mistakes#

Quick check#

What does CQRS separate? The model that handles commands (writes, with invariants) from the models that serve queries (reads, denormalised per use).

How is state derived in event sourcing? By replaying the aggregate’s events in order, optionally starting from a snapshot.

How do you handle a changed event schema? Version events and upcast old versions when reading. Never modify stored history.

How can event-sourced systems meet GDPR erasure? Crypto-shredding: encrypt personal fields per data subject and delete the key, or keep PII out of events.

Why not use Kafka alone as the event store? It has no efficient per-aggregate loading and no optimistic concurrency on an aggregate’s version.

Summary#

  • CQRS gives separate write and read models; read models are often eventually consistent.
  • Event sourcing stores immutable events as the source of truth, with audit, temporal queries and replay.
  • Plan for snapshots, upcasting, privacy and read-your-writes.
  • Use them where they pay off, not everywhere.

References#