Home > Enterprise >  All transaction should fail if at least one fails using Bulk creation for cosmos db
All transaction should fail if at least one fails using Bulk creation for cosmos db

Time:08-04

I am inserting a list of items using bulk for cosmos db. When one transaction fails, the others are still being created successfully. What I would like to happen is when one transaction fails all transaction should fail. So nothing should be created.

Is there a way to ensure this happens?

My code looks something like this:

List<Task> concurrentTasks = new List<Task>();
foreach(Item itemToInsert in ReadYourData())
{
    concurrentTasks.Add(container.CreateItemAsync(itemToInsert, new PartitionKey(itemToInsert.MyPk)));
}

await Task.WhenAll(concurrentTasks);

CodePudding user response:

Instead of doing a bulk operation, what you would need to do is perform a transactional batch operation. That will ensure that the whole batch will fail if one item in the batch fails.

You can learn more about it here: https://docs.microsoft.com/en-us/azure/cosmos-db/sql/transactional-batch?tabs=dotnet.

  • Related