Java Holiday Calendar (Day 9): Event Sourcing
Event sourcing opens up a new way of looking at your database apps. Turn your database into a record of transactions that you can look back to and restart from.
Join the DZone community and get the full member experience.Join For Free
Today's tip is about event sourcing, which is a relatively new way of designing database applications. Instead of seeing the database as a representation of the most current state, we would see it as a system of record for all transactions that ever took place in our applications.
So, instead of saying "find person 3 and replace that person's salary with whatever it is right now plus $100," we would say "person 3's salary increased by $100." Note the subtle but important distinction.
If we use the first scheme, then we would know the current salary but not what it was before, by how much it increased and when it increased. The latter scheme, however, allows us to replay all transactions so that we can reproduce all states the application ever had. That's great for when we are hunting bugs.
Another important property of event sourcing is that we do not need the (expensive) absolute consistency of the underlying database. Instead, we only need to make sure that the order of the events remains consistent over time.
How do we keep track of the most recent value in an event sourcing system when it is changing all the time? Well, we could implement something called a Materialized View that holds the most current state. So, if we have an event table called employee_event,s then we could have a Java class EmployeeView that will continuously replay the events in the employees_event table and distil the fold of all events so that we would actually know what salary person 3 has at the moment.
When the number of events increases, it would be more and more expensive to fast forward all the events — for example, when the application restarts. To combat this drawback, the EmployeeView could create periodic snapshots from which it can be restarted.
Event sourcing is particularly interesting for applications with a microservice architecture.
Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.
Opinions expressed by DZone contributors are their own.