Event Sourcing — Design Patterns

Event Sourcing keeps the sequence of events that happened (append-only, past-tense names, never changed), not just the latest state. The current status is a…

A bank passbook doesn't just record the balance. Each transaction is printed as one line: deposit, withdrawal, admin fee. The balance on the last line is the result of every line above it. When the bank records something wrong, the old line isn't erased: they add a correcting line, so both the mistake and the fix stay visible.

Event Sourcing stores data the same way. What's kept is the sequence of events that changed the data, not just the latest state. The current state is worked out by replaying every event from the start.

The problem: a table that only remembers the latest state

With plain CRUD, the shipments table has a status column, and every scan overwrites it: transit becomes delivering, then delivered. The old state is gone. When a customer asks "why did I get an SMS saying my parcel was received when it wasn't?", the table only knows the current status. There's no trace of who scanned what, and when.

Events: facts that already happened

const log = [
  { time: "08:10", type: "PickedUp" },
  { time: "11:30", type: "ArrivedAtWarehouse", city: "Bristol" },
  { time: "19:45", type: "ArrivedAtWarehouse", city: "London" },
  { time: "07:20", type: "OutForDelivery" },
]

The current status = replaying every event

function apply(state, e) {
  switch (e.type) {
    case "PickedUp": return { ...state, status: "picked_up" }
    case "ArrivedAtWarehouse": return { ...state, status: "transit", city: e.city }
    case "OutForDelivery": return { ...state, status: "delivering" }
    case "Received": return { ...state, status: "delivered", recipient: e.by }
    case "ReceiptCancelled": return { ...state, status: "delivering", recipient: null }
    default: return state
  }
}
const INITIAL = { trackingNo: "KCL-0001", status: null, city: null, recipient: null }
const rebuild = (events) => events.reduce(apply, INITIAL)

console.log(rebuild(log).status)              // delivering
console.log(rebuild(log.slice(0, 3)).status)  // transit
event status after it city
start null null
#1 PickedUp picked_up null
#2 ArrivedAtWarehouse Bristol transit Bristol
#3 ArrivedAtWarehouse London transit London
#4 OutForDelivery delivering London

Projections: many views from the same log

From the same events you can build other views. The history on the tracking page is one of them:

const LABEL = {
  PickedUp: () => "picked up by the courier",
  ArrivedAtWarehouse: (e) => "arrived at the warehouse in " + e.city,
  OutForDelivery: () => "out for delivery with the courier",
  Received: (e) => "received by " + e.by,
  ReceiptCancelled: (e) => "receipt cancelled: " + e.reason,
}
const history = (events) => events.map((e) => e.time + " " + LABEL[e.type](e))
// ["08:10 picked up by the courier", "11:30 arrived at the warehouse in Bristol", ...]

A view built from events is called a projection, exactly the read model from the CQRS lesson. A new report, say "how long parcels stay in each warehouse", is just a new projection run over the old events. The data has been there since day one.

A wrong scan: correct it with a new event

The courier scanned the wrong house: KCL-0001 was recorded as Received by Mr. Joko, and the "already received" SMS went straight to the customer. The way to fix it is to add an event, not delete one:

function append(e) {
  log.push(e)
  if (e.type === "Received") console.log("SMS sent: KCL-0001 received by " + e.by)
  if (e.type === "ReceiptCancelled") console.log("SMS sent: correction, KCL-0001 not received yet (" + e.reason + ")")
}

append({ time: "10:05", type: "Received", by: "Mr. Joko" })
append({ time: "10:40", type: "ReceiptCancelled", reason: "wrong scan" })
console.log(rebuild(log).status, log.length) // delivering 6

The status is back to delivering, and the log holds 6 events: the wrong scan and its correction are both recorded. An event that cancels the effect of another event like this is called a compensating event.

delete the Received event add ReceiptCancelled
current status delivering delivering
the log 4 events, as if nothing happened 6 events, the mistake and the fix recorded
the "already received" SMS that was sent the log can't explain it explained by event #5, and followed by a correcting SMS
other projections that already read event #5 don't know the event is gone get the correction too

