Skip to main content

How to Update an Azure Cosmos DB Item Only If It Hasn't Changed with an ETag in C#

· 15 min read
Jagdish Kumawat
Founder @ Dewiride

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​

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
}
PartWhat 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
ReplaceItemAsyncReplaces a item in the Azure Cosmos service as an asynchronous operation
ItemRequestOptionsThe options for this one request
IfMatchEtagGets 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.PreconditionFailed412, 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 --version prints a version that starts with 10.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​

Terminal
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:

NoteEdit.csproj
<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:

Program.cs (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:

Program.cs (two people 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}\"");
  • UpsertItemAsync writes the note with the text Milk, whether or not it exists already.
  • The two ReadItemAsync calls are Ana and Ben opening the note. Each returns an ItemResponse<Note>: the note is in Resource, and the ETag of the version they read is in ETag.

Then both of them save:

Program.cs (both 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. ReplaceItemAsync saves it over the stored note with the ID shopping in the partition key.
  • Ben's save is the same, from the copy he read: Milk, plus bread.

Last, read what's stored and clean up:

Program.cs (what's stored)
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:

Terminal
dotnet run
Output
Ana and Ben both read: "Milk"
Ana saves "Milk, eggs": 200 OK
Ben saves "Milk, bread": 200 OK
Stored: "Milk, bread"

macOS-style terminal window titled Terminal — NoteEdit showing dotnet run without the ETag: Ana and Ben both read Milk, Ana saves Milk, eggs with 200 OK, Ben saves Milk, bread with 200 OK, and the stored note is 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:

Program.cs (Ana's save, with her ETag)
// 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.ETag is the note's ETag when Ana read it. Microsoft's reference for the ETag of a response: ETags are used for concurrency checking when updating resources.
  • new ItemRequestOptions { IfMatchEtag = ana.ETag } sends it with the save, as the request's If-Match header. Cosmos DB compares it with the note's _etag: If the value of the if-match header matches the value of the _etag at 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:

Program.cs (first line)
using System.Net;

Then replace Ben's save with one that sends his ETag, and says what to do when Cosmos DB refuses it:

Program.cs (Ben's save, with his ETag)
// 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.ETag is the ETag from before Ana saved. Her save gave the note a new _etag, so Cosmos DB answers 412 and writes nothing, and the SDK throws a CosmosException with 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. ReadItemAsync gets the note as it is now, with its new ETag in ben.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​

Terminal
dotnet run
Output
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"

macOS-style terminal window titled Terminal — NoteEdit showing dotnet run with the ETag: Ana and Ben both read Milk, Ana saves Milk, eggs with 200 OK, Ben saves Milk, bread with 412 PreconditionFailed, Ben reads Milk, eggs again and saves Milk, eggs, bread with 200 OK, and the stored note is 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​

Program.cs
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);

macOS-style code window titled Program.cs — NoteEdit showing Ana and Ben reading the shopping note with ReadItemAsync, Ana's ReplaceItemAsync with IfMatchEtag set to her ETag, and Ben's ReplaceItemAsync with his ETag inside a try, whose catch for CosmosException when the status code is PreconditionFailed reads the note again and saves his change with the new ETag

Common Mistakes​

MistakeWhat happensDo this instead
Replacing an item without IfMatchEtagA save made from an old copy wipes out newer changes, and still answers 200 OKSend the ETag you read: new ItemRequestOptions { IfMatchEtag = <response>.ETag }
Retrying with the ETag you first readIt still isn't current, so the save fails with 412 againRead the item again and send the new response's ETag
Saving your old copy again with the new ETagThe save goes through, and the other change is lost anywayApply your change to the item you just read
Catching every CosmosException as a 412Errors such as a missing role look like a conflictAdd when (exception.StatusCode == HttpStatusCode.PreconditionFailed)
Setting IfMatchEtag on CreateItemAsyncMicrosoft's reference says CreateItemAsync ignores itUse 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​