CQRS & Event Sourcing — System Design

CQRS: split the write model (commands, which can be refused and guard the business rules) from the read model (queries, read models that are precomputed and…

The treasurer of a savings club never erases a line in the cash book. Every deposit and withdrawal is written on its own line, and the old ones stay. The whiteboard on the wall shows each member's total, copied from the book. If the board gets a number wrong, you wipe it and copy it again from the book.

The two ideas in this lesson work exactly like that. Event sourcing means you don't store the latest state, but the list of everything that happened, and the state is worked out again from that list. CQRS (Command Query Responsibility Segregation) means splitting the model for writing from the model for reading. The cash book = the event store, the board = a read model, copying again = a rebuild.

CQRS: a write model and a read model

At TicketTune, writing and reading need different things:

With CQRS, the write side stores changes with its own model, and the read side prepares read models: tables or caches shaped exactly the way a screen needs them, already computed, with no JOINs. The read model for the concert page is a single row: { concert: 42, ticketsLeft: 9997 }.

This differs from a read replica (the Database Scaling lesson). A replica is a copy of the same database with the same schema. In CQRS, a read model may have a completely different shape, even in another database: Redis for the tickets left, Elasticsearch for concert search.

Event sourcing: store what happened

An ordinary database stores the latest state: tickets_left = 9997. Where that number came from is lost. With event sourcing, what you store is the sequence of events in an event store, a log you can only add to (append-only). This is Archipelago Concert's event stream:

v Event Content
1 ConcertOpened quota 10,000
2 TicketsOrdered order 1001, Budi, 2 tickets
3 TicketsOrdered order 1002, Siti, 4 tickets
4 OrderCancelled order 1002, Siti, 4 tickets
5 TicketsOrdered order 1003, Rina, 1 ticket

v is the stream version, the event's running number. The current state comes from a replay: start from nothing and apply the events one by one. 10,000 − 2 − 4 + 4 − 1 = 9,997. You get two things for free: a complete audit trail (Siti once ordered and then cancelled, and that isn't lost), and time travel: the state at any version is just a replay up to that version. After v3, there were 9,994 tickets left.

A refused command never becomes an event. An event is a fact that has already happened, so it can't be refused and is never changed or deleted. Cancelling doesn't delete v3; it adds v4.

Replaying into a read model

The function that turns events into a read model is called a projector, and its result is a projection:

// TicketTune: Archipelago Concert's event store (an example model)
const events = [
  { v: 1, type: "ConcertOpened", quota: 10000 },
  { v: 2, type: "TicketsOrdered", orderId: 1001, buyer: "Budi", qty: 2 },
  { v: 3, type: "TicketsOrdered", orderId: 1002, buyer: "Siti", qty: 4 },
  { v: 4, type: "OrderCancelled", orderId: 1002, buyer: "Siti", qty: 4 },
  { v: 5, type: "TicketsOrdered", orderId: 1003, buyer: "Rina", qty: 1 },
];

// Projector: apply one event to the read model
function project(model, e) {
  if (e.type === "ConcertOpened") return { ticketsLeft: e.quota, ticketsPerBuyer: {} };
  const per = { ...model.ticketsPerBuyer };
  if (e.type === "TicketsOrdered") {
    per[e.buyer] = (per[e.buyer] ?? 0) + e.qty;
    return { ticketsLeft: model.ticketsLeft - e.qty, ticketsPerBuyer: per };
  }
  if (e.type === "OrderCancelled") {
    per[e.buyer] -= e.qty;
    return { ticketsLeft: model.ticketsLeft + e.qty, ticketsPerBuyer: per };
  }
  return model; // unknown events are skipped
}

// Rebuild: replay every event from the start
const readModel = events.reduce(project, null);
console.log(`rebuild from v1 to v${events.length}`);
console.log("tickets left:", readModel.ticketsLeft);
console.log("tickets per buyer:", JSON.stringify(readModel.ticketsPerBuyer));

// Time travel: the state after v3
const before = events.slice(0, 3).reduce(project, null);
console.log("after v3, tickets left:", before.ticketsLeft);

The output:

rebuild from v1 to v5
tickets left: 9997
tickets per buyer: {"Budi":2,"Siti":0,"Rina":1}
after v3, tickets left: 9994

In a real system, the projector also keeps running: every new event is applied to the read model right away. As in the Event-Driven Architecture lesson, the read model is eventually consistent: it lags a little behind the event store.

Rebuilding a projection

Suppose the concert page's projector was written without the OrderCancelled branch. When v4 arrives, the projector skips it. The concert page shows 10,000 − 2 − 4 − 1 = 9,993, and Siti's "My tickets" still says 4. That's 4 tickets off the real number, 9,997.

