If you have been reading about CosmosDB for some time now, you might have seen how fast it works. Cosmos DB works really fast and does not disable viewing/editing any document or collection when somebody is working on them. However, this results in the possibility of two actions happening parallel on the same document or collection.
Due to this, it is possible that somebody who started editing the document at a later point makes the changes and the one already working on the document is actually trying to update the old document. This scenario arises because of the “Last write wins” strategy that Cosmos DB follows.
LAST WRITE WINS
This means that whenever the last user made changes to the document or the collection in Cosmos DB, that will be considered as the latest document. So basically, the valid document will be the one which is the latest version of the document.
Now to avoid the scenario of using the outdated document and making sure that the document that you are modifying is the latest version of it, comes in the concept of Optimistic concurrency.
Cosmos DB handles this situation by providing the concept of optimistic concurrency. The response header tag and the document contain a special tag called as an entity tag. This is used along with an AccessCondition tag to ensure that we get an error if we are updating an old version of the document.
Entity Tag or Etag
The resources with the property _etag in Cosmos DB contain an Etag which is a system-defined meta property. It looks something like:
We can provide the etag with our update, insert or delete operations. This can be done by proving an object called AccessCondition as per RequestOptions. When we provide this etag, we need to specify the behavior that should be enforced as a part of the AccessCondition object.
Let us say you have an AccessCondition object.
It contains two properties:
The condition property is where the etag is specified to perform operations. The Type property, however, is the enumerator of type AccessConditionType and has two values:
And if the AccessCondition is not met after the request, CosmosDB rejects the operation and returns failure.