Event Sourcing & CQRS

Store every change that happened instead of just the current state, and use separate models for writing and reading data.

What is it?

Most apps store only the current state: a bankAccount row with a balance column that each deposit or withdrawal overwrites. Then someone asks: "how did this account reach $340? What were the transactions?" That history is gone. You'd need a separate log from day one, and even then, rebuilding "the account at 3pm last Tuesday" from it is painful.

Event sourcing flips what you save. Instead of the balance, you store the ordered list of events that happened: AccountOpened, Deposited($100), Withdrew($40). The balance is never stored. It's calculated by replaying the events from the start (or from a saved checkpoint). You get:

- A complete, trustworthy history for free. - The state at any point in time. - The ability to fix a calculation bug and replay history to get the corrected current state.

A separate, often-paired problem: the data shape you want for writing (validate a transaction, apply rules, stay consistent) is very different from the shape for reading (a denormalized, pre-joined, fast, searchable dashboard view). One shared model is often slow for reads or awkward for writes.

CQRS (Command Query Responsibility Segregation) uses one model for writes ("commands", which change state) and another for reads ("queries", which just fetch data). They can even live in different databases, each optimized on its own.

The two often go together: events are a natural write model, and read views are built by projecting events into whatever shape reads need. But they're separate ideas solving separate problems, and you can adopt either one alone.

Explain like I'm 10

Event sourcing is a bank keeping every transaction slip instead of a whiteboard with today's balance: the balance can always be recomputed, and you can answer 'what happened on March 3rd?' CQRS is that bank having a teller window for withdrawals (built for correctness) and a separate printed monthly statement (built for readability): same account, built differently for different jobs.

Examples

Traditional state storage vs. event sourcing

// Traditional: only the current state is stored
// accounts table: { id: 1, balance: 60 }
// The history of how it got to 60 is gone.

// Event sourced: every change is stored, in order
const events = [
  { type: "AccountOpened", amount: 0 },
  { type: "Deposited", amount: 100 },
  { type: "Withdrew", amount: 40 },
];

function currentBalance(events) {
  return events.reduce((balance, event) => {
    if (event.type === "Deposited") return balance + event.amount;
    if (event.type === "Withdrew") return balance - event.amount;
    return balance;
  }, 0);
}

currentBalance(events); // 60 — same answer, but the full history is preserved

Both agree the balance is 60, but only the event-sourced version can answer 'what was the balance right after the deposit?' or 'replay history with a corrected fee calculation.'

CQRS: separate models for writing and reading

// Write model (command side): enforces business rules, one account at a time
class AccountCommandHandler {
  withdraw(accountId, amount) {
    const events = eventStore.load(accountId);
    const balance = currentBalance(events);
    if (balance < amount) throw new Error("Insufficient funds");
    eventStore.append(accountId, { type: "Withdrew", amount });
  }
}

// Read model (query side): a denormalized view, rebuilt from events,
// optimized for a dashboard showing every account at once
class AccountSummaryProjection {
  onEvent(event) {
    if (event.type === "Withdrew") {
      dashboardDb.updateBalance(event.accountId, -event.amount);
    }
  }
}
// A dashboard query just reads dashboardDb directly — fast, pre-computed,
// and never touches the event store or the write-side business rules.

A withdrawal is strictly validated against the event history (the write/command side). The dashboard reads from a separate, pre-computed, denormalized store built by 'projecting' events as they happen (the read/query side). Each side is optimized for its own job.

How it works

A command (like "withdraw $40") is validated against the current state, rebuilt by replaying events (often from a periodic snapshot, so you don't replay all of history each time). If valid, a new event is appended to an append-only event store.

Separately, projections listen for new events and update their read-optimized views: a search index, a dashboard table, a cache. Reads never touch the command path; they query the projection directly.

Command  --> [ validate against replayed state ] --> Event Store (append-only)
                                                             |
                                                             v
                                                     Projection(s) update
                                                     read-optimized views
                                                             |
  Query    <--------------------------------------- Read Model(s)

Why does it exist?

Event sourcing exists because "just the current state" throws away what many systems eventually need: audit trails, debugging ("how did we get into this bad state?"), and fixing calculation bugs retroactively by replaying corrected logic over history.

CQRS exists because one shared model for reads and writes is a lose-lose compromise. Normalized, it's safe for writes but slow and awkward for the complex reads a UI wants. Denormalized, it's fast for reads but risks inconsistent writes. Splitting them lets each side be optimized for its own job.

When to use it

Use event sourcing when a full audit history is a real business requirement (financial ledgers, inventory changes, anything regulators or support teams must reconstruct), or when "what happened, and in what order" is valuable data itself.

Use CQRS when read and write patterns have truly diverged: heavy, complex reads (dashboards, search, reports) alongside a write side that needs strict validation.

When not to use it

Both add a lot of complexity:

- Event sourcing: every "current state" query needs replay logic (or snapshot infrastructure), and event schema changes need care, since old events never disappear. - CQRS: you run two models and keep them in sync, often with eventual consistency between them.

For a typical CRUD app with aligned read/write needs and no audit requirement, that's heavy overhead for no real benefit. Plain current-state storage is simpler and should be the default.

Common mistakes

  • Adopting event sourcing with no plan for event schema changes. Old events were recorded in an old shape and can't be rewritten, only accommodated.

  • Assuming CQRS needs two databases and heavy infrastructure from day one, when a simpler version (two query paths against related tables) captures much of the benefit far more cheaply.

  • Using event sourcing 'because it's interesting' on a system with no real audit or replay need.

Practice exercises

  1. Easy:

    Given a shopping cart's events (ItemAdded, ItemRemoved), write a function that computes the current cart contents by replaying them.

  2. Medium:

    Design the events (names and payloads) needed to fully event-source a simple task tracker's task lifecycle (created, assigned, completed, reopened).

  3. Hard:

    For an e-commerce order system, describe how you'd split the write model (placing/cancelling orders) from a read model (a customer-facing order history page), including what a projection must do to keep the read model updated.

Interview questions

What problem does event sourcing solve that traditional current-state storage doesn't?

It keeps the full history of how the system reached its current state, not just the final value. That enables audit trails, point-in-time reconstruction, and replaying history with corrected logic.

What does CQRS stand for, and what does it actually separate?

Command Query Responsibility Segregation. It separates the model that changes state (commands, which enforce business rules) from the model that reads state (queries, which can be denormalized and optimized for fast, convenient reads).

Why are event sourcing and CQRS often used together, even though they're separate concepts?

An event-sourced write model produces a stream of events, which is a natural source for building read-optimized projections. It gives CQRS's read side a complete, ready-made feed of every change.