Popular Posts

Event Sourcing Pattern

An architectural pattern that models the state changes made by applications as an immutable sequence or “log” of events. Instead of modifying the state of the application in-place.



Generally with crud applications we hold only current state not how we got there. That might be issue for some applications. For example lets think an online banking application. If only thing they can see is current balance not how they got to that balance, no withdrawal, deposit or fee history.

For Inventory Service, if there is 100 items in stock at the morning and in the evening there is 50 items left. Is it because 50 items sold or 100 items sold and 50 returned? 

Just having current state is not enough.

Problem: In certain situations we need to know the current state and every previous state that led to it. 

Instead of holding current state we have events that describes an entity.

As i explained immutability in previous blog, this events that are immutable, only new events can be append.

So we are not holding current balance, we are holding steps that led to that balance like deposits, credit and fees. So when user wanted to see balance we replay those events to get most up to date balance(Of course, every time user wanted to see just balance, calculating is not efficient, there are strategies for this. Like Snapshots and CQRS. for example taking snapshots. We can calculate current balance by snapshot that taken in certain time + replaying most current event until that snapshot). By storing every transaction we can detect suspicious transactions, fraudulent activities. 

 

Benefits

-Visualization

-Auditing

-Corrections

-High Write Performance


So where do we store Events?

-Database - Separate record for each event

-Message Broker - Separate Message for each event

Instead of storing the events in a private database that belongs to a service we can publish for anyone to consume.


Event Sourcing + CQRS is very popular combination. I will go in deep to that topics in Microservices and Event-Driven Architecture post.

Resources:

https://martinfowler.com/eaaDev/EventSourcing.html

https://martinfowler.com/eaaDev/EventNarrative.html

https://microservices.io/patterns/data/event-sourcing.html

https://medium.com/design-microservices-architecture-with-patterns/event-sourcing-pattern-in-microservices-architectures-e72bf0fc9274