Practical technical guides / Agent-era architecture: CQRS and event sourcing (snapshots)

Snapshot an Agent Case View With Its Projection Version, or a Code Change Serves Stale State

An agent reads a case view folded from events. A projection change over old snapshots hid a pending refund in 8 of 9 positions. Version each snapshot and test replay.

By Sandeep Belgavi · Published 2026-11-07

An agent reads a case view folded from events. A projection change over old snapshots hid a pending refund in 8 of 9 positions. Version each snapshot and test replay.

Why an agent reads a case through a projection

The help desk at Belgavi's Book Store records every case as an append-only stream of events: the case was opened, a note was added, a returned book arrived, a refund was requested, a refund was issued, the case was closed. Nothing is updated in place. When the help-desk agent picks up CASE-4127, it does not read those events one by one. It reads a case view: a small object folded from the stream that says the case is open, how many notes it has, how much has been refunded and, since the last release, which refunds are still pending.

That fold is the projection. In a CQRS system the projection is a read model; in an event-sourced aggregate it is the state you rebuild before handling a command. For an agent it is also the context the model sees, so a wrong projection is not a cosmetic bug. If the view says nothing is pending, the agent will happily offer a refund that has already been requested.

Long case streams make folding slow, so teams add snapshots. This guide is about the failure that appears when the fold function changes and old snapshots stay in place, and about the version check that prevents it. The companion code replays a synthetic 1,000-event case and shows each step.

Snapshots, briefly

A snapshot is the projection state at a known position in the stream. The Azure Architecture Center describes the standard approach: when streams are long, "create snapshots at specific intervals, such as every N events", then "load the most recent snapshot and replay only the events that occur after it". It adds the rule that matters here: "Snapshots are an optimization, not a replacement for the eventstream", and the stream "remains the source of truth, and you can regenerate snapshots from it at any time". Martin Fowler's original description of event sourcing makes the same point: application state is "purely derivable from the event log", so a snapshot is a cache.

For CASE-4127 read at event 930, a full replay folds 930 events. With a snapshot taken at event 900, the loader reads the snapshot and folds 30 events. That is the whole benefit, and it is real when an agent opens hundreds of long cases an hour.

The failure: a new fold over an old snapshot

The first version of the projection tracked status, notes and the refunded total. The agent sometimes offered a second refund while one was waiting for the finance team, so the team released projection version 2, which adds pending_refunds: an id is added on RefundRequested and removed on RefundIssued.

The fold code changed. The snapshots did not. The snapshot at event 900 was written by version 1, so it has no pending_refunds field. The loader takes the latest snapshot, defaults the missing field to an empty list and folds the 30 events after it. RefundRequested for RF-77 happened at event 121, long before the snapshot, so the tail never sees it.

Load pathEvents foldedpending_refundsAgent offers a second refund
Full replay with version 2930RF-77no
Version 1 snapshot at 900, version 2 tail30emptyyes
Version check, snapshot rejected, rebuild930RF-77no
Version 2 snapshot at 900, version 2 tail30RF-77no

Nothing crashes. Every test that only checks recent events passes, because the tail is folded correctly. The companion example checks every version 1 snapshot position from 100 to 900 against a full replay: the snapshot at 100 is harmless because the refund request is still in its tail, and the eight snapshots from 200 to 900 all produce a view with no pending refund.

The same thing happens without snapshots wherever a projection is persisted, such as a read model table that a new consumer version keeps updating incrementally instead of rebuilding.

What stays deterministic

The agent decides what to say and which tool to call. Everything below that line should be ordinary deterministic code that does not depend on the model:

  • the fold functions, which are pure functions of the previous state and one event;
  • the decision whether a snapshot may be used;
  • the guard in the refund tool, which re-checks pending refunds from the authoritative source before issuing anything.

The last item matters because the projection is context, not authority. Even a correct projection can be a few events stale by the time the model acts on it, so the tool that performs the effect checks again.

Record the projection version with every snapshot

