Search code examples
event-sourcingazure-cosmosdbazure-servicebus-queuesdatabase-concurrencyazure-servicebus-topics

DocumentDB unique concurrent insert?


I have a horizontally event-source driven application that runs using an Azure Service Bus Topic and a Service Bus Queue. Some events for building up my domain model's state are received through the topic by all my servers, while the ones on the queue (the ones received a lot more often and not mutating domain model state) are distributed among the servers in order to distribute the load.

Now, every time one of my servers receives an event through the queue or topic, it stores it in a DocumentDB which it uses as event store.

Now here's the problem. How can I be sure that the same document is not inserted twice? Let's say 3 servers receive the same event. They all try to store it. How can I make it fail for 2 of the servers in the case they decide to do it all at the same time? Is there any form of unique constraint I can set in DocumentDB or some kind of transaction scope to prevent the document from being inserted twice?


Solution

  • The id property for each document has a uniqueness constraint. You can use this constraint to ensure that duplicate documents are not written to a collection.