Skip to content
System Design Lab
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.

Advanced 4 min read· Updated 2026-11-18

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 stateStoring events
What is savedThe latest row: balance = 120Every change: +100, +50, −30
HistoryLost unless you add audit tablesBuilt in — the log is the history
LoadingOne readReplay the stream (or snapshot + tail)
New questions about the pastImpossible if the data was overwrittenReplay 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.

Loading simulation…

Load, decide, append

Aggregate with snapshots and optimistic concurrency
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

BenefitsCosts
Audit & debuggingComplete, immutable history; replay to reproduce any past state.Storage grows forever; old events need schema migrations (upcasting).
PerformanceAppends are fast and contention-free per stream.Loading costs grow with stream length — snapshots are mandatory for long-lived entities.
FlexibilityNew 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.

Further reading

Related topics