Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event sourcing pattern: why mustn't I store current state?

I'm learning event sourcing pattern I can not understand one thing at it.

There is the instruction to not store the current state of entity at DB in many tutorials. Developer should build an infrastructure for extracting all events ("event stream") from DB that is related to needed entity, afterwards it applies them to new needed-type object, so finally it's the current state.

Let it be an bank account. To return to my client her current account state I must:

  1. Extract all related events (possibly there are thousands events in DB)
  2. Compute amount of free money at that moment.

However what about performance? I think it's would be better just to store the current state of every account and a new event would create side-effect to it immediately. Am I not right?

like image 818
Ilya Loskutov Avatar asked Jan 20 '17 11:01

Ilya Loskutov


1 Answers

The whole point of event sourcing is to keep the state as series of changes, so having the current state is opposite to ES.

That being said, due to performance requirements sometimes a snapshot is created so that updates are not applied from the beginning, but only from the snapshot forward. Event stores are specialized databases targeted at applications using event sourcing and they can provide the snapshot functionality out of the box.

The other part of equation is that ES is complementary to CQRS - Command Query Responsibility Segregation pattern which separates read and write models (previous link didn't get it quite right, IMO, you might want to look at this one). Then the commands being executed or domain events are used to continuously update the read model which is actually a denormalized representation of the current state. So for commands you will build domain objects from events (ES) and act on them, while for queries you will bypass event store and retrieve data directly from the read model which can be a relational database, document database or something else, which is optimized for your reading scenarios.

If you have mostly-reading application, than the performance of command side which is implemented with ES, might not be that critical.

The benefits of ES are out of scope of this question and you can find quite a lot of info on internet (especially by Greg Young and Udi Dahan). I am personally a bit skeptical about it, and find it to make sense if working with long running business scenarios.

like image 150
Zdeslav Vojkovic Avatar answered Oct 23 '22 14:10

Zdeslav Vojkovic