Snapshots

A stream that grows without bound makes every load slower. A snapshot is a cache of the fold at one version: load it, replay only the events after it, and rebuild it from the events whenever it is wrong.

50 minutesChapter 15Event sourcing

inventory-service keeps the stock of a SKU as a stream of StockReceived and StockReserved events, and SKU-1503 is the popular one: 100,000 events and still growing. Every reservation loads the stream, folds it into the aggregate, decides and appends one event. The first load of the day reads all 100,000 rows. So does the second, and the load after a restart, and the load for a GET. The stream is correct, and the cost of reading it grows with every sale.

A stream of events ordered by version; a snapshot holds the fold of versions 1 to s, so a load reads one snapshot row and the events after s, where a load without it reads every event from version 1
Figure 15.1: A load reads the snapshot and the events after it

Learning objectives

  • Explain why an aggregate’s load cost grows with the length of its event stream
  • Write a snapshot in the same transaction as the command that crosses the threshold
  • Guard a snapshot upsert against an older write overtaking a newer one
  • Compare an inline snapshot against a Camel scheduled snapshotter for bounding the tail

Why this matters

When a stream only grows, like a popular SKU’s stock ledger, every load gets slower over time, and when a reservation takes over a hundred milliseconds instead of under one, it degrades every checkout that touches it. That growth stays invisible until the hot stream is the one being timed, by which point it is already affecting live latency. A snapshot avoids a second source of truth by remaining a disposable cache that the events can always rebuild, so the team never takes a shortcut in place of the real fix.

Pattern: Snapshot

The problem

An aggregate’s state is the fold of its events, so the work to load it is proportional to the length of its stream. Most streams stay short: an order has a handful of events. A ledger does not. Stock, an account or a counter takes an event for every change, and the oldest events still count in the answer.

The obvious fixes each give something up. Deleting old events destroys the history. A second table holding the current quantity is a second source of truth: nothing marks it as derived, so once it disagrees with the events neither can be trusted. Caching the aggregate in memory loses it on restart and does not help a second instance.

The solution

A Snapshot stores the aggregate’s state at one version, so that a load reads the snapshot and replays only the events after it.

Greg Young calls this a rolling snapshot and describes it as a heuristic: the stream is still the record, and the snapshot only controls how many events a load reads. Martin Fowler’s example is an overnight snapshot from which the day’s events are replayed. Three decisions make it safe.

A snapshot is a cache of the fold, never a source of truth. It can be deleted at any time and the events rebuild it, so a bug in how it was written costs time and not data. It describes the aggregate at exactly one version, a newer snapshot replaces it, and only the newest is kept. And the aggregate’s own code writes it, never a person, because a load believes whatever the snapshot says.

How Quarkus and Camel model it

InventoryItemAggregate can be built two ways: from its first event, or from an InventorySnapshot plus the events after the snapshot’s version. StockLedger chooses between them:

SnapshotRow snapshot = useSnapshot ? SnapshotRow.findById(sku) : null;
if (snapshot != null && snapshot.schemaVersion != config.snapshot().schema()) {
    meters.counter("inventory.snapshot.ignored").increment();
    LOG.infof("snapshot schema %d ignored for %s", snapshot.schemaVersion, sku);
    snapshot = null;
}
int from = snapshot == null ? 0 : snapshot.version;
long[] replayed = {0};
try (Stream<StockEvent> tail = tail(sku, from).peek(event -> replayed[0]++)) {
    aggregate = snapshot == null
            ? InventoryItemAggregate.replay(sku, tail)
            : InventoryItemAggregate.from(snapshot.state, snapshot.version, tail);
}

The schema version, inventory.snapshot.schema, describes InventorySnapshot. When the record changes meaning the version is raised, and every stored snapshot with the old value is skipped and rebuilt from the events. Young allows either rebuilding old snapshots after their structure changes or converting them; inventory-service only rebuilds.

The tail is read with a Panache projection, not entities:

