CQRS and Event Sourcing

CQRS
Command Query Responsibility Segregation

Senior Frequently asked 5 min

On this page

The question

What is CQRS?

30-second answer

Command Query Responsibility Segregation separates the model that changes data from the model that reads it. Commands go to a write model that enforces the business rules; queries go to one or more read models, denormalized and shaped for each screen or API, often in a different database. The read models are updated from the write side's changes, usually asynchronously, so they can lag behind.

Understand it

Commands write events, projections build reads

Step by step

A client sends the command Withdraw 50 to account 7. Commands go to the write side, which only decides and records.

Step 1 of 7
View as text

On the left, the write side: a command, the account aggregate, and the event store listing the account's events. On the right, the read side: a query, a balance view and a statement view. Highlights show which parts act in each step.

A client sends the command Withdraw 50 to account 7. Commands go to the write side, which only decides and records.

The account has no balance column. The aggregate loads its 3 events and replays them: balance 120, so withdrawing 50 is allowed.

The decision is recorded as a new event, Withdrew 50, appended to the store. Events are never updated or deleted: the log is the source of truth.

A query right now still reads 120: the projection has not processed the new event yet. The read side is eventually consistent.

A projection subscribes to the events and updates a read model shaped for one question: the balance view now holds 70.

A second projection builds a different read model from the same events: the statement, one line per transaction. Each can use its own database.

Queries never touch the aggregate or the event store. They read a row already shaped for them, and the read side scales on its own.

On the left, the write side: a command, the account aggregate, and the event store listing the account's events. On the right, the read side: a query, a balance view and a statement view. Highlights show which parts act in each step.

A client sends the command Withdraw 50 to account 7. Commands go to the write side, which only decides and records.

The account has no balance column. The aggregate loads its 3 events and replays them: balance 120, so withdrawing 50 is allowed.

The decision is recorded as a new event, Withdrew 50, appended to the store. Events are never updated or deleted: the log is the source of truth.

A query right now still reads 120: the projection has not processed the new event yet. The read side is eventually consistent.

A projection subscribes to the events and updates a read model shaped for one question: the balance view now holds 70.

A second projection builds a different read model from the same events: the statement, one line per transaction. Each can use its own database.

Queries never touch the aggregate or the event store. They read a row already shaped for them, and the read side scales on its own.

Takeaway: With CQRS, commands and queries use separate models. With event sourcing, the write model is a log of events, and projections turn that log into read models shaped for each query, a moment later.

CQRS and event sourcing are separate choicesCQRS splits the model into a write side for commands and a read side for queries. Each side can store state as tables or, on the write side, as a log of events. Event sourcing stores the write side as events, and almost always comes with CQRS, because the log is hard to query directly.CQRS: separatewriteand read modelsWrite side storescurrent state: tablesWrite side storesevents: eventsourcingRead models fromchange data captureRead models fromprojections of events
CQRS and event sourcing are separate choicesCQRS splits the model into a write side for commands and a read side for queries. Each side can store state as tables or, on the write side, as a log of events. Event sourcing stores the write side as events, and almost always comes with CQRS, because the log is hard to query directly.CQRS: separatewriteand read modelsWrite side storescurrent state: tablesWrite side storesevents: eventsourcingRead models fromchange data captureRead models fromprojections of events
CQRS and event sourcing are separate choices

In code

sealed interface AccountEvent permits Opened, Deposited, Withdrew {}
record Opened(UUID id) implements AccountEvent {}
record Deposited(long amount) implements AccountEvent {}
record Withdrew(long amount) implements AccountEvent {}

final class Account {
    private long balance;

    static Account replay(List<AccountEvent> history) {
        Account a = new Account();
        history.forEach(a::apply);                     // rebuild state: no balance column anywhere
        return a;
    }

    List<AccountEvent> withdraw(long amount) {         // decide, but do not change state here
        if (amount > balance) throw new InsufficientFunds(balance, amount);
        return List.of(new Withdrew(amount));
    }

    void apply(AccountEvent e) {
        switch (e) {
            case Opened o -> balance = 0;
            case Deposited d -> balance += d.amount();
            case Withdrew w -> balance -= w.amount();
        }
    }
}
An event-sourced aggregate: decide from past events, return new ones
@Component
class BalanceProjection {
    private final JdbcTemplate jdbc;

    BalanceProjection(JdbcTemplate jdbc) { this.jdbc = jdbc; }

    @KafkaListener(topics = "accounts.events", groupId = "balance-view")
    void on(StoredEvent e) {
        long delta = switch (e.event()) {
            case Deposited d -> d.amount();
            case Withdrew w -> -w.amount();
            case Opened o -> 0;
        };
        // Upsert, guarded by the event's position, so a replayed or duplicate event is applied once
        jdbc.update("""
            INSERT INTO balance_view (account_id, balance, position) VALUES (?, ?, ?)
            ON CONFLICT (account_id) DO UPDATE SET balance = balance_view.balance + EXCLUDED.balance,
                position = EXCLUDED.position WHERE balance_view.position < EXCLUDED.position""",
            e.accountId(), delta, e.position());
    }
}
A projection keeps a read model up to date, and can be rebuilt
// Wrong: the event log is no longer what happened; projections and audits now disagree
 Wrong eventStore.update(accountId, 2, new Deposited(10));     // was Deposited 100 by mistake

// Right: append the correction; replaying gives the right balance and keeps the trail
 Right eventStore.append(accountId, expectedVersion, List.of(new DepositCorrected(-90, "typo in amount")));
