What is Event Sourcing: Definition, Example, and Use Cases
events. Instead of saving only the current state, the system records every state change, allowing you to reconstruct past states and audit history easily.How It Works
Imagine you keep a diary where you write down every action you take during the day instead of just noting how you feel at the end. Event sourcing works similarly by saving every change (event) that happens in the system, like "OrderPlaced" or "PaymentReceived." These events are stored in order, creating a timeline of what happened.
When you want to know the current state, you replay all these events from the start, like reading your diary from day one to today. This way, the system can rebuild its state anytime and also see exactly how it got there. This is very useful for tracking, debugging, and recovering from errors.
Example
class BankAccount { constructor() { this.events = []; } deposit(amount) { this.events.push({ type: 'Deposit', amount }); } withdraw(amount) { this.events.push({ type: 'Withdraw', amount }); } getBalance() { return this.events.reduce((balance, event) => { if (event.type === 'Deposit') return balance + event.amount; if (event.type === 'Withdraw') return balance - event.amount; return balance; }, 0); } } const account = new BankAccount(); account.deposit(100); account.withdraw(30); account.deposit(50); console.log('Current Balance:', account.getBalance());
When to Use
Event sourcing is great when you need a full history of changes, such as in financial systems, order management, or auditing applications. It helps with debugging because you can see exactly what happened and when.
It is also useful in microservices where different parts of the system react to events asynchronously, improving scalability and flexibility. However, it adds complexity and requires careful design, so it is best used when auditability and traceability are important.
Key Points
- Stores all changes as a sequence of events, not just current state.
- Allows rebuilding state by replaying events.
- Improves auditability and debugging.
- Supports asynchronous communication in microservices.
- Introduces complexity and requires event storage management.