StoredStockEvent.find("streamId = ?1 and version > ?2 order by version", sku, afterVersion)
        .project(Payload.class).withHint("org.hibernate.fetchSize", 500).stream().map(Payload::payload);

A projection matters for memory. A Panache stream() of entities still puts every row in the persistence context, so replaying 100,000 events holds 100,000 entities until the transaction ends. A projection to a record returns the payloads and nothing is managed.

ReservationTransaction loads, decides, appends, and then compares the new version with the snapshot’s:

if (config.snapshot().inline() && every > 0
        && aggregate.version() - loaded.stats().snapshotVersion() >= every) {
    store.upsert(aggregate, "inline");
}

The upsert is one SQL statement, written through the EntityManager because Panache has no native-query API:

INSERT INTO inventory.snapshots (stream_id, version, schema_version, state, taken_at, taken_by)
VALUES (?1, ?2, ?3, cast(?4 as jsonb), now(), ?5)
ON CONFLICT (stream_id) DO UPDATE SET version = excluded.version, schema_version = excluded.schema_version,
    state = excluded.state, taken_at = excluded.taken_at, taken_by = excluded.taken_by
WHERE excluded.version > inventory.snapshots.version

The WHERE is the guard. Two writers can compute snapshots from different versions, and without it the older one can arrive last and move the stored version backwards. A snapshot never conflicts with an appending command: it lives in its own table, keyed to a version, and the command that writes it has just appended at that version. Reads never write, so a GET on a stream that has none stays slow until a command arrives.

A lost race on a hot SKU is retried with @Retry(retryOn = ConcurrencyConflict.class) around the separate @Transactional bean, so each attempt is a new transaction that loads again.

Camel offers the other place to write the snapshot. SnapshotterRoute is Young’s out-of-band snapshotter: a timer, a query for the streams that are too far past their snapshot, and one call per stream.

from("scheduler:snapshotter?delay={{inventory.snapshotter.delay-ms}}")
        .setHeader("n", constant(config.snapshot().every()))
        .to("sql:" + TOO_FAR_BEHIND)
        .split(body())
        .setBody(simple("${body[stream_id]}"))
        .bean("snapshots", "take");

take loads the stream through the same StockLedger and writes with the same guarded upsert in a transaction of its own. A Quarkus @Scheduled method would do the same job in less code; a query, a split and a call per item is what a route expresses well.

What a rebuild costs

The timing is taken inside the service, around the snapshot read, the event read, the JSON mapping and the fold. For each stream, five loads are discarded and 21 are timed, with the full load and the snapshot load alternating so that drift affects both. The median is reported. The database is PostgreSQL on the compose stack and the machine is an 8-core laptop. Before the timing each stream is brought to a snapshot with 99 events after it, the longest tail the policy allows. The streams then hold 1,100, 10,100 and 100,200 events. Each figure is the median of three runs, each in a new JVM.

Median load times: a full replay takes 1.6 ms for 1,100 events, 11.6 ms for 10,100 and 127.7 ms for 100,200, and a snapshot load with 99 events after it takes 0.50 ms, 0.63 ms and 0.95 ms
Figure 15.2: A full load grows with the stream; a snapshot load stays under 1 ms
Stream Events in the stream Events replayed with a snapshot Median full load Median snapshot load Cost per event on a full load
SKU-1501 1,100 99 1.6 ms 0.50 ms 1.4 us
SKU-1502 10,100 99 11.6 ms 0.63 ms 1.2 us
SKU-1503 100,200 99 127.7 ms 0.95 ms 1.3 us

The full load is linear in the stream, and most of it is spent turning rows into events and folding them, not reading them: EXPLAIN (ANALYZE) puts the database read of the 100,200 event stream at 41 ms of the 128 ms. The snapshot load reads one row and 99 events, so it stayed under 1 ms on every stream in all three runs, and it rises from 0.50 ms to 0.95 ms while the full load rises from 1.6 ms to 127.7 ms. The state is 57 bytes of jsonb at any version, which is why the policy counts events and not bytes.

