Event sourcing is a great way to atomically update state and publish events. The traditional way to persist an entity is to save its current state. Event sourcing uses a radically different, event-centric approach to persistence. A business object is persisted by storing a sequence of state changing events. Whenever an object’s state changes, a new event is appended to the sequence of events. Since that is one operation it is inherently atomic. A entity’s current state is reconstructed by replaying its events.
To see how event sourcing works, consider the Order entity.
Traditionally, each order maps to a row in an
ORDER table along with rows in another table like the
But when using event sourcing, the
Order Service stores an
Order by persisting its state changing events: Created, Approved, Shipped, Cancelled.
Each event would contain sufficient data to reconstruct the Order’s state.
Events are persisted in an event store. Not only does the event store act as a database of events, it also behaves like a message broker. It provides an API that enables services to subscribe to events. Each event that is persisted in the event store is delivered by the event store to all interested subscribers. The event store is the backbone of an event-driven microservices architecture.
In this architecture, requests to update an entity (either an external HTTP request or an event published by another service) are handled by retrieving the entity’s events from the event store, reconstructing the current state of the entity, updating the entity, and saving the new events.
Here is how the
Order Service handles a request to update an
As you can see, event sourcing addresses a challenge of implementing an event-driven architecture. Additional significant benefits of persisting business events include the following:
100% accurate audit logging - Auditing functionality is often added as an afterthought, resulting in an inherent risk of incompleteness. With event sourcing, each state change corresponds to one or more events, providing 100% accurate audit logging.
Easy temporal queries - Because event sourcing maintains the complete history of each business object, implementing temporal queries and reconstructing the historical state of an entity is straightforward.
The benefits of event sourcing are clear. Let’s see how the Eventuate Local puts this unique and powerful approach to work.