Event sourcing: state as a log of events
Keep the history, derive the state
Section titled “Keep the history, derive the state”Most databases keep the current state: the balance of an account is a number in a row, and a withdrawal changes it. The earlier values are gone, unless something else wrote them down. Event sourcing turns this round. As the Azure Architecture Center puts it, instead of storing only the current state, you store the full series of actions taken on an object in an append-only store, which is the system of record. Martin Fowler’s definition is the same idea: whenever the state of the system changes, record the change as an event, and the state can be rebuilt by processing the events again at any time.
Mental model. A bank keeps your statement, a list of transactions, and the balance is what you get by adding them up. If the two ever disagreed, the statement would win. Event sourcing builds software the same way: the log is the record, and the balance is a view of it. Version control is the other familiar example: the commits are the log, and the working copy is the state.
Each entity, an account for instance, has its own stream of events: Deposited 100, Deposited 50, Withdrawn 30. The current state is found by replaying the stream from the start. The Azure Architecture Center calls this rehydration.
A command is handled in four steps. Load the entity’s stream and replay it to get the current state. Check the rule against that state: a withdrawal of 500 from a balance of 120 is refused. If the command is accepted, append the new event or events to the stream. If it is refused, nothing is appended at all.
A small event store
Section titled “A small event store”This example keeps the log in memory. It accepts or rejects commands, derives the balance by folding the events, refuses a second writer that read stale state, and uses a snapshot to avoid reading the whole log. The output is real, produced by the .NET SDK when the examples are checked.
// An event-sourced account: the log of events is the record, and the balance is derived by replaying it.// A snapshot saves the replay from starting at the first event, and the store refuses a write made on stale state.
var store = new EventStore();
// 1. Commands decide, events record. A rejected command appends nothing.Console.WriteLine(Handle(store, "Deposit", 100));Console.WriteLine(Handle(store, "Deposit", 50));Console.WriteLine(Handle(store, "Withdraw", 30));Console.WriteLine(Handle(store, "Withdraw", 500));Console.WriteLine(Handle(store, "Deposit", 20));Console.WriteLine($"log events={store.Events.Count} balance={Replay(store.Events).Balance} (derived, never stored)");
// 2. Two handlers read the stream at version 4, and both try to append: the second is refused.var seen = store.Events.Count;var first = store.TryAppend("Deposited", 10, expectedVersion: seen);var second = store.TryAppend("Deposited", 10, expectedVersion: seen);Console.WriteLine($"concurrency first={(first ? "appended" : "refused")} second={(second ? "appended" : "refused")} (the loser reloads and retries)");
// 3. A long stream: a snapshot every 1,000 events means a load replays at most 999 events instead of all of them.while (store.Events.Count < 1000) store.TryAppend("Deposited", 1, store.Events.Count);var snapshot = Replay(store.Events);for (var i = 0; i < 3; i++) store.TryAppend("Deposited", 10, store.Events.Count);
var all = Replay(store.Events);var fromSnapshot = Replay(store.Events.Skip(snapshot.Version), snapshot);Console.WriteLine($"snapshot at={snapshot.Version} balance={snapshot.Balance}");Console.WriteLine($"full replay events={store.Events.Count} balance={all.Balance}");Console.WriteLine($"with snapshot events={store.Events.Count - snapshot.Version} balance={fromSnapshot.Balance} (same balance, fewer events read)");
static string Handle(EventStore store, string command, int amount){ var balance = Replay(store.Events).Balance; if (command == "Withdraw" && amount > balance) return $"{command,-8} {amount,4} rejected: balance is {balance}, nothing appended"; store.TryAppend(command == "Deposit" ? "Deposited" : "Withdrawn", amount, store.Events.Count); return $"{command,-8} {amount,4} accepted: event {store.Events.Count} appended";}
// Folding the events from a starting state gives the current state. This is the whole idea of event sourcing.static State Replay(IEnumerable<Event> events, State? from = null){ var state = from ?? new State(0, 0); foreach (var e in events) state = new State(state.Version + 1, state.Balance + (e.Type == "Deposited" ? e.Amount : -e.Amount)); return state;}
record Event(string Type, int Amount);record State(int Version, int Balance);
class EventStore{ private readonly List<Event> _events = []; public IReadOnlyList<Event> Events => _events;
// Optimistic concurrency: the append succeeds only if the stream is still at the version the caller read. public bool TryAppend(string type, int amount, int expectedVersion) { if (expectedVersion != _events.Count) return false; _events.Add(new Event(type, amount)); return true; }}Deposit 100 accepted: event 1 appendedDeposit 50 accepted: event 2 appendedWithdraw 30 accepted: event 3 appendedWithdraw 500 rejected: balance is 120, nothing appendedDeposit 20 accepted: event 4 appendedlog events=4 balance=140 (derived, never stored)concurrency first=appended second=refused (the loser reloads and retries)snapshot at=1000 balance=1145full replay events=1003 balance=1175with snapshot events=3 balance=1175 (same balance, fewer events read)This is the exact code that produced this output, run with the .NET SDK when the site was built. Nothing runs in your browser.
Read the output in three parts. The first part appends 4 events and rejects a withdrawal of 500 against a balance of 120, which appends nothing. The balance of 140 is not stored anywhere: it is derived each time. The second part shows two handlers that read the stream at version 4 and both try to append. The first succeeds and the second is refused, because the stream has moved. This is the optimistic concurrency that the Azure Architecture Center describes: the event store rejects an append if the stream changed since it was read, and the handler reloads, checks the rule again and retries. It is what stops two withdrawals from both seeing the same balance.
Snapshots, so that a load does not read everything
Section titled “Snapshots, so that a load does not read everything”An account that has been open for 5 years, with 20 events a day, has 20 × 365 × 5, which is 36,500 events. If the store can read and fold 20,000 events a second, a made-up figure, loading that account replays for 36,500 / 20,000, which is 1.8 s. That is too slow for every request.
A snapshot saves the state at a point in the stream. Taking one every 1,000 events, a load starts from the last snapshot and replays at most 999 events: 999 / 20,000 is about 50 ms, and it is 36.5 times fewer events than the full stream. Over 5 years there are 36 snapshots for the account. The snapshot is an optimisation, not a new source of truth: the stream stays the record, and a snapshot can be thrown away and made again. Greg Young’s documents call this a rolling snapshot, a denormalisation of the state at a point in time, and note that it spares you from replaying the history of a stream that may hold a million events.
In the example above, the last part does this. After 1,003 events a full replay reads 1,003 events and a replay from the snapshot taken at event 1,000 reads 3, and both arrive at the same balance, 1,175.
Check your understanding: event sourcing
This quiz needs JavaScript to check your answers.
Reading is another matter
Section titled “Reading is another matter”If the only way to find out about an account is to replay its stream, then a question such as “which accounts have a negative balance?” would mean replaying all of them. Greg Young makes the point directly: you cannot ask the system for all users whose first name is a given value, because there is no representation of the current state to query. The answer is to build one. A projection listens to the events and keeps a table up to date, which is the read model of the previous lesson. The Azure Architecture Center calls these materialized views.
This is why the two are so often presented together. Young calls the relationship between CQRS and event sourcing symbiotic, and the Azure Architecture Center says that event sourcing is commonly combined with CQRS. But they are separate, and Fowler is explicit that event sourcing needs no asynchronous processing and no reader of the log other than the code that derives the working copy. You can use CQRS with ordinary tables. You can use event sourcing and read each account by replay, if you never need a question across accounts.
A message broker is not an event store either. The Azure Architecture Center warns against the confusion: a broker such as Kafka typically lacks the per-entity stream query and the optimistic concurrency, and works well as the distribution layer that fans events out to projections and other consumers.
Changing the past is not allowed
Section titled “Changing the past is not allowed”Events are facts, and facts are not edited. A withdrawal that should not have happened is corrected by adding an event that reverses it, a compensating event such as WithdrawalReversed. The wrong event stays, and so does the record that it was undone, which is the audit trail that was the point.
The format of events is the harder problem. The store keeps events for years, and the code that reads them changes. Say version 1 of Deposited has an amount, and version 2 adds a currency. The old events do not have one. The Azure Architecture Center lists strategies that may be combined:
- Tolerant reading. Consumers ignore fields they do not know and use defaults for missing ones. This is enough for an added optional field.
- Versioning. Each event carries a version, and consumers choose their handling by it.
- Upcasting. A function converts an old event to the current shape as it is read, for example by adding a currency of EUR to every v1
Depositedevent, and several can be chained. The stored events do not change. - Rewriting the store. Migrating the stored events to the new format directly. This breaks immutability and undermines the audit trail, so the Azure Architecture Center advises it as a last resort.
Each change to an event leaves a conversion in the code for as long as the old events exist. After four changes there are four steps in the chain.
There is one more tension, with privacy. A store that never deletes cannot satisfy a request to erase a person’s data by deleting rows. The Azure Architecture Center describes two approaches: keep personal data outside the events and refer to it by id, so that it can be deleted on its own, or encrypt it in the events with a key for each person and delete the key, which is called crypto-shredding. Both need to be designed in from the beginning.
How big the log gets
Section titled “How big the log gets”Say a bank has 1,000,000 accounts, each recording 20 events a day, and an event takes 200 bytes. That is 1,000,000 × 20, or 20,000,000 events a day, which is 4 GB a day. After a year it is 4 GB × 365, or 1,460 GB, which is 1.46 TB, and after 5 years 7.3 TB. A store that holds only the current state of those accounts, 1 KB each, stays near 1 GB however long it runs. Storage is cheap, so this may be no problem. But the log only grows, and every rebuild of a projection reads the whole of it, which is why the cost of replay and the age of the snapshots matter.
When it pays and when it does not
Section titled “When it pays and when it does not”The Azure Architecture Center is direct. Event sourcing is a complex pattern that changes how you store data, handle concurrency, evolve schemas and query state. It is costly to migrate to or from, and for most systems and most parts of a system, traditional data management is enough. It fits when you need to capture intent, to keep an audit trail, to replay or rebuild state, or to avoid write conflicts, and it fits less when the operations are plain CRUD, when the system is a prototype, when the data is mostly static, or when the team has no experience with event-driven systems. And it need not be all or nothing: use it for a payment ledger or an order pipeline, and ordinary tables for user profiles and settings.
Fowler lists its problems: replaying events becomes difficult when results depend on outside systems, the schema of events changes over time, and many people find that it adds a lot of complexity.
The trade-off in one place
Section titled “The trade-off in one place”Event sourcing is not one of the four options of the explorer, but the same framework applies.
- Decision. Record every change as an event in an append-only log, and derive the state by replaying it.
- Why? The log gives a complete history, an audit trail, the ability to rebuild any state or read model, and appends that avoid update-in-place contention.
- Benefits. Auditability. State and read models that can be rebuilt, including new ones from old events. Appends instead of updates, with optimistic concurrency.
- Costs. A different way of storing, testing and querying. Events that cannot be edited, so schema changes and corrections need upcasting and compensations. Read models are needed for queries. Privacy needs a design.
- Failure modes. A bug writes wrong events that stay for ever. A duplicate event is applied twice by a consumer that is not idempotent. A load becomes slow as a stream grows.
- Scaling limitations. The log grows without limit, replay time grows with the length of a stream, and every projection must keep up with the append rate.
- Alternative. Ordinary current-state tables with an audit table, when you need the history but not the replay.
What happens if the events are wrong?
Section titled “What happens if the events are wrong?”A bug records 1,500 withdrawals for 10 euros too much. The events are in the store, and a projection and a notification service have already read them. Nothing can be updated in place. The fix is to append 1,500 compensating events, each returning 10 euros, which puts 15,000 euros back in total. The wrong events stay in the log, with the corrections after them, so anyone who audits the account sees what happened and when it was repaired. The projections are rebuilt, or take the compensating events as they come.
If the bug is also in the code that replays, there is a second problem: replaying the history with the fixed code can give a different answer from what the old code gave. The Azure Architecture Center advises integration tests of projections and of the paths along which the schema of events evolves for that reason. And the outside world is not undone by compensation: if one of those events sent an email, the email was sent.
- Event sourcing stores every change as an event in an append-only log. The state is derived by replaying the stream, and a command that is rejected appends nothing.
- Optimistic concurrency refuses an append made on a stream that has moved, so two handlers cannot both act on the same balance.
- 36,500 events (5 years at 20 a day) take 1.8 s to replay at 20,000 a second. A snapshot every 1,000 events cuts a load to at most 999 events, about 50 ms and 36.5 times fewer.
- Nothing is edited. Errors are corrected with compensating events (1,500 wrong withdrawals, 1,500 reversals, 15,000 euros), and the format of events changes by tolerant reading, versions and upcasting.
- The log grows: 1,000,000 accounts at 20 events a day of 200 bytes add 4 GB a day, 1.46 TB a year. It is separate from CQRS, which it often feeds, and from a broker.
Your progress
Built by GhaziAlibi.
© ShardCraft. All rights reserved.