Tutorials Microservices & Event-Driven Architecture (EDA) Mastery
Event Sourcing: Capturing every state change
On this page
Deep Dive: Event Sourcing
In a normal database, you store the 'Current State'. In Event Sourcing, you store the 'History of Changes'. The current state is just a result of replaying those changes.
1. Why use it?
- **Infinite Audit:** You know exactly who changed what and when.
- **Time Travel:** You can see what the system looked like at 2 PM last Tuesday.
- **Performance:** Writes are 'Append-Only', which is the fastest possible DB operation.
2. Snapshots
If an account has 10,000 transactions, replaying all of them every time you want to check the balance is slow. We use **Snapshots**. Every 100 events, we save the current state. When loading, we load the last snapshot and then only replay the events that happened after it.
4. Interview Mastery
Q: "What is the biggest challenge of Event Sourcing?"
Architect Answer: "**Versioning**. If you change a field name in an event today, you must still be able to read that event from 3 years ago. You either need to maintain 'Upcasters' (code that migrates old events to the new format on the fly) or keep your event schema extremely stable. Event Sourcing is a 'Marriage to your Data'—you have to be careful what you commit to."