CodeBlanks Logo Icon CodeBlanks

Event sourcing

Learn the event sourcing pattern.

What is event sourcing?

Event sourcing stores the events that produce state instead of storing state directly. State is rebuilt by replaying the events. This gives audit history and the ability to rewind time.

A replayEvents(events) function models this: state starts at 0, each event's effect is applied. Example: replayEvents([{amount: 10}, {amount: 5}, {amount: -3}]) returns 0 + 10 + 5 - 3 = 12. Events are immutable; they are only appended. This fits data with history such as bank balances and order status. Combined with CQRS, writes and reads run through separate models.

The event chain

An event chain is a sequence of immutable events appended in order. Each event carries an effect; the sum of effects yields the state. replayEvents walks this chain with a for...of loop.

Example: let state = 0; for (const e of events) { state += e.amount; }. For events = [{amount: 10}, {amount: 5}, {amount: -3}] state becomes 10, 15, 12 in turn. This is the logic of a real event store: events go to a log, the consumer replays them whenever needed. Because events never change, audit is safe; instead of deleting an old event, you append a compensating event.

Practice Write the event replay function

Write function replayEvents(events). Define let state = 0. Add for (const e of events) { state += e.amount; }. End with return state. Print console.log(replayEvents([{amount: 10}, {amount: 5}, {amount: -3}])).

Starter code

index.js
// Write the replayEvents function
// Start from state 0, apply each event's effect
// Print with [{amount: 10}, {amount: 5}, {amount: -3}]
// write here

Sample solution

index.js
function replayEvents(events) {
  let state = 0;
  for (const e of events) {
    state += e.amount;
  }
  return state;
}
console.log(replayEvents([{amount: 10}, {amount: 5}, {amount: -3}]));

Expected output

12

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How is state obtained in event sourcing?

index.js
replayEvents([{amount: 10}, {amount: 5}, {amount: -3}])
  • It is read directly from the table
  • It is taken from the cache
  • Events are replayed Correct answer
  • It is written to a constant

Explanation: State is obtained by replaying events.

2 Match each piece to its role

Term Meaning
event Immutable record
replay Applies events in order
amount Event's effect
compensating Offsetting event

3 Complete the loop body

Question
for (const e of events) {
  state += ____.amount;
}
Answer
for (const e of events) {
  state += e.amount;
}

Explanation: Each event's amount is added.

All lessons in Expert