Event Sourcing & CQRS · CQRS and Projections
Snapshots
Speed up loading long-lived aggregates.
Aggregates with thousands of events load slowly. A snapshot stores the aggregate's state at a stream version; loading reads the latest snapshot and only the events after it. Snapshots are an optimization, not a source of truth — they can be deleted and rebuilt. Version snapshot schemas, take them asynchronously every N events, and prefer redesigning overly long-lived streams (e.g., close and reopen accounting periods) when possible.
Snapshots trade-off
| Criterion | Without snapshots | With snapshots |
|---|---|---|
| Load cost | O(events) | O(events since snapshot) |
| Storage | Events only | Events + snapshots |
| Correctness risk | None | Stale/incompatible snapshot schemas |
| When needed | Short streams | Long-lived aggregates |
Python
async def load_account(store, snapshots, account_id: str):
snap = await snapshots.latest(f"account-{account_id}") # {"version": 9000, "state": {...}, "schema": 2}
state = Account(**snap["state"]) if snap and snap["schema"] == 2 else Account(id=account_id)
start = snap["version"] + 1 if snap and snap["schema"] == 2 else 0
events, version = await store.read_stream(f"account-{account_id}", from_version=start)
for e in events:
state = apply(state, e)
if len(events) > 500:
await snapshots.save_async(f"account-{account_id}", version, state, schema=2)
return state, version
Common pitfalls
- Treating snapshots as the source of truth.
- Snapshot schema changes without versioning.
- Snapshotting synchronously on every write.
Key points
- Optimization only
- Version snapshot schemas
- Prefer shorter streams by design
Further reading: Azure Architecture: Event Sourcing
Practice questions
Can snapshots be deleted safely?
Answer
Yes — they're derived data; the event stream remains the source of truth and snapshots can be rebuilt.
What design change can avoid the need for snapshots?
Answer
Modeling shorter-lived streams, e.g., closing a ledger period and starting a new stream with an opening balance event.
Open in the app to mark lessons complete, take notes and track your progress.