Azure Cosmos DB for NoSQL can now commit writes across partition keys, containers, and databases as one atomic unit. Distributed transactions are currently in public preview. Every operation commits, or none of them do.
Previously, applications that needed atomic operations across multiple logical partitions often relied on application-managed patterns such as sagas and compensating transactions. Distributed transactions move that coordination into Azure Cosmos DB, simplifying application logic while preserving all-or-nothing execution.
This blog explains the problem, introduces the API, and walks through the sample application, where Alice transfers money to Bob and the application records a ledger entry.
What problem do distributed transactions solve?
Alice sends Bob $150. That’s three different write operations: Alice’s balance goes down, Bob’s goes up, and a ledger entry records the transfer. If any one of them lands without the others, your books are wrong.

In the sample, those three items deliberately live in different places:

| Item | Container | Partition key value |
|---|---|---|
| Alice’s account | accounts | alice |
| Bob’s account | accounts | bob |
| Ledger entry | ledger | posting month, for example 2026-11 |
Both containers use /pk as the partition key path. The distributed transactions guide use the same banking /accounts/ledger shape.
Why were transactions previously limited to one logical partition?
Azure Cosmos DB scales by partitioning your data. Its ACID guarantees, with snapshot isolation, have always applied to operations within one logical partition key (learn more). Because Alice and Bob use different partition keys, the transfer crossed that boundary.

Applications typically used one of two approaches::
- Model around it. If the items that change together share a partition key, use transactional batch. It’s atomic, but limited to one partition key in one container, 100 operations, 2 MB and 5 seconds. If one operation fails, the others return 424 (failed dependency) or 409 (conflict).
- Build a saga pattern. Split the business transaction into local steps and write compensating “undo” steps for when something fails. As the Ignite session put it, you build and operate all of it yourself, and retries, timeouts and compensations live in your code.
Transactional batch remains the best fit when the data model stays within one partition key. Distributed transactions address the cases that genuinely span partitions, containers, or databases.
What are distributed transactions in Azure Cosmos DB?
Distributed transactions are atomic read or write transactions that span logical partitions, containers, and databases within one Azure Cosmos DB for NoSQL account and region.

- Write transactions start with CosmosClient.CreateDistributedWriteTransaction(). You can combine CreateItem, UpsertItem, ReplaceItem, PatchItem and DeleteItem in one transaction, and they commit or abort together.
- Read transactions start with CosmosClient.CreateDistributedReadTransaction().They return the requested items from one committed snapshot, so the reader does not observe a partially applied distributed write.
- Scope: logical partitions, containers and databases within the same account and region.

How it works under the covers. Under the hood – Azure Cosmos DB coordinates a two-phase commit protocol across the participating partitions. During the preparation phase, participants validate and prepare their operations. Once all participants have successfully prepared, the service coordinates the commit. If preparation fails, the transaction is aborted. The benefit is that your team/application doesn’t run a coordinator and there is no need to orchestrate compensation logic anymore.

How does the sample app use distributed transactions?
The sample application is built with .NET and uses the Azure Cosmos DB .NET SDK (Microsoft.Azure.Cosmos 3.64.0-preview.0) along with Azure.Identity for authentication.
1. Setup the Cosmos DB Client
CosmosClientOptions clientOptions = new()
{
MaxRetryAttemptsOnAbortedTransactions = 10,
MaxRetryWaitTimeOnAbortedTransactions = TimeSpan.FromSeconds(30)
};
TokenCredential credential = environment.IsDevelopment()
? new DefaultAzureCredential()
: string.IsNullOrWhiteSpace(managedIdentityClientId)
? new ManagedIdentityCredential()
: new ManagedIdentityCredential(managedIdentityClientId);
client = new CosmosClient(options.Endpoint, credential, clientOptions);
The sample uses the SDK’s default transaction retry settings, allowing up to 10 retries or 30 seconds of cumulative retry delay for transactions the service identifies as retriable. HTTP 429 throttling is handled separately through the SDK’s rate-limiting retry settings.
For authentication, the application uses DefaultAzureCredential during development and managed identity when deployed, avoiding the need to manage account keys. Access is controlled through Microsoft Entra ID RBAC, with the sample requiring the Cosmos DB Built-in Data Contributor role scoped to the /dbs/banking database.
The application also reuses a single CosmosClient instance, following recommended SDK practices. These choices align with the Azure Cosmos DB Agent Kit guidance for authentication, least-privilege access, and client management.
2. The transfer: read, validate, then commit atomically
ItemResponse<CosmosAccount> alice = await ReadAccountAsync(AccountAId);
ItemResponse<CosmosAccount> bob = await ReadAccountAsync(AccountBId);
if (alice.Resource.Balance < amount) { /* client-side rejection */ }
using DistributedTransactionResponse response = await cosmosClient
.CreateDistributedWriteTransaction()
.PatchItem(accountsContainer, new PartitionKey(AccountAId), AccountAId,
[PatchOperation.Increment("/balance", -(double)amount)],
new DistributedTransactionPatchItemRequestOptions
{
IfMatchEtag = alice.ETag,
FilterPredicate = $"from c where c.balance >= {amountLiteral}"
})
.PatchItem(accountsContainer, new PartitionKey(AccountBId), AccountBId,
[PatchOperation.Increment("/balance", (double)amount)],
new DistributedTransactionPatchItemRequestOptions { IfMatchEtag = bob.ETag })
.CreateItem(ledgerContainer, new PartitionKey(entry.PartitionKey), entry.Id, entry)
.ExecuteTransactionAsync(cancellationToken);
Three things are worth calling out:
- PatchOperation.Increment changes each balance on the server instead of replacing it with a value calculated by the application.
- IfMatchEtag is optimistic concurrency. Every item has a server-generated _etag. If it no longer matches, the server rejects the operation with 412 Precondition Failed (learn more).
- FilterPredicate is a conditional patch. The SQL-like from c where … condition must hold, or the operation fails (learn more). Here it guards against Alice’s balance dropping after the read.
The application also checks Alice’s balance before it creates a write transaction. In the sample’s insufficient-funds scenario, a $500 transfer is rejected before any transaction is submitted.