Snapshots and event versions

Snapshots. A parcel has few events, but a courier's COD balance can have hundreds of thousands after a few years. Replaying them all every time the balance is read is slow. Save a snapshot (the state a replay produced) every, say, 1,000 events. When loading, take the latest snapshot and replay only the events after it, 1,000 at most.

Event versions. Old events may not be changed, but the shape of an event can change. Say a new version of ArrivedAtWarehouse carries warehouse: { city, code }. If apply only knows the new version (e.warehouse.city), replaying an old event throws TypeError: Cannot read properties of undefined (reading 'city'). apply must know both versions: e.v === 2 ? e.warehouse.city : e.city. This is often underestimated, because old events stay around for years.

Two writers at once. A courier's COD balance is $100, and two withdrawals of $80 arrive at the same time on two servers. Both replay the same log, both see a balance of $100, and both pass validation. The balance becomes -$60. An event store prevents this with optimistic concurrency: an append names the version it read (the length of the log at that time), and it is refused if the log has grown since.

const ledger = [{ type: "Deposited", amount: 100 }]

function appendAt(event, versionRead) {
  if (ledger.length !== versionRead) throw new Error("Log changed: read again, then validate again")
  ledger.push(event)
}

const v = ledger.length // server A and server B both read v = 1, balance 100
appendAt({ type: "Withdrew", amount: 80 }, v) // server A: succeeds
try {
  appendAt({ type: "Withdrew", amount: 80 }, v) // server B: still uses v = 1
} catch (err) {
  console.log(err.message) // Log changed: read again, then validate again
}
console.log(ledger.length) // 2

Server B reads the log again: the balance is now $20, so its withdrawal is refused with Insufficient funds. In the exercise, createAccount runs in one process, so this check is not needed yet.

Exercise: createAccount

The exercise uses a simple account, like a courier's COD balance. createAccount(events) returns an object with four methods, and its balance is always the result of a replay:

rebuild(events) in the starter just calls createAccount(events). The console then shows 0, 120 (100 + 50 - 30), 3, Insufficient funds, invalid deposit, 120 from rebuilding the whole log, then 150 from rebuilding the first two events.

⚠️ When can the log no longer be trusted?

TL;DR: Event Sourcing keeps the sequence of events that happened (append-only, past-tense names, never changed), not just the latest state. The current status is a replay: events.reduce(apply, INITIAL), and log.slice(0, n) gives the state at any point in time. The same log can feed many projections, like the tracking page history. Mistakes are fixed with a correcting event (ReceiptCancelled), not by deleting: KCL-0001 is back to delivering and the log holds 6 events. apply must have no side effects and must know every event version; snapshots speed up replaying a long log. In the exercise: validate before the push, the balance is always a replay, so rebuilding the whole log gives 120 and the first two events give 150.

⚡ Keep what happened, not just the result

Meaning: CRUD keeps the latest state, so the old state is gone every time the status column is overwritten. Event Sourcing keeps the sequence of events that happened (append-only, past-tense names like PickedUp), then works the state out from it.

⚡ The current status = replaying the events

Write:

const INITIAL = { trackingNo: "KCL-0001", status: null, city: null, recipient: null }
const rebuild = (events) => events.reduce(apply, INITIAL)

Meaning: apply(state, e) returns a new state from one event. log.slice(0, 3) replays the first three events, so the state at any point in time can be worked out again. apply must have no side effects, like sending an SMS.

⚡ A wrong scan: correct it with a new event

Write:

append({ time: "10:05", type: "Received", by: "Mr. Joko" })
append({ time: "10:40", type: "ReceiptCancelled", reason: "wrong scan" })
console.log(rebuild(log).status, log.length)
Guess first: the log starts with 4 events and the status is delivering. After those two append lines, what gets printed?

delivering 6. The status is back, and the wrong scan and its correction are both recorded.

Meaning: An event already recorded is never changed or deleted. Mistakes are fixed with a correcting event.

What you will learn