You are developing a C# backend service for a smart home energy monitoring application that stores device configurations in Azure Cosmos DB using the NoSQL API. You need to implement Optimistic Concurrency Control (OCC) using the Azure Cosmos DB .NET SDK v3 to ensure that updates to a device configuration are not overwritten by concurrent processes.
Which sequence of actions should you perform to complete the update?
- 1Initialize a CosmosClient instance, and call GetContainer on the target Database object to retrieve a Container reference.
- 2Call ReadItemAsync<DeviceConfig> with the configuration ID and a PartitionKey instance to retrieve the current item.
- 3Extract the ETag value from the Headers property of the returned ItemResponse<DeviceConfig> object.
- 4Instantiate a new ItemRequestOptions object and set its IfMatchEtag property to the extracted ETag value.
- 5Call ReplaceItemAsync<DeviceConfig> with the modified object, its ID, its PartitionKey, and the ItemRequestOptions object.
Answer
Initialize the CosmosClient and obtain a Container reference, retrieve the item using ReadItemAsync along with its partition key, retrieve the ETag from the response headers, create an ItemRequestOptions instance with the IfMatchEtag property set to the retrieved ETag, and call ReplaceItemAsync with the updated document, its ID, PartitionKey, and the request options.
To implement Optimistic Concurrency Control (OCC) in Azure Cosmos DB using the C# .NET SDK v3, you must follow a read-before-write pattern. First, retrieve a reference to the container via `CosmosClient` and `Database`. Next, fetch the target document using `ReadItemAsync<T>` specifying the item ID and its `PartitionKey`. You then extract the `ETag` metadata property from the response headers. Next, create a new `ItemRequestOptions` instance and assign the extracted `ETag` string to its `IfMatchEtag` property. Finally, invoke `ReplaceItemAsync<T>` passing the updated object, its ID, its `PartitionKey`, and the custom `ItemRequestOptions`. If another process has modified the document in the meantime, the ETag on the server will not match, and the SDK will throw a `CosmosException` with a `412 Precondition Failed` status code, preventing the overwrite.
Step-by-Step Solution
Key Concept
Implementing Optimistic Concurrency Control (OCC) using the Cosmos DB .NET SDK v3 with ETag validation.
Estimated Time:2m 30s