Microservices Design Pattern - Event Sourcing Pattern
The Event Sourcing pattern is a software architecture pattern where changes to an application's state are stored as a sequence of events. Instead of storing the current state of data directly (like in traditional CRUD systems), each state change is recorded as an immutable event, and the current state is reconstructed by replaying these events. This approach offers many advantages, particularly for complex applications that need to keep detailed histories of state changes.
In event sourcing, you’d store the events that happened to change the state of the order. You could materialize the current state of the order by replaying those events.
A Cheatsheet on Event Sourcing Pattern :
Here's a breakdown of how the Event Sourcing pattern works, its benefits, and typical use cases.
Key Concepts of Event Sourcing
Events as Immutable Facts:
Every change in the system is recorded as an event. For example, if you're working on an e-commerce application, actions like "OrderCreated," "OrderCharged," and "OrderReserved" would all be events.
These events are stored in an event store in the order they occur and are treated as immutable historical facts that cannot be altered or deleted.
Event Store:
The event store is a database or a log where events are persistently stored. It can be as simple as an append-only log or as complex as a distributed event store designed for high scalability.
Events can be appended only; they cannot be modified or deleted, ensuring a clear audit trail.
Replaying Events to Derive State:
The current state of an entity can be derived by replaying all relevant events in the event store. By replaying events, you can reconstitute the state of an object or an entire application at any point in time.
Event-Driven Architecture:
Event Sourcing is often paired with event-driven architectures, where events trigger actions or workflows across different parts of the application, promoting decoupling and scalability.
Snapshots:
Replaying events can become time-consuming as the number of events grows. To mitigate this, snapshots (periodic summaries of state) are created to save the current state of an entity at specific intervals. When reconstructing state, only events after the most recent snapshot need to be replayed.
Example of Event Sourcing
Let's consider an example of a bank account application using Event Sourcing:
Events:
OrderCreated
OrderCharged
OrderReserved
OrderPlaced
Event Store:
Each of these events is stored in an event store with a timestamp and other metadata. Over time, the store could look like this:





