How to Update an Azure Cosmos DB Item Only If It Hasn't Changed with an ETag in C#
When two people read the same Azure Cosmos DB item and both save it, the second save replaces the first, and nobody is told. Send the ETag you read with IfMatchEtag, and Cosmos DB refuses a save made from an old copy with 412 PreconditionFailed, so your app can read the item again and keep both changes. Here's the lost update and its fix in a small C# app, with what each run printed.
Every item in Azure Cosmos DB has a system property _etag, a version that changes with each write. Microsoft's page on optimistic concurrency control: The value of the _etag is automatically generated and updated by the server every time the item is updated. A write can send the ETag it started from, and the server checks it: If the value of the if-match request header is no longer current, the server rejects the operation with an "HTTP 412 Precondition failure" response message. In the .NET SDK, you send it with the IfMatchEtag property of ItemRequestOptions.
Syntax
try
{
ItemResponse<<Type>> <saved> = await <container>.ReplaceItemAsync(<item>, "<id>", new PartitionKey("<value>"),
new ItemRequestOptions { IfMatchEtag = <etag> });
// 200 OK: the stored item still had <etag>, and now holds <item>
}
catch (CosmosException <exception>) when (<exception>.StatusCode == HttpStatusCode.PreconditionFailed)
{
// 412: the item changed after <etag> was read, and nothing was written
}
| Part | What it is |
|---|---|
<Type> | The C# type of the item |
<saved> | The response. Its StatusCode is OK (200), and its Resource is the saved item |
<container> | The Container from CosmosClient.GetContainer |
<item> | The changed item: A JSON serializable object that must contain an id property |
<id> | The Cosmos item id of the existing item. It has to match the id of <item> |
<value> | The item's partition key value, the value of the property that the partition key path names |
<etag> | The ETag of the response that read the item, such as ItemResponse<T>.ETag |
<exception> | The CosmosException the SDK throws when the save is refused |
ReplaceItemAsync | Replaces a item in the Azure Cosmos service as an asynchronous operation |
ItemRequestOptions | The options for this one request |
IfMatchEtag | Gets or sets the If-Match (ETag) associated with the request in the Azure Cosmos DB service. The save goes through only while the stored item still has this ETag |
HttpStatusCode.PreconditionFailed | 412, from System.Net: the stored item has a newer ETag than <etag> |
Leave out the ItemRequestOptions, and ReplaceItemAsync replaces the stored item whatever its ETag is.
The Example
A shopping list is one note: an item in a container notes in a database howto, whose partition key path is /id. Ana and Ben open the note at the same time, and both see Milk. Ana adds eggs and saves, then Ben adds bread and saves. The console app NoteEdit plays both of them, so the two saves happen in a known order. It runs twice: first saving the plain way, to show what goes wrong, then with the ETag. It signs in with my Azure CLI account and deletes the note at the end, so it can run again.
Prerequisites
- The .NET 10 SDK.
dotnet --versionprints a version that starts with10.0. - The Azure CLI, signed in with
az login. The app uses that sign-in. - A Cosmos DB for NoSQL container whose partition key path is
/id, and a Cosmos DB data role for your account on it, such as Cosmos DB Built-in Data Contributor: Connect using role-based access control and Microsoft Entra ID.
Step 1: Create a Console App and Add the Packages
dotnet new console -n NoteEdit
cd NoteEdit
dotnet add package Microsoft.Azure.Cosmos --version 3.64.0
dotnet add package Newtonsoft.Json --version 13.0.4
dotnet add package Azure.Identity --version 1.21.0
dotnet new console -n NoteEdit creates the project in a new NoteEdit folder, and cd moves into it. The three packages are the Cosmos DB SDK, Newtonsoft.Json, which the SDK requires you to reference yourself, and the Microsoft Entra ID credentials. How to Connect to Azure Cosmos DB with Microsoft Entra ID in C# explains each one and the client. Each dotnet add package writes its package into the project file, which now reads:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Azure.Identity" Version="1.21.0" />
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.64.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
</ItemGroup>
</Project>
Step 2: Connect
Replace Program.cs, starting with the client:
using System.Text.Json;
using Azure.Identity;
using Microsoft.Azure.Cosmos;
// The account's URI, from its Overview page in the Azure portal.
const string AccountEndpoint = "https://cosmos-maf-servicedesk-4224.documents.azure.com:443/";
using CosmosClient client = new(AccountEndpoint, new AzureCliCredential(), new CosmosClientOptions
{
UseSystemTextJsonSerializerWithOptions = JsonSerializerOptions.Web,
});
Container notes = client.GetContainer("howto", "notes");
PartitionKey key = new("shopping");
AccountEndpoint is your account's URI, from its Overview page in the Azure portal, and AzureCliCredential signs in with your Azure CLI account. JsonSerializerOptions.Web writes the note's Id as id, the name Cosmos DB expects. The note's ID is shopping, and with the partition key path /id that's its partition key value too, so key is new("shopping").
Step 3: Save Without the ETag
First, the plain way. Add two people who read the note:
await notes.UpsertItemAsync(new Note("shopping", "Milk"), key);
// Ana and Ben open the same note.
ItemResponse<Note> ana = await notes.ReadItemAsync<Note>("shopping", key);
ItemResponse<Note> ben = await notes.ReadItemAsync<Note>("shopping", key);
Console.WriteLine($"Ana and Ben both read: \"{ana.Resource.Text}\"");
UpsertItemAsyncwrites the note with the text Milk, whether or not it exists already.- The two
ReadItemAsynccalls are Ana and Ben opening the note. Each returns anItemResponse<Note>: the note is inResource, and the ETag of the version they read is inETag.
Then both of them save:
// Ana saves first, then Ben.
ItemResponse<Note> saved = await notes.ReplaceItemAsync(ana.Resource with { Text = "Milk, eggs" }, "shopping", key);
Console.WriteLine($"Ana saves \"Milk, eggs\": {(int)saved.StatusCode} {saved.StatusCode}");
saved = await notes.ReplaceItemAsync(ben.Resource with { Text = "Milk, bread" }, "shopping", key);
Console.WriteLine($"Ben saves \"Milk, bread\": {(int)saved.StatusCode} {saved.StatusCode}");
ana.Resource with { Text = "Milk, eggs" }is Ana's copy of the note with her change.ReplaceItemAsyncsaves it over the stored note with the IDshoppingin the partitionkey.- Ben's save is the same, from the copy he read: Milk, plus bread.
Last, read what's stored and clean up:
Note stored = (await notes.ReadItemAsync<Note>("shopping", key)).Resource;
Console.WriteLine($"Stored: \"{stored.Text}\"");
// Remove the note, so the app can run again.
await notes.DeleteItemAsync<Note>("shopping", key);
record Note(string Id, string Text);
The last read shows what Cosmos DB kept, DeleteItemAsync removes the note, and the Note record is the item: an ID and a text. Run it:
dotnet run
Ana and Ben both read: "Milk"
Ana saves "Milk, eggs": 200 OK
Ben saves "Milk, bread": 200 OK
Stored: "Milk, bread"

