Search code examples
nservicebussaga

How to prevent a NServiceBus saga from being started multiple times?


I want to create a saga which is started by message "Event1" but which will ignore receipt of "duplicate" start messages with the same applicative id (which may result from two or more users hitting a UI button within a short period of time). The documentation seems to suggest that this approach would work:

  • Saga declares IAmStartedByMessages<Event1>
  • Saga configures itself with ConfigureMapping<Event1>(s => s.SomeID, m => m.SomeID);
  • Handle(Event1 evt) sets a boolean flag when it processes the first message, and falls out of the handler if the flag has already been set.

Will this work? Will I have a race condition if the subscribers are multithreaded? If so, how can I achieve the desired behavior?

Thanks!


Solution

  • The race condition happens when two Event1 messages are processed concurrently. The way to prevent two saga instances from being created is by setting a unique constraint on the SomeID column.