Handling Stale messages

I’d like to understand how stale messages are/can be treated. In case you’re not clear what I mean by stale messages here’s an example:

StatusChangedEvent: Draft–>Submitted : timestamp 1
StatusChangedEvent: Submitted–>Active : timestamp 2
StatusChangedEvent: Active–>Submitted : timestamp 3

The only message we care about is the last one as this is the current state. If the service was down for some reason and then brought back up, its possible that all three messages could be processed at the same time. However, only one will ever succeed at a time due to concurrency checking. However, if msg 3 succeeded first then 1, then 2 the final result will be ‘Active’ which isn’t correct.

So I’m interested in what the recommendation is for handling this scenario. I don’t think TTL is a good option here as we never want that last message to disappear before its had a chance to be processed.

My preferred option would be to store the timestamp on the entity that you are changing and just discard stale messages with a if message.TimeOfChange < entity.LastChangedAt check in your handlers. Would that work?



That’s the approach I was considering but wanted to see if there were any ‘built’ in ways or other options that would be better. I assume this is a common problem for people, we believe its likely to be a common scenario in our environment.

Thanks for the reply!

I’ve seen some generic solutions where each command has a header with the timestamp and “entity id” that would allow a generic solution to discard all messages where the entity had a more recent timestamp but in my experience that mostly leads to complex code to make sure to not load the entity twice, caching issues etc. I guess depending on how common this pattern is in your system you might consider something like it but I would call YAGNI on that until proven otherwise?