Microservice Patterns
Event Sourcing
Store every change as an immutable event and derive current state by replaying them — gaining a full audit trail and time travel, at the cost of replay time that snapshots must keep in check.
What you will learn
- Explain the difference between storing state and storing events.
- Load an aggregate by replaying its stream and append new events with optimistic concurrency.
- See why long streams slow every command, and fix it with snapshots.
- Know when event sourcing pays off and when it does not.
Before you start
Overview
Your bank does not store just your balance — it stores every deposit and withdrawal. The balance is whatever those transactions add up to. If there is ever a dispute, the history explains exactly how you got there.
In event sourcing the source of truth is an append-only log of events per entity (a *stream*): AccountOpened, MoneyDeposited, MoneyWithdrawn. To handle a command, the service loads the entity by replaying its stream, decides which new events the command produces, and appends them. Nothing is ever updated in place.
| Storing state | Storing events | |
|---|---|---|
| What is saved | The latest row: balance = 120 | Every change: +100, +50, −30 |
| History | Lost unless you add audit tables | Built in — the log is the history |
| Loading | One read | Replay the stream (or snapshot + tail) |
| New questions about the past | Impossible if the data was overwritten | Replay events into a new projection |
Run it
In A, busy accounts grow their streams by hundreds of events and every command pays to replay them: watch p95 and Events replayed per load climb. B stores a snapshot every 50 events. Drag the snapshot interval to see the trade-off.
Load, decide, append
public Account load(String accountId) {
Optional<Snapshot> snap = snapshots.latest(accountId);
Account account = snap.map(s -> Account.fromSnapshot(s.state())).orElseGet(() -> Account.empty(accountId));
long from = snap.map(Snapshot::version).orElse(0L);
eventStore.readStream(accountId, from).forEach(account::apply); // replay only the tail
return account;
}
public void withdraw(String accountId, Money amount) {
Account account = load(accountId);
List<Event> newEvents = account.decideWithdraw(amount); // throws if balance too low
// Fails with ConcurrencyException if someone appended since we loaded — retry the command.
eventStore.append(accountId, account.version(), newEvents);
if (account.version() + newEvents.size() >= account.snapshotVersion() + SNAPSHOT_EVERY) {
newEvents.forEach(account::apply);
snapshots.save(accountId, account.version(), account.toSnapshot());
}
}Advanced Event sourcing almost always comes with CQRS: the event store is great for loading one entity by id but terrible for queries like "all accounts with a negative balance". Projections turn the stream into query-friendly read models, and publishing events to other services needs the same care as the Transactional Outbox — many event stores offer a subscription API for exactly this.
Trade-offs
| Benefits | Costs | |
|---|---|---|
| Audit & debugging | Complete, immutable history; replay to reproduce any past state. | Storage grows forever; old events need schema migrations (upcasting). |
| Performance | Appends are fast and contention-free per stream. | Loading costs grow with stream length — snapshots are mandatory for long-lived entities. |
| Flexibility | New read models can be built from past events at any time. | Querying requires projections; the team must learn a different way of modelling. |
Production considerations
- Use it where history is the business (ledgers, orders, compliance) — not for every CRUD table.
- Monitor stream length and replay time per load; alert before they hurt latency.
- Keep streams short-lived when you can (e.g. a stream per billing period rather than per account for life).
- Make snapshots disposable: they are a cache, rebuildable from events if the format changes.