Microservices make it easy to expand a software system with new components. A frequent problem, however, is the data managed by the microservices – perhaps after a year in operation, a new request suddenly requires information that should have been collected from the beginning. Or there is a lack of historical data that the software has long since discarded. Event sourcing can help in such cases.
The core principle of event sourcing is simple: software not only saves the current status of its area of application, but also every event that has ever occurred and has led to a change in this state.
The principle behind it is not particularly new, but fundamentally known for thousands of years. Because even an account book kept by an accountant using pen and paper is no different: from the moment an account is opened, each booking (i.e. each event) is recorded individually. All relevant technical information is stored within the booking, such as the change in the inventory and – if you want it more precisely – the debit and credit side of the booking as well as associated metadata such as the date and a descriptive text.
Now ask the accountant about the current “state” of the account, it can be reconstructed at any time from the totality of all postings: Only the amounts of all individual transactions have to be offset. The exciting thing about it: With such a rebuild, not only the current status of the account can be reconstructed based on the events, but the status at any point in time. In order to determine the account balance at a certain – but arbitrary – point in time, only the events up to this point in time have to be taken into account during the rebuild and all subsequent events are neglected – and the point-in-time recovery is successful.
If at some point there are a lot of postings in the account book, the accountant may get tired of having to keep adding up everything for a current balance. That is why he uses a trick: at regular intervals – for example at the end of every day, every week or every month – it determines the current balance (i.e. the status of the account) and records it in the ledger. If someone asks for a current account balance in between, he only needs to add postings that have been made since then. In this way he creates a snapshot that he can easily build on at a later point in time.