Rebuilding State from Events
What You'll Learn
You'll learn how to reconstruct the current state of your system by replaying stored events, giving you a complete audit trail and the ability to "time travel" through your application's history.
The Core Idea
When using Event Sourcing, you don't store the current state directly in a traditional database. Instead, you store every event that changed the state. To know what the current state is, you replay all those events from the beginning (or from a checkpoint) through your domain logic.
Think of it like a bank statement: instead of just showing your current balance, it lists every deposit and withdrawal. If you want to know your balance at any point, you start from zero and apply each transaction in order.
How Replay Works
- Start with an empty state (or initial state)
- Fetch events from the event store in the order they occurred
- Apply each event to the state using your aggregates or projections
- Result: the current state is rebuilt
This process is called rehydration or reconstitution.
Why This Matters
- Audit trail: You can see exactly how you arrived at the current state
- Time travel: Rebuild state as it was at any point in history
- Bug fixes: If your logic was wrong, you can fix it and replay events with the corrected logic
- New views: Create new projections of old data without migrating databases
The Trade-off
Replaying thousands of events every time can be slow. That's why systems often use snapshots—saved states at certain points—so you only replay events after the snapshot.
Key Takeaway: Rebuilding state from events means treating your event stream as the source of truth, allowing you to reconstruct any state by sequentially applying stored events through your domain logic.