Microservices.io is brought to you by Chris Richardson. Experienced software architect, author of POJOs in Action and the creator of the original CloudFoundry.com. His latest startup is eventuate.io, a microservices application platform.
He offers a comprehensive set of resources for learning about microservices including articles, an O'Reilly training video, consulting, workshops and hands on training classes.Learn More
Join the microservices google group
You have applied the Event-driven architecture pattern. In order to be reliable, services must atomically publish events whenever their state changes. It is not viable to use a distributed transaction that spans the database and the message broker. How to reliably/atomically publish events whenever state changes?
A good solution to this problem is to use event sourcing. Event sourcing persists the state of a business entity such an Order or a Customer as a sequence of state-changing events. Whenever the state of a business entity changes, a new event is appended to the list of events. Since saving an event is a single operation, it is inherently atomic. The application reconstructs an entity’s current state by replaying the events.
Applications persist events in an event store, which is a database of events. The store has an API for adding and retrieving an entity’s events. The event store also behaves like a message broker. It provides an API that enables services to subscribe to events. When a service saves an event in the event store, it is delivered to all interested subscribers.
The following diagram shows how the e-commerce system could use event sourcing to persist orders.
Instead of simply storing the current state of each order as a row in an
ORDERS table, the application persists each Order as a sequence of events.
CustomerService can subscribe to the order events and update its own state.
Event sourcing has several benefits:
Event sourcing also has several drawbacks: