Exercise — Event Sourcing: rebuild an account balance from an event stream, with snapshots.
Topic: microservices, Data Management. Level: Hard.
Answer
Replaying millions of events per read is expensive, so periodically persist a **snapshot** of state at a known version, then replay only events after that version. On load: fetch latest snapshot, apply subsequent events. This bounds replay cost while keeping the event log authoritative.
```java
Account load(String id) {
Snapshot snap = snapshots.latest(id); // e.g. version 1000
Account acc = snap != null ? Account.from(snap) : new Account();
long fromVersion = snap != null ? snap.version() : 0;
for (Event e : store.eventsAfter(id, fromVersion)) // replay only the tail
acc.apply(e);
return acc;
}
void maybeSnapshot(String id, Account acc, long version) {
if (version % 1000 == 0) snapshots.save(id, acc.toSnapshot(version));
}
```