Event Sourcing

Also known as: event log, event store.

Storing every change as an immutable event and working out the current state by replaying the events.

Synthetic dataExamples on this page use synthetic data created for illustration.

Definition

Event sourcing stores every change to a system as an immutable event, in order, instead of storing only the latest state. The current state, and any earlier state, is obtained by replaying the events up to the moment of interest.

In plain terms

A bank statement is event sourcing: it lists deposits and withdrawals, and the balance is the sum. Nobody stores “balance = 75” as the only fact, because then the history, the audit trail and any error could not be recovered.

The benefits are a complete history, the ability to rebuild state at any past moment and to recompute it with new rules. The costs are extra work to read the current state quickly (usually by keeping periodic snapshots) and care with events whose meaning changes over time.

Example

An account’s events:

#EventBalance after replaying up to here
1Deposited 100100
2Withdrew 3070
3Deposited 575

The current state is 75. Replaying only the first two events gives the state at that earlier moment, 70. If the withdrawal turns out to have been entered twice, a correcting event is added; the original stays visible.

Common misunderstandings

  • “It is the same as an audit log.” An audit log records changes about the data; here the events are the data.
  • “It requires a special database.” The idea is an append-only record of events; ordinary stores can hold it.
  • “Replaying is always cheap.” Long histories are usually shortcut with snapshots of the state.

References

  1. Martin Fowler. Event Sourcing . martinfowler.com, 2005.
  2. Martin Kleppmann. Designing Data-Intensive Applications . O'Reilly Media, 2017. ISBN 978-1449373320.