The fix is to store, next to each snapshot, the information needed to decide whether it may be used:

def take_snapshot(events, version, upto):
    state, _ = replay(events, version, upto=upto)
    return {'projection_version': version, 'last_seq': upto,
            'state': state, 'state_hash': state_hash(state)}

def load_checked(events, snap, version):
    if snap and snap['projection_version'] == version \
            and state_hash(snap['state']) == snap['state_hash']:
        state, read = replay(events, version, start=snap)
        return state, read, 'snapshot used'
    state, read = replay(events, version)
    return state, read, 'rebuilt'

projection_version is a number you bump whenever the fold changes in a way that alters any field. last_seq is the stream position the state includes. The hash catches a snapshot that was edited or truncated in storage. When the version does not match, the loader falls back to a full replay; it never mixes an old state with new code.

Axon Framework ships the same idea. Its snapshotting reference describes a RevisionSnapshotFilter driven by an @Revision annotation on the aggregate, "filtering non-matching snapshots from the Repository's loading process", so that "with every new production deployment of your application that adjusts the Aggregate state, you would only have to adjust the revision value in the annotation". If your framework has a revision or snapshot filter, use it; if you wrote your own snapshot table, add the column.

Migrating an existing system

  1. Add projection_version and last_seq columns to the snapshot store. Backfill existing rows with the version that is running today.
  2. Make the loader reject snapshots whose version differs from the code's version, and log each rejection with the case id. Release this before any fold change.
  3. Release the new fold with a bumped version. The first read of each case rebuilds from the stream and writes a fresh snapshot.
  4. If rebuilding on first read is too slow for busy cases, run a background job that rebuilds snapshots for active cases before traffic moves to the new version, and let the loader use either version during the overlap only if both produce the same state for that case.
  5. Delete snapshots of retired versions once nothing reads them.

Test that a snapshot never changes the answer

The property to test is replay equivalence: for one projection version, loading a snapshot at any position and folding the tail must equal a full replay. The companion test takes a snapshot every 100 events of the synthetic case and compares; for version 2 there are no differences.

def equivalence_cuts(events, version, every=100):
    full, _ = replay(events, version)
    return [c for c in range(every, len(events), every)
            if replay(events, version, start=take_snapshot(events, version, c))[0] != full]

Run this in CI for every projection, and run a second test that deliberately loads a snapshot from the previous version and asserts it is rejected. That second test is the one that would have caught the release above.

Tradeoffs and failure modes

  • Rebuild cost after a release. Bumping the version invalidates every snapshot at once. Rebuilding lazily spreads the cost but makes first reads slow; rebuilding eagerly needs a job and capacity.
  • Forgetting to bump. The version is a manual signal. A code review checklist item for projection changes, or a hash of the fold function's source used as the version, reduces the risk; the equivalence test across versions catches the rest.
  • Upcasting is a different problem. Changing the shape of stored events needs upcasters on read. Changing the fold over unchanged events needs snapshot invalidation. A release can need both.
  • Hidden inputs. A fold that reads the clock, a configuration flag or another service is no longer a function of the stream, and no snapshot check can save it. Keep folds pure.

When snapshots are unnecessary

Most help-desk cases have a few dozen events, and folding them takes microseconds. Snapshots earn their complexity only when measured load time matters: long-lived aggregates, high read rates, or cold reads from slow storage. If a full replay of your longest case is fast enough, skip snapshots and the versioning problem disappears with them. The same holds for the agent: it gains nothing from a snapshot except speed, so do not add one before you measure that you need it.

Verify it yourself

The companion example builds the synthetic CASE-4127 stream, writes a version 1 snapshot at event 900, reads the case at event 930 through each load path in the table and prints the result; its tests assert every row, the eight misleading snapshot positions, and that a tampered snapshot is rejected by the hash. To check your own system, pick the longest real case stream, load it through your snapshot path and through a full replay, and compare the two states field by field after every projection release.

Primary references and authorship

Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/case_view_snapshots. Views are my own and do not represent any employer, past or present.