Both saves answered 200 OK, and the note says Milk, bread: Ana's eggs are gone, and neither of them was told. Ben's copy was made before Ana saved, so saving it replaced her change. That's a lost update, and Cosmos DB can't spot it on its own: the database doesn't know if the previously read value by either or both of the conflicting operations was indeed the latest value of the item. It doesn't check unless the save asks it to: For replace item operations, if-match must be explicitly expressed as a part of the request options.
Step 4: Send the ETag You Read
Now each save sends the ETag of the copy it was made from. Change Ana's save to:
// Ana saves first. The note still has the ETag she read, so Cosmos DB saves her change.
ItemResponse<Note> saved = await notes.ReplaceItemAsync(ana.Resource with { Text = "Milk, eggs" }, "shopping", key,
new ItemRequestOptions { IfMatchEtag = ana.ETag });
Console.WriteLine($"Ana saves \"Milk, eggs\": {(int)saved.StatusCode} {saved.StatusCode}");
ana.ETagis the note's ETag when Ana read it. Microsoft's reference for theETagof a response: ETags are used for concurrency checking when updating resources.new ItemRequestOptions { IfMatchEtag = ana.ETag }sends it with the save, as the request'sIf-Matchheader. Cosmos DB compares it with the note's_etag: If the value of theif-matchheader matches the value of the_etagat the server, the item is then updated. Nobody has saved the note since Ana read it, so they match.
Step 5: Catch the 412 and Try Again
HttpStatusCode is in System.Net, so add this as the first line of Program.cs:
using System.Net;
Then replace Ben's save with one that sends his ETag, and says what to do when Cosmos DB refuses it:
// Ben saves with the ETag he read. Ana's change gave the note a new one, so Cosmos DB refuses.
try
{
await notes.ReplaceItemAsync(ben.Resource with { Text = "Milk, bread" }, "shopping", key,
new ItemRequestOptions { IfMatchEtag = ben.ETag });
}
catch (CosmosException exception) when (exception.StatusCode == HttpStatusCode.PreconditionFailed)
{
Console.WriteLine($"Ben saves \"Milk, bread\": {(int)exception.StatusCode} {exception.StatusCode}");
// Ben reads the note again, adds his change to what's there now, and saves with the new ETag.
ben = await notes.ReadItemAsync<Note>("shopping", key);
Console.WriteLine($"Ben reads it again: \"{ben.Resource.Text}\"");
saved = await notes.ReplaceItemAsync(ben.Resource with { Text = ben.Resource.Text + ", bread" }, "shopping", key,
new ItemRequestOptions { IfMatchEtag = ben.ETag });
Console.WriteLine($"Ben saves \"{saved.Resource.Text}\": {(int)saved.StatusCode} {saved.StatusCode}");
}
IfMatchEtag = ben.ETagis the ETag from before Ana saved. Her save gave the note a new_etag, so Cosmos DB answers412and writes nothing, and the SDK throws aCosmosExceptionwith that status.when (exception.StatusCode == HttpStatusCode.PreconditionFailed)catches only the 412. Any other error still stops the app, as it should.- Inside the
catch, Ben does what Microsoft advises for a 412: Retry the request after reading the latest version of the resource and updating the eTag on the request.ReadItemAsyncgets the note as it is now, with its new ETag inben.ETag. His change is added to that text,ben.Resource.Text + ", bread", and the save sends the new ETag.
Adding the change to the text he just read is what keeps both changes. Saving his old copy, Milk, bread, with the new ETag would go through just as well, because the ETag matches, and Ana's eggs would be lost all the same.
Step 6: Run It Again
dotnet run
Ana and Ben both read: "Milk"
Ana saves "Milk, eggs": 200 OK
Ben saves "Milk, bread": 412 PreconditionFailed
Ben reads it again: "Milk, eggs"
Ben saves "Milk, eggs, bread": 200 OK
Stored: "Milk, eggs, bread"