Correct a mistake with a new event, never by editing history
One command, then a query, through both sidesThe client sends a command. The write side loads the aggregate's events, checks the rule and appends a new event. A projection reads the event and updates the read model. Later, a query reads the read model directly.Read modelProjectionEvent storeWrite sideClientWithdraw 50load events, append Withdrew 50Withdrew 50balance = 70GET balance70
One command, then a query, through both sidesThe client sends a command. The write side loads the aggregate's events, checks the rule and appends a new event. A projection reads the event and updates the read model. Later, a query reads the read model directly.Read modelProjectionEvent storeWrite sideClientWithdraw 50load events, append Withdrew 50Withdrew 50balance = 70GET balance70
One command, then a query, through both sides

Solve it

Add a “balance at the end of each month” report to an event-sourced system

Accounts are event-sourced: the store holds every Opened, Deposited and Withdrew event since the system started three years ago. The only read model is the current balance. Finance now wants each account’s balance at the end of every month, for all three years. Explain how you add it without touching the write side.

  1. See that the data already exists. Every past balance can be computed from the events, so this is a new read model, not a new feature on the write side.
  2. Write a new projection. For each event, add its amount to the account’s running balance, and when an event falls in a new month, store the previous month’s closing balance.
  3. Replay from the start. Run the projection over all events, in order, into a new table, while new events keep arriving; then let it catch up and follow live.
  4. Switch readers when it is current. The report queries the new table; the old balance view is untouched.
  5. Check. For a few accounts, the latest month’s closing balance must equal the current balance view, and the sum of each month’s changes must match the events.
@Component
class MonthEndProjection {
    private final Map<UUID, Long> running = new HashMap<>();
    private final Map<UUID, YearMonth> month = new HashMap<>();

    void on(StoredEvent e) {                                    // called for every event, oldest first
        YearMonth m = YearMonth.from(e.occurredAt().atZone(ZoneOffset.UTC));
        YearMonth last = month.put(e.accountId(), m);
        if (last != null && !last.equals(m)) {
            reports.saveClosing(e.accountId(), last, running.get(e.accountId()));   // month ended
        }
        running.merge(e.accountId(), delta(e.event()), Long::sum);
    }

    void rebuild() { eventStore.readAll(0).forEach(this::on); }   // replay from position 0
}
A month-end projection, built by replaying every event

How to answer

  • Each side can be designed, stored and scaled for its own workload.
  • Read models can be rebuilt from the source of truth at any time.
  • The cost is more moving parts and eventual consistency on the read side.
  • It is applied to one bounded context, not to a whole system.

Common mistakes

  • Equating CQRS with event sourcing. Each can be used without the other, though they often go together.
  • Applying CQRS to simple CRUD (create, read, update, delete) screens, where one model would do and the extra parts only add lag and bugs.

Follow-up questions

What is event sourcing?

Instead of storing the current state and overwriting it, you store every change as an immutable event, in order, in an append-only event store. The current state is derived by replaying the events, and read models are built by projections that subscribe to them. You get a full audit trail, the ability to rebuild state at any point in time, and new read models from old data.

  • Events are facts in the past tense, such as Withdrew, and are never updated or deleted.
  • Mistakes are corrected with new events, not edits.
  • Optimistic concurrency on the aggregate's version stops two conflicting appends.

See it in the infographic: Commands write events, projections build reads

When are CQRS and event sourcing worth their cost, and when are they not?

CQRS pays when reads and writes differ a lot: complex rules on write, many differently shaped reads, or very different loads. Event sourcing pays when the history itself has business value, such as ledgers, audit-heavy domains or systems that must answer what was true at a past date. Neither suits simple CRUD, teams new to eventual consistency, or data that must be erased on request.

  • Event sourcing makes schema changes harder; old events live forever and need upcasting.
  • Deleting personal data in an immutable log needs crypto-shredding or separate storage.
  • Start with one bounded context, not the whole system.

See it in the infographic: Commands write events, projections build reads

In an event-sourced system, how do you change the shape of an event that is already stored?

Stored events never change, so the code must read every version. Add fields in a backward-compatible way with defaults. For larger changes, write a new event type or version, and an upcaster that converts old versions into the new shape when they are read. Version events explicitly, and keep old event classes or schemas as long as old events exist.

  • Weak schemas, such as JSON with optional fields, evolve more easily than rigid ones.
  • Rebuilding a read model replays old versions, so test projections against them.
  • Copy-and-transform the store only as a last resort, and keep the original.

See it in the infographic: Commands write events, projections build reads

How does CQRS help in a microservices system with a database per service?

A screen that needs data from several services cannot join their databases. A service can subscribe to the others' events and keep its own read model with exactly the joined data it needs, answering the query from one local table instead of calling several services on every request.

Check yourself

1. In a CQRS system with event sourcing, where does a query for the current balance read from?
Show answers
  • A read model that a projection keeps up to date: Correct. Queries use read models shaped for them, not the write side.
  • The event store, replaying the account's events on every request: Incorrect. That is how the write side loads an aggregate, too slow for every query.
  • The aggregate's balance column: Incorrect. An event-sourced aggregate has no stored balance column.
2. An event Deposited 100 was recorded, but the real deposit was 10. How do you fix it in an event-sourced system?
Show answers
  • Append a correcting event, such as a correction of minus 90: Correct. History stays true, and replaying gives the right balance.
  • Edit the stored event to say 10: Incorrect. Events are immutable; editing breaks audits and read models already built.
  • Delete the event and append Deposited 10: Incorrect. Deleting from the log loses what happened and confuses every projection.