Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should events be stored in order, and how, when using CQRS/event sourcing

Recently I've followed a CQRS workshop which made me wonder how events are stored when using event sourcing.

I think that after every single event the entire application should be in a valid state (otherwise the replay functionality is useless). This means that event should be stored in exactly the order they happened. I also believe that the order of events for all aggregates is important. For example, a user could make a product and an order (product and order both being separate aggregates, order references product through an ID). This means that the 'create product event' should be stored before the 'add product to event'. Otherwise replaying would could lead to an invalid state where the order, referencing the product, exists before the product exists.

How is this situation handled? Should you always send events to the database using a synchronous methods, for example by locking the database? Is this solution scalable? Or should you store events for each aggregate in a different table? But how do you ensure ordering then? Another option would be to store the time for each event, and sort by that. Is the precision of timers on a PC high enough to be able to do that?

like image 666
Roy T. Avatar asked Jul 12 '15 17:07

Roy T.


1 Answers

I know this is an old thread, but you're absolutely right to question this. The persistence of the events in an event store is irrelevant to your question. Timestamps are an invalid solution, and what the users can logically do is irrelevant to your question.

Your question, correct me if I'm wrong, is that once an event store publishes events via something scalable (for example message bus) - how do you guarantee that the denormalizers receive the events in the correct order. Message buses typically do not guarantee ordering of events.

The answer is you can't, so one option I would suggest is to provide version number with the event, and only update a projected model if the version number of the last known state matches that in the event. If it doesn't, configure the event to retry while you wait for the next event in line.

like image 165
Oriental Avatar answered Nov 10 '22 00:11

Oriental