Event Sourcing
Event Sourcing is an architectural pattern where the state of an application is determined by a sequence of events, rather than just the current state. Instead of storing "User A has balance $100", you store "User A created", "User A deposited $50", "User A deposited $50".
1. The Core Concept
In traditional databases, when you update a record, the old data is overwritten and lost. In Event Sourcing, you never delete or overwrite data. You only append new events to a log (Event Store).
- Current State: Derived by replaying all events from the beginning.
- Event: An immutable record of something that happened in the past (e.g.,
ItemAddedToCart,OrderShipped).
2. How it Works
- Capture: Every change to the application state is captured as an event object.
- Store: These events are stored in the order they were applied.
- Replay: To get the current state of an entity (e.g., a Bank Account), the system loads all events for that ID and applies them sequentially.
Example: Bank Account
Events Log:
AccountOpened { balance: 0 }MoneyDeposited { amount: 100 }MoneyWithdrawn { amount: 20 }
Derived State: Balance = $80.
3. Snapshots
Replaying thousands of events every time you need the current state is slow. To optimize this, systems often create Snapshots.
A snapshot saves the current state at a specific point in time (e.g., after event #1000). To get the current state, you load the latest snapshot and replay only the events that happened after it.
4. Benefits
- Audit Trail: You have a 100% accurate history of everything that happened. You can answer "How did we get here?".
- Temporal Queries: You can determine the state of the application at any point in time (Time Travel).
- Debugging: You can copy the production event log to a dev machine and replay it to reproduce a bug exactly.
5. Challenges
- Complexity: Requires a shift in mindset and more infrastructure.
- Event Schema Evolution: Handling changes to the structure of events over time (Versioning) is difficult.
- External Systems: You can't "replay" sending an email or charging a credit card. You need to handle side effects carefully.
programming/cqrs programming/event-driven-architecture programming/domain-driven-design