What Is Event Sourcing? Explained with Examples
On this page
Learning Objective
Explain the core inversion of event sourcing, that the sequence of changes is the source of truth and current state is a derived value, contrast it with conventional state-oriented storage, and describe how an aggregate is rehydrated from its event stream.
Concept Explanation
A conventional application stores current state. The orders table has a row per order with a status column, and when the order ships, the application overwrites 'paid' with 'shipped'. The previous value is gone. If you later need to know when it shipped, who marked it shipped, or what state it passed through, you need to have anticipated that question and written an audit table alongside. The database records what is true; it deliberately discards how it became true.
Event sourcing inverts this. The system stores the sequence of events that happened, appending each new one and never updating or deleting anything, and derives current state by folding that sequence. The orders table is replaced by an orders event stream containing OrderPlaced, PaymentCaptured, ItemAdded, ShipmentDispatched. Current state is not stored as the truth; it is computed, a left fold over the events with a reducer function that starts from an empty aggregate and applies each event in order. If you want to know the state of the order at any point in its history, you fold up to that point and stop.
The claim worth taking seriously is that this is not an exotic technique but the normal way that serious record-keeping has always worked. A double-entry accounting ledger never overwrites a balance; it appends transactions and derives the balance. A bank statement is an event stream and the balance is a projection. Version control stores commits, not the current file contents, and reconstructs the working tree by applying them. In each case the reason is the same: the sequence of changes contains strictly more information than the resulting state, and that extra information turns out to be worth keeping.
The unit of consistency in an event-sourced system is the aggregate, a term from domain-driven design meaning a cluster of entities with a boundary inside which invariants are enforced and which is loaded and saved as a unit. Each aggregate instance has its own stream, typically named like order-9f12, and events within a stream have a monotonically increasing sequence number. A command handler loads the aggregate by replaying its stream, validates the command against the resulting in-memory state, and, if the command is valid, appends one or more new events. It never mutates the existing events, because they are facts about the past and the past does not change.
That append-only discipline is what gives event sourcing its concurrency story. Because the aggregate knows the sequence number it was loaded at, the append can be conditional: write this event at expected version 7, and fail if the stream is already at version 8 because somebody else appended concurrently. This is optimistic concurrency control, and it gives strong consistency within an aggregate without any locking. The caller retries by reloading, revalidating, and reappending. Consistency across aggregates, by contrast, is not provided and must be handled with the saga and outbox techniques covered in the final phase of this course, which is the central reason aggregate boundaries have to be drawn thoughtfully rather than arbitrarily.
| Question | State-oriented storage | Event-sourced storage |
|---|---|---|
| What is stored | Current state; prior values overwritten | Every state change, appended, never modified |
| How is current state obtained | Read the row directly | Fold the event stream, or read a cached snapshot plus later events |
| History | Only what an audit table was built to capture | Complete and inherent - history is the storage format |
| Answering a new question about the past | Impossible if the data was not retained | Replay the log with a new projection |
| Concurrency control | Row locks or an optimistic version column | Conditional append at an expected stream version |
| Cost of a read | One indexed lookup | Fold over N events, mitigated with snapshots |
Worked Example: An Order Aggregate Rehydrated From Its Stream
The reducer below is the whole idea in one function. State is never stored; it is always the result of applying events in order, starting from nothing.
// The stream for aggregate order-9f12, as stored. Nothing here is ever updated.
// seq | type | data
// 1 | OrderPlaced | { customerId: 'c-771', items: [{sku:'KB-88', qty:1, priceCents:12900}] }
// 2 | ItemAdded | { sku: 'MS-12', qty: 2, priceCents: 2400 }
// 3 | PaymentCaptured | { amountCents: 17700, processorRef: 'ch_8812' }
// 4 | ShipmentDispatched | { carrier: 'UPS', tracking: '1Z99...' }
const EMPTY = { status: 'none', items: [], totalCents: 0, paid: false, version: 0 };
function apply(state, event) {
switch (event.type) {
case 'OrderPlaced':
return { ...state, status: 'placed', customerId: event.data.customerId,
items: event.data.items,
totalCents: sum(event.data.items) };
case 'ItemAdded':
return { ...state, items: [...state.items, event.data],
totalCents: state.totalCents + event.data.priceCents * event.data.qty };
case 'PaymentCaptured':
return { ...state, paid: true, status: 'paid' };
case 'ShipmentDispatched':
return { ...state, status: 'shipped', carrier: event.data.carrier };
default:
return state; // unknown event types are ignored, not fatal
}
}
function rehydrate(events) {
return events.reduce((s, e) => ({ ...apply(s, e), version: e.seq }), EMPTY);
}
// A command handler: load, decide, append conditionally.
async function handleCancelOrder(orderId) {
const events = await store.readStream(`order-${orderId}`);
const order = rehydrate(events);
if (order.status === 'shipped') throw new Error('Cannot cancel a shipped order');
if (order.status === 'cancelled') return; // already true, idempotent
// Optimistic concurrency: fails if anyone appended since we read.
await store.append(`order-${orderId}`, { type: 'OrderCancelled', data: { reason: 'customer_request' } },
{ expectedVersion: order.version });
}
// Folding only the first two events gives the exact state as of that moment -
// the same query that answers "what did this order look like before payment?"Real-World Examples
- LMAX, the London-based financial exchange, built its trading platform around an event-sourced architecture in which a single-threaded business logic processor consumes an ordered input event stream and every state change is an output event. Martin Fowler documented the design publicly in 2011, and LMAX open-sourced the Disruptor ring buffer that feeds it. The event-sourced core is what let the exchange achieve both very high throughput and complete replayability of its trading state, since any historical position can be reconstructed by replaying the input stream.
- Nubank, the Brazilian digital bank that grew to be one of the largest financial technology companies in Latin America, has publicly described building its core banking ledger on an immutable, append-only model using Clojure and Datomic, where the database retains the full history of facts rather than overwriting them. Their engineering talks make the same argument this lesson does for a regulated financial domain: a ledger that discards how a balance was reached is throwing away exactly the information an auditor, a dispute investigator, or a debugging engineer will later need.
Review Questions & Answers
An audit log is a secondary record maintained alongside an authoritative current-state store, which means the two can drift, the log can be incomplete for anything nobody anticipated auditing, and the log can be modified or skipped by code paths that write directly to the state table. In event sourcing there is no separate current-state store to drift from: the log is the authoritative record, and current state is a derived value with no independent existence. Completeness is structural rather than a matter of discipline, because there is no way to change state except by appending an event.
When a command handler loads an aggregate it also records the stream version it read, say version 7. When it appends the resulting event it passes that number as an expected version, and the event store performs the append only if the stream is still at 7. If a concurrent writer already appended, the stream is at 8, the conditional append fails, and the handler reloads, revalidates the command against the new state, and retries. No lock is held between the read and the write, so a slow or crashed handler blocks nobody, and the conflict is detected at write time rather than prevented at read time.
Because event streams outlive the code that reads them. A stream may contain event types that were emitted by an older version of the service and later retired, or types emitted by a newer deployment that an older instance has not yet been updated to understand during a rolling deploy. Throwing on an unknown type would make a single obsolete or unrecognized event permanently unreadable and would break rehydration for every aggregate that ever emitted one. Ignoring unknown types keeps the fold tolerant, which is the same forward-compatibility principle the schema versioning lesson later in this phase develops in full.
It guarantees strong consistency inside a single aggregate, because every change to that aggregate goes through a conditional append at an expected version, so concurrent conflicting writes are detected and rejected rather than silently interleaved. It guarantees nothing about consistency across aggregates: two aggregates cannot be modified atomically, so a business rule spanning both must be handled through a saga with compensating actions, or by redrawing the aggregate boundary so the rule falls inside one. That is precisely why aggregate boundaries have to be chosen around invariants rather than around convenience.