Systems using Event Sourcing store their persistent state as a sequence of events instead of updating a single model. A particular state can be recreated by replaying all events. It's basically a persistent transaction log file for your application.
Why should I care?
You're able to restore the system state to any point in time. More important you have all information available to debug the reason for a certain state. Depending on your business domain, this might be a business- or even legal requirement.
On the source code level, I see a hugh advantage in the maintainability and readability of the code. Every chance to the system's state goes through a command which result is a set of events. This makes it easy for other developers to understand your system.
On the other hand, using event sourcing comes with a cost. Your event store will grow and its additional data that needs to be maintained. For performance reasons you have to maintain additional snapshots. If you avoid snaphots your application might need some extra time recreating a particular state that you canot affort. Also you might need to maintain a separate read model that needs to be in sync.
How can I build such a system?
In an event sourced system all intents are expressed as a command. Commands are usually start with an verb (e.g. ShipOrderCommand). A command should clearly express a single intent. Generic commands like "Update" or "Insert" are not useful.
Each command has an CommandHandler thats first resposibility is to check the preconditions if this command can be performed by the caller depending on the current state and may reject it's execution. A CommandHandler never modifies any data directly, but it returns a sequence of events that are the result of the command. For example the ShipOrderCommand may return an event OrderShippedEvent.
The events provided by the CommandHandlers are then handled by an EventBus that stores the events in the EventStore. The EventStore also knows about EventHandlers which register for a certain event type and notifies them about the new event. Usual jobs of EventHandlers are updating the domain model.
The EventStore holds all events and provides methods to get all events for a particular thing. The EventStore is the transaction log of your application from which you can rebuild the state of the system.
The following sequence diagram shows this interaction between those components:
This is just a brief overview of the most important components of an event sourced system. I will write some subsequent posts over time where I want to explore the parts in more detail. It's a journey.
Marco Rico Gomez is a passionate software developer located in Germany who likes to share his thoughts and experiences about software development and technologies with others.
blog comments powered by Disqus