Database / Azure Cosmos DB interview questions
How does optimistic concurrency work in Azure Cosmos DB?
Cosmos DB uses ETags for optimistic concurrency control. Every item in Cosmos DB has a system-generated _etag property that changes on every write. When you read an item, you get its current ETag. When you want to update that item, you include the ETag in the write request using the If-Match HTTP header (or the SDK equivalent ifMatchEtag option). Cosmos DB compares your ETag against the item's current ETag on the server.
- If they match — no one else has modified the item since you read it — the write succeeds and a new ETag is assigned.
- If they do not match — someone else modified the item in between — the server returns HTTP 412 Precondition Failed and your write is rejected.
This prevents the lost-update problem in concurrent environments without holding any locks, which would block reads. The calling code is expected to handle the 412 by re-reading the item with its new ETag and re-applying the business logic before retrying the write.
// C# SDK example
ItemResponse<Product> readResponse = await container.ReadItemAsync<Product>(
"product-42", new PartitionKey("electronics"));
Product product = readResponse.Resource;
string etag = readResponse.ETag;
product.Price = 29.99m;
try
{
await container.ReplaceItemAsync(
product, product.Id,
new PartitionKey("electronics"),
new ItemRequestOptions { IfMatchEtag = etag });
}
catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.PreconditionFailed)
{
// Retry: re-read, re-apply business logic, retry write
}ETags are also used in Change Feed processing — you can use the ETag to detect whether an item has changed since you last processed it, avoiding redundant processing of unchanged items.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
