Practical Microservices: What about out-of-order messages (page 55)

Within chapter 4 an aggregator is implemented. The aggregator handler is written so that it is idempotent (i.e. it doesn’t matter if the handler is called once or N times with same parameters).

The way this is achieved is that view data tracks the global position of an event. In another words if event 5 is delivered multiple times the view data is updated only once.

However, the code cannot survive out-of-order delivery of events. In another words if message store delivers first event 5 followed by event 3 the videosWatched parameter should be updated twice (i.e. once for event 3 and once for event 5). In this case, however, the aggregator will increment the counter only once resulting in wrong state.

Perhaps message store can guarantee in-order delivery of events, but I suppose this would be a good thing to mention.

Otherwise there are probably multiple ways to fix this. One that comes to mind is to track a list of events (global position indices) processed by aggregator in the database and increment the counter if aggregator receives an event it has not yet processed.

1 Like

Hi uhef, yes, messages arriving out of order can be a problem with certain message transports. MessageDB does indeed prevent the case you describe in that once a message is written, unless PG’s sorting functionality fails, it will always return the messages in the order that they were written.

There are, of course, no guarantees as to which message will be written first, but because MessageDB is Just Postgres™ under the hood and uses a query that orders by global_position ASC (message-db/get-category-messages.sql at master · message-db/message-db · GitHub).

Thank you for calling it out, and I agree, that is a good thing to let folks be aware of.