Event sourcing
Store every change as an immutable event and derive current state from the history.
15 min readStore what happened, not just where you ended up
A conventional table stores the current balance of an account: 70. An event-sourced system stores the facts that produced it: AccountOpened, Deposited 100, Withdrew 30. Current state is a fold over the events, applied in order. Events are append-only and never updated; a correction is a new event (Reversed withdrawal), exactly as an accountant would record it. Ledgers, order lifecycles and collaborative documents fit this model naturally because their history is the business.
Loading state and snapshots
To handle a command, load the entity's events, replay them to get current state, check the command against it, and append new events. Concurrency is handled optimistically: append only if the stream is still at the version you loaded, otherwise reload and retry. Replaying 50 000 events on every command is slow, so take a snapshot every few hundred events and replay only the events since the snapshot.
What you gain
History is a first-class asset rather than something you wish you had kept.
- A complete audit trail by construction, not as a separate table that can drift
- Temporal queries: what did this account look like last Tuesday?
- New read models built later by replaying the full history
- Bugs can be diagnosed by replaying the exact sequence that caused them
What it costs
Event sourcing is powerful and expensive. Every event schema you publish must be readable forever, so evolving them needs care. Simple questions such as 'list overdue orders' require projections built from the events, which are eventually consistent. Deleting personal data from an immutable log needs techniques such as crypto-shredding (encrypting each user's data with a key you can destroy). Use it for the few domains where history matters, not as the default for every table.
Key takeaways
- Event sourcing stores immutable facts; current state is derived by replaying them
- Use optimistic concurrency on the stream version and snapshots to bound replay time
- It gives a built-in audit trail and the ability to build new views from history
- Reserve it for domains where history matters; it complicates queries and deletion
Sign in to track lessons and earn badges.