Module 5 - Architecture Patterns
Event Sourcing
Store every change as an immutable event, not just the current state.
1The Bank Ledger Analogy
Simple Analogy
Your bank doesn't just store your current balance. It records every transaction: deposit $100, withdraw $50, transfer $25. Your balance is derived by replaying all transactions. That's event sourcing-store the events, derive the state.
Event Sourcing persists the state of an entity as a sequence of events. Instead of storing current state, you store what happened. Current state is computed by replaying events.
2Traditional vs Event Sourcing
Traditional (State)
- • Store current state only
- • UPDATE overwrites old data
- • History is lost
- • Simple to query current state
Event Sourcing
- • Store all events
- • Events are immutable (append-only)
- • Complete audit trail
- • Replay to get any point in time
3Benefits
Complete Audit Trail
Every change is recorded. Perfect for compliance.
Time Travel
Reconstruct state at any point in history.
Debugging
Replay events to reproduce bugs exactly.
Flexibility
Build new projections from existing events.
4Challenges
Event Schema Evolution
Old events with outdated schemas need handling (upcasting).
Storage Growth
Events accumulate forever. Use snapshots to speed up replay.
Eventual Consistency
Projections lag behind event writes.
Complexity
Harder to query than traditional state storage.
5Key Takeaways
1Event Sourcing stores events, not current state
2Events are immutable-append-only log
3Complete audit trail and time travel
4Often paired with CQRS for read optimization
5Use snapshots to avoid replaying millions of events
?Quiz
1. In event sourcing, how do you get current user balance?
2. Main benefit for financial systems?