- Ana saves:
200 OK, because the note still had the ETag she read. - Ben saves:
412 PreconditionFailed, because his ETag was from before Ana's save. Nothing was written. - Ben reads it again: Milk, eggs, with Ana's change and a new ETag.
- Ben saves:
200 OK, and the note keeps both changes: Milk, eggs, bread.
Running the app a second time printed exactly the same lines: it deletes the note at the end.
The Complete File
using System.Net;
using System.Text.Json;
using Azure.Identity;
using Microsoft.Azure.Cosmos;
// The account's URI, from its Overview page in the Azure portal.
const string AccountEndpoint = "https://cosmos-maf-servicedesk-4224.documents.azure.com:443/";
using CosmosClient client = new(AccountEndpoint, new AzureCliCredential(), new CosmosClientOptions
{
UseSystemTextJsonSerializerWithOptions = JsonSerializerOptions.Web,
});
Container notes = client.GetContainer("howto", "notes");
PartitionKey key = new("shopping");
await notes.UpsertItemAsync(new Note("shopping", "Milk"), key);
// Ana and Ben open the same note.
ItemResponse<Note> ana = await notes.ReadItemAsync<Note>("shopping", key);
ItemResponse<Note> ben = await notes.ReadItemAsync<Note>("shopping", key);
Console.WriteLine($"Ana and Ben both read: \"{ana.Resource.Text}\"");
// Ana saves first. The note still has the ETag she read, so Cosmos DB saves her change.
ItemResponse<Note> saved = await notes.ReplaceItemAsync(ana.Resource with { Text = "Milk, eggs" }, "shopping", key,
new ItemRequestOptions { IfMatchEtag = ana.ETag });
Console.WriteLine($"Ana saves \"Milk, eggs\": {(int)saved.StatusCode} {saved.StatusCode}");
// Ben saves with the ETag he read. Ana's change gave the note a new one, so Cosmos DB refuses.
try
{
await notes.ReplaceItemAsync(ben.Resource with { Text = "Milk, bread" }, "shopping", key,
new ItemRequestOptions { IfMatchEtag = ben.ETag });
}
catch (CosmosException exception) when (exception.StatusCode == HttpStatusCode.PreconditionFailed)
{
Console.WriteLine($"Ben saves \"Milk, bread\": {(int)exception.StatusCode} {exception.StatusCode}");
// Ben reads the note again, adds his change to what's there now, and saves with the new ETag.
ben = await notes.ReadItemAsync<Note>("shopping", key);
Console.WriteLine($"Ben reads it again: \"{ben.Resource.Text}\"");
saved = await notes.ReplaceItemAsync(ben.Resource with { Text = ben.Resource.Text + ", bread" }, "shopping", key,
new ItemRequestOptions { IfMatchEtag = ben.ETag });
Console.WriteLine($"Ben saves \"{saved.Resource.Text}\": {(int)saved.StatusCode} {saved.StatusCode}");
}
Note stored = (await notes.ReadItemAsync<Note>("shopping", key)).Resource;
Console.WriteLine($"Stored: \"{stored.Text}\"");
// Remove the note, so the app can run again.
await notes.DeleteItemAsync<Note>("shopping", key);
record Note(string Id, string Text);

Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Replacing an item without IfMatchEtag | A save made from an old copy wipes out newer changes, and still answers 200 OK | Send the ETag you read: new ItemRequestOptions { IfMatchEtag = <response>.ETag } |
| Retrying with the ETag you first read | It still isn't current, so the save fails with 412 again | Read the item again and send the new response's ETag |
| Saving your old copy again with the new ETag | The save goes through, and the other change is lost anyway | Apply your change to the item you just read |
Catching every CosmosException as a 412 | Errors such as a missing role look like a conflict | Add when (exception.StatusCode == HttpStatusCode.PreconditionFailed) |
Setting IfMatchEtag on CreateItemAsync | Microsoft's reference says CreateItemAsync ignores it | Use it on replace and delete calls. CreateItemAsync already refuses an ID that exists in the partition |
FAQ
Does the SDK retry a 412 by itself?
No. In Microsoft's table of status codes for the Cosmos DB SDKs, 412 says No under both "Should add retry" and "SDKs retry": the same request would only fail the same way, because its ETag is still old. Read the item again, apply your change, and save with the new ETag, as in Step 5.
Does reading an item lock it?
No. In the run, Ben had read the note before Ana saved it, and her save still answered 200 OK. A replace checks the ETag only when it sends one: then Cosmos DB compares IfMatchEtag with the item's current _etag.
Can I delete an item only if it hasn't changed?
DeleteItemAsync takes the same ItemRequestOptions, so you can pass IfMatchEtag to it too, and Microsoft's reference for IfMatchEtag says it's most commonly used with the delete and replace methods of Container. I only ran replaces here.
Do upserts and creates check the ETag?
CreateItemAsync ignores IfMatchEtag. UpsertItemAsync ignores it when the upsert creates the item, and applies it when the upsert replaces one. Both come from Microsoft's reference for IfMatchEtag.
How do I let a save win on purpose?
Leave IfMatchEtag out. ReplaceItemAsync then replaces whatever is stored, as Ben's save did in the first run.
Conclusion
To update an Azure Cosmos DB item only if it hasn't changed since you read it, pass the ETag from your read to ReplaceItemAsync as new ItemRequestOptions { IfMatchEtag = ... }. If someone saved first, the call throws a CosmosException with PreconditionFailed (412) and writes nothing: read the item again, apply your change to what's there now, and save with the new ETag. Without the ETag, the last save wins without a word.
Additional Resources
- Transactions and optimistic concurrency control —
_etag, theif-matchheader and the 412 answer. - Design resilient applications with Azure Cosmos DB SDKs — which status codes to retry, and what to do after a 412.
- RequestOptions.IfMatchEtag Property — the .NET reference, with the methods that ignore it.
- Container.ReplaceItemAsync Method — its parameters and what it returns.
- Create an item in Azure Cosmos DB for NoSQL using .NET —
CreateItemAsync,ReplaceItemAsyncandUpsertItemAsync.
