Snapshot
Snapshot de event sourcing
Escrito por Darjus Kazakevic · revisado el
Save the current state now and then, so loading does not replay every event.
With event sourcing, you store every change as an event and rebuild state by replaying them. Loading an aggregate means replaying its whole stream. That takes milliseconds at 200 events and seconds at 200,000, and long-lived streams, like a bank account or a device, get there.
A Snapshot is the aggregate's state saved at a known version. Loading reads the latest snapshot and replays only the events after it. The events stay the source of truth, so a snapshot is only a cache.
En esencia — Save an aggregate's state every N events, then load from the latest snapshot and replay only the newer events, never from event one.
Cuándo recurrir a él
Recurre a él cuando
- Streams with thousands of events, like accounts or devices
- Load time is measurably dominated by event replay
- The same long streams are loaded many times a second
Reconsidéralo cuando
- Streams of a few hundred events that already load fast
- The stream should be split instead, for example one per year
- You are not using event sourcing: the row already is the state
The moving parts
- State at a version
- A snapshot stores the aggregate's state plus the version of the last event it includes. Loading replays only events with a higher version.
- How often
- Take one every N events, often 100 to 1,000, or when load time crosses a limit you measured. Most streams are short and never need one.
- Snapshot schema
- A snapshot stores the state that today's apply() code produced. When that code changes, old snapshots hold the old result. A schema number on each snapshot lets new code ignore old ones.
Applying it well
- A snapshot must be safe to delete
- The events stay the source of truth; the snapshot is a cache. Deleting every one should cost only time. If it loses data, something stopped being rebuildable from the stream.
- Version snapshots with the code that made them
- Store a schema number with each snapshot and ignore any snapshot made by older apply() code. The next load replays from an earlier point and writes a correct one.
- Take snapshots off the write path
- Write snapshots in the background or after the command commits. A failed snapshot must never fail the user's command, because it is only an optimization.
Errores habituales
- Data that exists only in the snapshot, so deleting snapshots loses it.
- New code reading snapshots made by old apply() logic. The symptom: wrong totals after a deploy.
- Writing the snapshot inside the command's transaction, so a snapshot error fails the user.
- Adding snapshots to short streams, which adds code and saves no measurable time.