Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 57 ยท Architectural and Modern Patterns

Event Sourcing

Learn Event Sourcing: store every change as an event, rebuild state by replay, speed it up with snapshots, and know when this pattern is worth its cost.

A normal database stores the current state. A bank account row says the balance is 120. If you ask how it got to 120, the database shrugs: earlier values were overwritten. You can add an audit log on the side, but then you have two sources of truth that can disagree.

Event Sourcing flips this. Instead of storing the state, you store the sequence of events that produced it: AccountOpened, Deposited 100, Deposited 50, Withdrew 30. The current state is not stored as the truth; it is computed by replaying the events. The event list is append-only, so nothing is ever overwritten. A bank ledger works exactly this way, and so does a Git history: the commits are the truth and the working tree is derived from them.

The core idea

flowchart LR
    C["Command:<br/>Withdraw 30"] --> A["Aggregate<br/>(checks rules)"]
    A -->|"appends"| ES[("Event store<br/>append-only")]
    ES -->|"replay"| A
    ES -->|"publish"| P["Projections,<br/>other services"]

A command is checked against the state rebuilt from past events; if allowed, a new event is appended, and others can read the same stream.

Four terms matter:

  • Event: a fact in the past tense that has happened and cannot be undone, named in business language (MoneyWithdrawn, not UpdateBalance). Events are immutable.
  • Event store: an append-only log, usually grouped into one stream per entity (all events of account 42). It supports "append" and "read the stream".
  • Aggregate: the object that decides whether a command is allowed. It rebuilds its state by applying its past events, then emits new ones.
  • Projection: a read model computed from events (see CQRS).

A runnable bank account

The aggregate has two kinds of methods. Command methods check rules and record events. An apply method changes state from an event and contains no rules, because past events must always be replayable, even if today's rules are stricter.

Node.js An event-sourced account

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The rejected withdrawal left no trace in the store, since only accepted events are appended. The last block shows optimistic concurrency: each append states which version it based its decision on, and the store refuses a write built on stale information. The loser reloads and tries again.

What you gain

  • A complete audit trail for free. Every change is recorded with when and why, in business terms.
  • Time travel. Replay up to any moment to see the state last Tuesday, or to debug how a bad state arose.
  • New read models later. You can add a projection next year and fill it by replaying history, which is impossible if you only kept current state.
  • Natural integration. The same events feed other services, search indexes and analytics.
Node.js Time travel and a new projection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Snapshots

Replaying thousands of events on every command gets slow. A snapshot saves the state at a certain version, say every 100 events. To load, read the latest snapshot and replay only the events after it. The snapshot is a cache: you can delete all of them and lose nothing.

Node.js Loading from a snapshot

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Both paths produce the same state; the second applies 100 events instead of 1000.

Costs and traps

  • Events are forever. You cannot edit history. To fix a mistake you append a compensating event (DepositCorrected). Plan event versioning from the start: when an event's shape changes, old events must still be readable, usually through an "upcaster" that converts old versions on load.
  • Queries are harder. "Show all accounts with a balance over 1000" cannot be answered by scanning streams. You need projections, which means eventual consistency, so event sourcing nearly always comes with CQRS.
  • Learning curve. Teams used to tables need time to think in events and replays.
  • Privacy and deletion. An immutable log clashes with "delete my data" requests. Common answers are encrypting personal data per user and discarding the key, or keeping personal data out of events.
  • Tooling. Schema migrations become event-version migrations. Debugging means reading streams.

CQRS versus Event Sourcing

CQRS Event Sourcing
Question it answers How do I model reads and writes separately? How do I store the write side?
Stores Anything A log of events
Needs the other? No No, but projections usually follow

When to use it

Event Sourcing is a good fit for domains where history is the business: finance and accounting, orders and logistics, anything with compliance audits or "what happened and why" questions, and systems that publish events anyway. It is a poor fit for simple CRUD, for data without meaningful history (a user's theme setting), or for teams that cannot afford the extra operational complexity. You can also event-source a single critical part, such as the ledger, and keep the rest in ordinary tables.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In Event Sourcing, what is the source of truth?

    State is derived by replaying events. Snapshots and read models are only caches or views of that log.
  2. 2. Why should the aggregate's apply method contain no business rules?

    Rules are checked before an event is recorded. When replaying history, every stored event must be applied, even one that a newer rule would reject.
  3. 3. What does the expected version passed to append protect against?

    Optimistic concurrency: the store rejects an append if the stream has grown since the writer loaded it, so the writer can reload and retry.
  4. 4. What is a snapshot?

    A snapshot is a cache of the state at a version. It can be deleted without losing data because the events remain.
  5. 5. A past event contains a mistake. What is the usual correct way to fix it?

    History is immutable, so you record a new event that corrects the outcome, such as a correction or reversal.

Summary

  • Event Sourcing stores every change as an immutable, past-tense event; current state is computed by replay.
  • Aggregates check rules in command methods and change state in a rule-free apply.
  • Optimistic concurrency uses the expected stream version to reject stale writes.
  • You gain an audit trail, time travel and the ability to build new read models from history.
  • Snapshots shorten replay; they are caches, not truth.
  • Costs: event versioning, harder queries (so projections and eventual consistency), privacy questions and a learning curve.

Next lesson: Event-Driven Architecture.