In an ordinary database, wrong data like this has to be patched by hand. With event sourcing, the event store is right; only the copy is wrong. So: fix the projector code, empty the read model, then replay every event from v1. That's rebuilding a projection. The same move creates a read model that never existed before, such as "sales per hour", from all the old events.

Snapshots: replays that don't run too long

To validate a command, the write side must know the stream's current state, which means a replay. Five events are cheap. A concert with 30,000 orders and cancellations means 30,000 events for every new command. A snapshot is the state stored at a given version. With a snapshot every 100 events, a command reads the latest snapshot plus at most 99 events after it. A snapshot is only a cache: if it's lost, it can be rebuilt from the events.

Two commands can also replay the stream at the same time. Budi and Siti order at the same moment: both commands replay up to v5, both pass validation, and both add an event. If only 2 tickets are left and each orders 2, the concert sells more than its quota. That is why an event store accepts an append only if the stream is still at the version that was read (optimistic concurrency):

function append(stream, newEvent, versionRead) {
  if (stream.length !== versionRead) {
    throw new Error(`version changed: read v${versionRead}, now v${stream.length}`);
  }
  stream.push({ ...newEvent, v: versionRead + 1 });
}

const version = events.length; // Budi's command and Siti's command both replay up to v5
append(events, { type: "TicketsOrdered", orderId: 1004, buyer: "Budi", qty: 2 }, version); // becomes v6
try {
  append(events, { type: "TicketsOrdered", orderId: 1005, buyer: "Siti", qty: 2 }, version);
} catch (e) {
  console.log(e.message); // version changed: read v5, now v6
}

Siti's refused command runs again: it replays up to v6, then validates again with the latest number of tickets left. In an SQL table, the constraint UNIQUE (stream_id, version) guards the same thing: a second insert for version 6 fails with UNIQUE constraint failed (tested on SQLite).

🤔 When to use it

CQRS + event sourcing adds a lot of parts: an event store, projectors, rebuilds, snapshots, and read models that lag. It's worth it when the domain has complex business rules, needs an audit trail (finance, ticketing, insurance), and reads and writes look very different. A simple CRUD app needs one table and one model. CQRS also works without event sourcing: an ordinary write table, plus a read model updated after every write.

📌 Events that change shape

Old events must not be edited. When their shape changes, say version 2 of TicketsOrdered adds a category field, the projector must still read version 1: assume the category is "Regular", or convert old events to the new shape as they are read (upcasting).

⚠️ Read models that are quietly wrong

TL;DR: CQRS: split the write model (commands, which can be refused and guard the business rules) from the read model (queries, read models that are precomputed and shaped for the screen), so each can be optimised on its own. Event sourcing: state isn't stored as the latest value but as a sequence of events in an append-only event store, and the state is rebuilt by replay (Archipelago Concert: 10,000 − 2 − 4 + 4 − 1 = 9,997). A projector turns events into a read model; when a projector is wrong (it forgets OrderCancelled: 9,993), fix it and rebuild from v1. The bonus is an audit trail and time travel. Snapshots store the state at a given version so replays don't run too long. Use it when the domain is complex, needs an audit trail, and reads and writes differ a lot; not for simple CRUD.

⚡ Separate write and read models

Meaning: CQRS splits the model for commands (writes, which can be refused and guard the business rules) from the model for queries (reads, with no side effects), so each can be optimised on its own. The concert page's read model is a single row: { concert: 42, ticketsLeft: 9997 }.

⚡ Store what happened, not the result

Guess first: the quota is 10,000. Budi orders 2, Siti orders 4 then cancels, Rina orders 1. How many tickets are left?

9,997: 10,000 − 2 − 4 + 4 − 1. And Siti's cancellation stays on record; it isn't lost.

Meaning: Event sourcing stores the sequence of events in an event store you can only add to. The current state comes from a replay: start from nothing and apply the events one by one.

⚡ Replay into a read model

Write:

// Rebuild: replay every event from the start
const readModel = events.reduce(project, null);
console.log(`rebuild from v1 to v${events.length}`);
console.log("tickets left:", readModel.ticketsLeft);

Meaning: The projector applies one event to the read model. events.reduce runs it from v1 to v5. Replaying only up to v3 is time travel: 9,994 tickets were left then.

⚡ A wrong projector? Rebuild

Meaning: A projector that forgets the OrderCancelled branch shows 9,993. The event store is right; only the copy is wrong. Fix the projector, empty the read model, then replay every event from v1.

What you will learn