Database / Azure Cosmos DB interview questions
What is the Cosmos DB Patch API and how does it differ from Replace?
The Patch API (partial document update) was introduced in Cosmos DB in 2022 to address a common inefficiency in document updates. Before Patch, the only way to modify a field in a Cosmos DB item was to read the full document, change the field in memory, and replace the entire document. For large documents or high-frequency partial updates this was wasteful — full read + full write = ~6x the RU cost of a targeted patch.
The Patch API lets you specify a list of operations to apply directly on the server without reading the document first. Supported patch operations:
add— Add a new property or array element at the specified pathset— Set a property to a value (creates if absent, overwrites if present)replace— Replace an existing property (fails if the property does not exist)remove— Delete a propertyincrement— Atomically increment a numeric property by a delta valuemove— Move a property from one path to another
// C# Patch API example: update price and increment stock count atomically PatchOperation[] patches = new[] { PatchOperation.Set("/price", 24.99), PatchOperation.Increment("/stockCount", -1), PatchOperation.Add("/lastModified", DateTime.UtcNow) }; await container.PatchItemAsync<Product>("product-42", new PartitionKey("electronics"), patches);
The increment operation is particularly powerful for counters — it is atomic at the document level, so concurrent increments from multiple clients do not race (unlike read-modify-replace which is a classic read-modify-write race condition). Patch also supports a condition parameter (a SQL WHERE-like filter) that makes the patch conditional — apply only if the document matches the filter, otherwise return a 412.
More Related questions...