The cost per event gives the rule for N. A load replays at most N-1 events after a snapshot, so the worst case is N-1 times the per-event cost plus the fixed cost of reading the snapshot. A smaller N bounds the tail more tightly and writes more snapshots, each one a row version written inside a command. At N of 10 a load replays at most 9 events and 1,000 reservations write 100 snapshots; at N of 1,000 a load replays at most 999 events and 1,000 reservations write one.

Inline or out of band

Where the snapshot is written decides how long the tail can get.

Inline, the command that crosses N events writes the snapshot in the same transaction, so the tail stays below N; out of band, commands append without snapshots and a timer route takes them later, so the tail can pass N during a burst
Figure 15.3: Inline bounds the tail, out of band moves the cost
  Inline, in the command’s transaction Camel route on a timer
Tail after a load At most N-1 events N plus whatever arrives between two ticks
Cost on the command One upsert every N events None
Finding the work None One max(version) scan per tick, unless a head table is kept
Failure of the snapshot Rolls the command back The next tick retries; commands are unaffected
Streams nobody commands Never snapshotted Snapshotted when they pass N, bulk loads included
Same row, same guard Yes Yes

During a burst of 1,000 reservations with a route period of one second, the largest tail sampled reached 350 events with N at 100 (322 to 358 over three runs). Within eight seconds after the burst the stored snapshot was again less than N events behind the head, and the version it stored never went down. With a period of 30 seconds the tail grew to 974, almost the size of the burst.

Young’s snapshotter suits commands on a latency budget, or streams bulk-loaded without a snapshot. Inline is the default because it is the only arrangement that bounds the tail.

Build, run, observe

cd examples/15-snapshots
mvn -B verify
./verify.sh

verify.sh loads three streams, the largest of 100,000 events, and compares loads with and without a snapshot. Watch how many events a load replays after the snapshot. It prints 27/27 checks passed.

Try one change and rerun:

  • SNAPSHOT_EVERY=0 ./verify.sh: no snapshot is written and every load replays the whole stream.
  • SNAPSHOT_GUARD=false ./verify.sh (demo code): a stale snapshot replaces a newer one and the stored version goes down.
  • INVENTORY_FETCH=entities EXTRA_JAVA_OPTS=-Xmx96m ./verify.sh (demo code): replaying 100,000 events as managed entities runs out of heap with OutOfMemoryError.

When not to use it

Most streams do not need one. A stream of 1,100 events loads in 1.6 ms without one, and every snapshot is another thing to version, write and keep correct. Measure the load first.

A snapshot cannot repair a wrong fold. If the aggregate’s logic had a bug, the snapshot repeats it. Fix the logic, raise the schema version, and let the events rebuild every snapshot.

When the read side is hot, a projection is the better cache: a table kept up to date from the events and built for queries. Snapshots serve the load path of the aggregate only.

Common pitfalls

  • Turning off the snapshot makes every load replay the full stream again, returning a hot stream’s load time to its uncached cost.
  • Removing the version guard on the snapshot upsert lets a stale write overtake a newer one, moving the stored version backwards.
  • Replaying a long stream as managed entities instead of a projection keeps every row in the persistence context, which can exhaust the heap on a large stream.
  • Choosing a large N to reduce snapshot writes widens the tail a load must replay, trading write cost for read cost on every load.

🤖 Explore with your agent “In examples/15-snapshots, load SKU-1503, the 100,000-event stream, with and without its snapshot, then find where InventoryItemAggregate, StockLedger, SnapshotterRoute and inventory.snapshot.schema decide what a load replays. Set SNAPSHOT_EVERY to 10 and state the most events a load can replay and what it costs in snapshot writes.” Check: a load with a snapshot replays fewer than N events, a load without it replays the whole stream, and both give the same quantity and version.

References