Minborg

Minborg
Minborg

Friday, December 9, 2016

Day 9, Java Holiday Calendar 2016, Event Sourcing

9. Event Sourcing



Today's tips 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 persons salary with whatever it is right now plus $100" we would say "person 3's salary increased by $100". Note the subtile 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 re-produce all states the application ever had. Great 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 remain 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_events then we could have a Java class EmployeeView that continuously will replay the events in the employees_event table and distiller 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 micro service architecture.

Read more about Event Sourcing on Emil Forslund's blog here and on Event Sourcing and Micro Services on eventuate.io here.

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.




No comments:

Post a Comment

Note: Only a member of this blog may post a comment.