Reputation: 22926
I have an Azure Cosmos DB with a UserData collection which contains multiple documents of users.
The documents are edited via an azure function which grabs the document, parses the json to a class, edits the class as needed, and sets it back as the user document.
So what if while it's doing that another azure function is called grabbing the document from Azure Cosmos DB and doing other changes before the first function is done? Even if it's changing completely separate fields in the document the other fields remain the same and Azure has no obvious way of knowing what fields to overwrite and which to keep.
The only way this could behandled is if the request for the document waits until whatever function which requested it first has finished requesting it but again I don't know how Azure can figure that out.
Upvotes: 2
Views: 1664
Reputation: 136196
By default Cosmos DB will not prevent this behavior but you can control that by implementing optimistic concurrency using etag
.
Essentially what you will do is whenever you send a document update request, you send the document's etag along with the request. If the etag matches with the etag value of the document on the server, update request will succeed otherwise it will fail (should be with 419 status code, however the documentation doesn't mention that). In case of failure, you could fetch the latest document (along with its etag), update it and send the updated document again.
From Replace a Document
REST API documentation (see Request Headers section):
If-Match
String Used to make operation conditional for optimistic concurrency. i.e. the document is updated only if the specified etag matches the current version in the database. The value should be set to the etag value of the resource.
Upvotes: 5