Lesson 17 / 25
Snapshots, Versioning and Replays
Keep event-sourced systems fast and evolvable over years.
Living with old events
Long-lived aggregates may accumulate thousands of events, making every load slow. A snapshot stores the aggregate's state at a version (say every 100 events); loading reads the latest snapshot and only the events after it. Snapshots are a cache: you can delete and rebuild them. Events written years ago must still be readable, so plan event versioning: add fields compatibly, or use upcasting, where old event versions are converted to the current shape as they are read, so domain code only knows the latest version. Never change the meaning of an existing event type. Replays rebuild projections or create new ones; design projections to run against the full history at high speed, track their position (a checkpoint), and run side-effect-free during replays so you do not resend old emails.
Loading with a snapshot and an upcaster
Old v1 events lack currency; the upcaster fills it in before the domain sees them.
def upcast(event):
if event["type"] == "MoneyDeposited" and event.get("schema", 1) == 1:
return {**event, "currency": "INR", "schema": 2}
return event
def load(store, account_id):
stream = f"account-{account_id}"
snap = store.latest_snapshot(stream) # e.g. {"state": {...}, "version": 4200}
acct = Account.from_snapshot(snap) if snap else Account(account_id)
for e in store.read_stream(stream, from_version=acct.version + 1):
acct.apply(upcast(e))
if acct.version - (snap["version"] if snap else 0) > 100:
store.save_snapshot(stream, acct.to_snapshot(), acct.version)
return acctA bank passbook
The passbook lists every transaction, but each page carries a balance brought forward. You read from the last balance forward instead of adding up every entry since the account opened.
Quick check: What is the role of a snapshot in event sourcing?
- It replaces the event stream permanently
- It caches state at a version so loading replays fewer events
- It deletes old events
- It publishes events to the broker
Answer
It caches state at a version so loading replays fewer events — Snapshots are a performance optimisation; the events remain the source of truth.