Event Sourcing
Overview
Instead of storing just the current state of data in a domain, Event Sourcing stores every change to that state as an append-only sequence of immutable events. The current state is derived by replaying these events from the beginning.
Key Concepts
The Event Store
Events are facts about things that have already happened (e.g., OrderCreated, ItemAdded, ShippingAddressUpdated). These are stored in an Event Store, which functions as an append-only database (like Kafka or EventStoreDB). Because events are immutable, there are no UPDATE or DELETE operations, only INSERTs, eliminating database locking contention.
Projections and CQRS
Reading an entire history just to find a current balance is slow. Therefore, Event Sourcing is almost always paired with CQRS. The system listens to the stream of events and builds "Projections"-denormalized views of the current state stored in a read-optimized database.
Snapshots
To optimize the replay process for entities with thousands of events, the system periodically takes a "snapshot" of the current state (e.g., saving the balance every 100 transactions). To find the current state, it only has to load the latest snapshot and replay the few events that occurred after it.
Trade-offs
Event sourcing provides a flawless, unalterable audit log for free (ideal for financial or legal systems). It allows you to implement "time travel" (querying what the state was last Tuesday) and rebuild read models from scratch if requirements change. However, it is extremely complex to implement, makes simple queries difficult without CQRS, and forces developers to deal with schema evolution over time (how do you replay a 3-year-old event whose structure has changed?).
Interview Tips
- Suggest Event Sourcing when the prompt mentions strict auditing requirements, financial ledgers, or e-commerce shopping carts where historical intent matters.
- Explicitly mention pairing it with CQRS to solve the read-performance problem.
- Mention "Snapshots" to show you understand how to optimize the performance of replaying long event streams.
Summary
- Event Sourcing stores data as a sequence of immutable events rather than overwriting current state.
- Current state is derived by replaying the event log.
- It provides a perfect audit trail and the ability to query historical states ('time travel').
- It avoids UPDATE/DELETE locking contention in the database.
- It requires CQRS to create queryable read models, adding significant architectural complexity.