3. Understanding Distributed Transaction Responses
Distributed transactions report one of two response modes. The all-or-nothing write guarantee is the same in both modes; the difference is when the client receives the response.
- Standard mode: Provides confirmation of the transaction’s final commit or abort outcome before returning a response. This is suitable for workloads that require confirmation of transaction completion before proceeding.
- FastResponse mode: Optimized for workloads that prioritize lower write latency and do not require immediate read-after-write visibility. The service can return an earlier response while continuing transaction processing in the background.
Both modes maintain the same atomicity and durability guarantees. FastResponse is particularly beneficial for write-intensive workloads where applications can continue processing without waiting for the final transaction outcome.
bool succeeded = response.IsSuccessStatusCode && response.All(operation => operation.IsSuccessStatusCode);
...
else if (response.ResponseMode == DistributedTransactionResponseMode.Standard)
message = successMessage;
else
message = " FastResponse received. Cosmos DB will continue processing the transaction.";
4. A consistent read: the receipt
using DistributedTransactionResponse response = await cosmosClient
.CreateDistributedReadTransaction()
.ReadItem(accountsContainer, new PartitionKey(AccountAId), AccountAId)
.ReadItem(accountsContainer, new PartitionKey(AccountBId), AccountBId)
.ReadItem(ledgerContainer, new PartitionKey(ledgerPartitionKey), ledgerId)
.ExecuteTransactionAsync(cancellationToken);
One call reads Alice, Bob, and the ledger entry across two partitions and two containers from the same committed snapshot. Results are returned in request order through GetOperationResultAtIndex<T>(i).
What happens when data changes mid-transaction?
The sample includes an optimistic-concurrency scenario: it stages a transfer, changes Alice’s account with an independent write, and then attempts to commit using the original ETags.

- Stage the transfer. Read Alice and Bob and retain their ETags. No transaction writes are submitted yet.
- Change Alice. An ordinary PatchItemAsync call adds 1 to Alice’s balance outside the transaction, which changes her _etag.
- Commit the staged transfer with the original ETags. Alice’s conditional patch returns 412 (Precondition Failed), sometimes inside an overall 452 aborted transaction. Bob is not credited, and the ledger entry is not created.

The follow-up query confirms the result: Alice is at 301 because of the independent write, Bob remains at 1,000, and the ledger contains only the earlier successful transfer. After a confirmed conflict, read fresh state and recalculate instead of replaying the stale proposal.
What do you need to use distributed transactions with Azure Cosmos DB?
| Requirement | Details |
|---|---|
| API | NoSQL only |
| Throughput | Provisioned (manual or autoscale) |
| Regions | Public Azure region. Single-write regions only and multi-write region support is planned. |
| SDK | .NET v3 Microsoft.Azure.Cosmos 3.64.0-preview.0 or higher (other SDKs “coming soon”) |
| Enrollment | Request through the onboarding form; typically fulfilled in 1–2 business days |
| Limits | 100 operations, 2 MB per transaction |
Multi-region accounts: transactions are atomic within the write region. Committed changes replicate asynchronously to secondary regions. Depending on the configured consistency level and replication progress, readers in secondary regions can temporarily observe different versions of data across participating partitions.
Should you use transactional batch or distributed transactions?
- Use Transactional batch when every item shares one logical partition key in one container. It is the established, efficient choice for that scope (learn more).
- Use Distributed transactions when the atomic boundary must span partitions, containers, or databases in one account and region – for example, a balance transfer plus a ledger entry, or an order plus inventory updates.
FAQ
Are distributed transactions in Azure Cosmos DB generally available? No. They’re in public preview, without an SLA, and behavior and limits might change before general availability (learn more).
Can a distributed transaction span two Azure Cosmos DB accounts? No. The documented scope is logical partitions, containers and databases within the same account and region.
Which SDKs support it? The .NET v3 SDK, starting at 3.64.0-preview.0. Support for other SDKs is coming soon.
What happens if one operation fails? The transaction aborts and none of its writes are applied. In the sample’s ETag conflict, Alice’s operation returns 412 (Precondition Failed); the overall transaction can return 452 to indicate that it was aborted. Bob is not credited, and no ledger entry is written (sample).
Do I still need transactional batch? Yes. Use it when all items share one logical partition key in one container (learn more).
How do I authenticate without keys? Use Microsoft Entra ID with DefaultAzureCredential or a managed identity. The identity must have data-plane permissions on every participating container; in the sample, Cosmos DB Built-in Data Contributor is scoped to /dbs/banking (learn more, sample).
Where can you try it?
- Read the guide: aka.ms/cosmosdb/dtx-learn
- Run the sample: aka.ms/cosmosdb/dtx-sample-app
- Request preview enrollment: aka.ms/cosmosdb/dtx-onboard
About Azure Cosmos DB
Azure Cosmos DB is a fully managed and serverless NoSQL and vector database for modern app development, including AI applications. With its SLA-backed speed and availability as well as instant dynamic scalability, it is ideal for real-time NoSQL applications that require high performance and distributed computing over massive volumes of NoSQL and vector data.
To stay in the loop on Azure Cosmos DB updates, follow us on X, YouTube, and LinkedIn.
0 comments
Be the first to start the discussion.