Introduction
Azure Cosmos DB is a globally distributed NoSQL database designed for applications that require high availability, low latency, and flexible scalability. It supports horizontal partitioning, allowing applications to distribute data across multiple logical and physical partitions.
However, partitioning introduces an important challenge when an application needs to update multiple related records together. For example, consider a banking application that transfers money from one account to another. The application must decrease the balance of the sender, increase the balance of the receiver, and create a transaction history record. If these records belong to different logical partitions, maintaining consistency becomes more complicated.
Traditionally, Azure Cosmos DB supported ACID transactions within a single logical partition. Developers needed to implement application-level coordination, compensation logic, or the saga pattern when operations crossed partition boundaries.
Azure Cosmos DB for NoSQL now introduces distributed transactions in public preview. This capability allows developers to execute atomic read and write operations across multiple logical partitions, containers, and databases within the same account and region.
In this article, we will explore how distributed transactions work, how to configure them, and how to implement cross-partition transactions using the Azure Cosmos DB .NET SDK.
Understanding Transactions in Azure Cosmos DB
A database transaction is a group of operations treated as a single logical unit. A transaction follows ACID properties:
- Atomicity ensures that all operations succeed or none of them are committed.
- Consistency ensures that transactions maintain valid application data.
- Isolation prevents concurrent operations from observing partially committed changes.
- Durability ensures that committed changes are retained.
Azure Cosmos DB has traditionally provided ACID transaction support within a single logical partition.
A logical partition contains items that share the same partition key value. For example, if an accounts container uses /accountId as its partition key, all records associated with account-101 belong to the same logical partition.
When two accounts have different partition key values, their records belong to different logical partitions.
Why Cross-Partition Transactions Are Challenging
Consider a banking application with two accounts.
| Account |
Partition key |
Initial balance |
| account-101 |
account-101 |
1000 |
| account-202 |
account-202 |
500 |
Suppose the application transfers 200 from account-101 to account-202.
The application needs to perform three operations:
- Decrease account-101's balance by 200.
- Increase account-202's balance by 200.
- Create a transaction history record.
If the first operation succeeds but the second fails, the application can end up with inconsistent financial data.
A traditional transactional batch cannot solve this scenario because the operations involve different partition keys.
Distributed transactions address this limitation by allowing supported operations across multiple logical partitions to participate in one atomic transaction.
Understanding Distributed Transactions in Azure Cosmos DB
Distributed transactions extend transaction boundaries beyond a single logical partition.
With the distributed transaction API, an application can execute operations across:
- Multiple logical partitions within the same container.
- Multiple containers within the same database.
- Multiple databases within the same Cosmos DB account.
All participating operations are committed as one atomic unit. If the transaction aborts, none of its writes are committed.
For example, a banking application can update two account records and create a ledger entry in a separate container through one distributed write transaction.
It is important to understand that distributed transactions are currently in public preview. They do not have a service-level agreement, and supported features, limits, and behavior can change before general availability.
Distributed Transactions vs. Transactional Batch
Azure Cosmos DB provides two transaction approaches for different scenarios.
| Feature |
Transactional Batch |
Distributed Transaction |
| Transaction scope |
One logical partition |
Multiple logical partitions |
| Multiple containers |
No |
Yes |
| Multiple databases |
No |
Yes, within the same account |
| Atomic writes |
Yes |
Yes |
| Atomic reads |
Not a distributed snapshot |
Yes |
| Performance |
Generally lower latency |
Additional distributed coordination |
| Availability |
Established capability |
Public preview |
Use transactional batch when all related records share the same complete partition key in one container.
Use distributed transactions when the business operation genuinely requires atomic updates across different partitions, containers, or databases.
Prerequisites for Implementing Distributed Transactions
Before implementing this functionality, verify that your Azure Cosmos DB account meets the current preview requirements.
The distributed transaction preview has specific limitations:
- The account must use the Azure Cosmos DB for NoSQL API.
- The account must use provisioned throughput, either manual or autoscale.
- Serverless accounts are not supported in the preview.
- The account must have a single write region.
- The account must run in a supported public Azure region.
- Certain features, including customer-managed keys, continuous backup, hierarchical partition keys, and per-partition automatic failover, are not supported in the preview.
You must also request enrollment for the account through the distributed transactions onboarding process. Self-service enrollment through the Azure portal or Azure CLI is not currently available.
For .NET applications, use the supported preview version of the Azure Cosmos DB SDK. The current documentation specifies Microsoft.Azure.Cosmos version 3.64.0-preview.0 as the minimum required version.
Installing the Azure Cosmos DB SDK
Create a new .NET console application:
dotnet new console -n CosmosDistributedTransactions
cd CosmosDistributedTransactions
Install the required Azure Cosmos DB SDK:
dotnet add package Microsoft.Azure.Cosmos --version 3.64.0-preview.0
For Microsoft Entra ID authentication, also install Azure.Identity:
dotnet add package Azure.Identity
The Cosmos DB SDK provides the distributed transaction APIs, while Azure.Identity allows the application to authenticate using developer credentials or a managed identity.
Configuring the CosmosClient
The first step is creating a CosmosClient instance.
The distributed transaction API uses CosmosClientOptions to configure retry behavior for transactions that the service reports as retriable.
using Microsoft.Azure.Cosmos;
using Azure.Identity;
var options = new CosmosClientOptions
{
MaxRetryAttemptsOnAbortedTransactions = 10,
MaxRetryWaitTimeOnAbortedTransactions =
TimeSpan.FromSeconds(30)
};
string endpoint =
"https://<your-account>.documents.azure.com:443/";
using CosmosClient client = new CosmosClient(
endpoint,
new DefaultAzureCredential(),
options
);
DefaultAzureCredential supports several authentication methods, including developer credentials and managed identities.
For production applications, managed identity is generally a better choice than storing account keys in configuration files.
The application identity must have data-plane write permissions on every container participating in the distributed transaction. The Cosmos DB Built-in Data Contributor role is one example of a suitable role.
Next, retrieve references to the required containers:
Container accounts =
client.GetContainer("banking", "accounts");
Container ledger =
client.GetContainer("banking", "ledger");
In this example, the banking database contains two containers:
- accounts stores customer account information and uses /pk as its partition key.
- ledger stores transaction history and also uses /pk as its partition key.
Implementing a Cross-Partition Write Transaction
Let's implement a banking transaction that transfers money between two accounts.
Assume that the accounts container contains the following records:
{
"id": "account-A",
"pk": "account-A",
"balance": 1000
}
{
"id": "account-B",
"pk": "account-B",
"balance": 1000
}
The application will transfer 100 from account-A to account-B and create a corresponding ledger entry.
Creating the distributed transaction
The .NET SDK provides CreateDistributedWriteTransaction() to create a distributed write transaction.
The following example uses conditional patch operations to update both accounts.
using Microsoft.Azure.Cosmos;
var ledgerEntry = new
{
id = "txn-1001",
pk = "2026-12",
from = "account-A",
to = "account-B",
amount = 100
};
using DistributedTransactionResponse response =
await client
.CreateDistributedWriteTransaction()
.PatchItem(
accounts,
new PartitionKey("account-A"),
"account-A",
new[]
{
PatchOperation.Increment("/balance", -100L)
},
new DistributedTransactionPatchItemRequestOptions
{
FilterPredicate =
"from c where c.balance >= 100"
})
.PatchItem(
accounts,
new PartitionKey("account-B"),
"account-B",
new[]
{
PatchOperation.Increment("/balance", 100L)
})
.CreateItem(
ledger,
new PartitionKey("2026-12"),
ledgerEntry.id,
ledgerEntry)
.ExecuteTransactionAsync(
CancellationToken.None
);
There are three operations in this transaction.
The first PatchItem operation decreases the sender's balance by 100. The FilterPredicate ensures that the account has enough balance before the update is accepted.
The second PatchItem operation increases the receiver's balance by 100.
The CreateItem operation adds a transaction record to the ledger container.
Because all three operations belong to the same distributed transaction, Azure Cosmos DB commits them together or aborts the transaction.
The example assumes that both account records already exist and that the required containers use the /pk partition key path.
Handling the transaction response
After executing the transaction, inspect the response before treating the operation as successful.
if (!response.IsSuccessStatusCode ||
response.Any(operation =>
!operation.IsSuccessStatusCode))
{
throw new InvalidOperationException(
$"Transaction failed: {response.StatusCode}; " +
$"{response.ErrorMessage}; " +
$"ActivityId={response.ActivityId}; " +
$"Diagnostics={response.Diagnostics}"
);
}
Console.WriteLine("Transaction committed.");
Checking both the overall response and individual operation results helps identify failures during transaction execution.
The preview also supports a FastResponse mode. In this mode, a response can arrive before the final commit or abort outcome is known. Therefore, applications must not treat every successful initial response as proof that the transaction has reached a terminal committed state.
Implementing Cross-Partition Read Transactions
Distributed transactions are not limited to write operations. They also support consistent reads across multiple logical partitions and containers.
Consider a reporting application that needs to read two account balances at the same committed point in time.
Using independent ReadItemAsync calls can produce inconsistent results if a transfer occurs between the two reads.
A distributed read transaction solves this problem by providing a point-in-time consistent snapshot.
The following example reads two accounts:
using System.Net;
using Microsoft.Azure.Cosmos;
using DistributedTransactionResponse response =
await client
.CreateDistributedReadTransaction()
.ReadItem(
accounts,
new PartitionKey("account-A"),
"account-A"
)
.ReadItem(
accounts,
new PartitionKey("account-B"),
"account-B"
)
.ExecuteTransactionAsync(
CancellationToken.None
);
if (!response.IsSuccessStatusCode &&
response.StatusCode != HttpStatusCode.NotModified)
{
throw new InvalidOperationException(
$"Read transaction failed: {response.ErrorMessage}"
);
}
for (int i = 0; i < response.Count; i++)
{
if (response[i].StatusCode == HttpStatusCode.NotModified)
{
continue;
}
if (!response[i].IsSuccessStatusCode)
{
throw new InvalidOperationException(
$"Read operation {i} failed."
);
}
var account =
response.GetOperationResultAtIndex<
Dictionary<string, object>
>(i).Resource;
Console.WriteLine(
$"{account["id"]}: {account["balance"]}"
);
}
The results are returned in the same order as the read operations were added.
This approach is useful when an application needs to compare related records without observing a partially applied distributed write transaction.
For ordinary single-item reads, continue using ReadItemAsync because it is generally simpler and has lower overhead.
Important Considerations for Production Applications
Distributed transactions simplify cross-partition consistency, but they introduce additional considerations for production systems.
Handle concurrent account updates
Two applications may attempt to update the same account simultaneously.
A conditional patch operation helps protect business rules. In the banking example, the sender's balance must remain sufficient before the debit is accepted.
For more complex updates, consider ETags and optimistic concurrency control.
Implement safe retry handling
Network interruptions and transaction aborts can occur.
The SDK provides retry options for transactions reported as retriable by the service. However, applications must understand the difference between a confirmed abort and a request that was canceled or interrupted before the final outcome was known.
A canceled request does not prove that the transaction rolled back. Do not blindly execute the same business operation again.
Use a unique business transaction identifier and an idempotency strategy to prevent duplicate transfers or ledger records.
Monitor transaction diagnostics
The SDK exposes transaction diagnostics, activity IDs, response status codes, and operation-level results.
Log these details when transactions fail. They help identify throttling, conflicts, permission problems, and other service-side issues.
Avoid logging sensitive information such as account credentials or unnecessary customer data.
Understand multi-region behavior
During the preview, distributed transactions are atomic within the write region.
Accounts with multiple write regions are not supported. Data replication to secondary regions is asynchronous and occurs per partition.
Applications that require consistent transactional reads should consider routing reads to the write region or following the documented session-token and consistency guidance.
Common Mistakes and Troubleshooting
| Problem |
Possible reason |
Recommended solution |
| Distributed transaction API is unavailable |
Incorrect SDK version |
Install the supported preview SDK |
| Transaction enrollment fails |
Account is not enrolled or does not meet preview requirements |
Verify account eligibility and enrollment |
| Transaction returns 403 |
Missing data-plane permissions |
Assign the required Cosmos DB data role |
| Transaction is aborted |
A conditional operation or another operation failed |
Inspect individual operation results |
| Duplicate ledger entries |
Unsafe retry implementation |
Use unique transaction IDs and idempotency controls |
| Read results are inconsistent |
Independent reads were used |
Use a distributed read transaction |
| Transaction cannot execute |
Unsupported account configuration |
Review the preview limitations |
One important mistake is assuming that a transaction can span multiple Cosmos DB accounts. The current distributed transaction preview supports operations across partitions, containers, and databases within the same account and region. It does not provide a distributed transaction boundary across separate Cosmos DB accounts.
Advantages and Disadvantages of Distributed Transactions
Advantages
- Cross-partition consistency: Multiple related records can be updated atomically even when they belong to different logical partitions.
- Simplified application logic: Developers can avoid implementing custom coordination and compensation logic for supported transaction scenarios.
- Consistent reads: Applications can read related records from different partitions using a single point-in-time snapshot.
- Multiple containers: A transaction can update business records and corresponding ledger or audit records in different containers.
- Existing .NET integration: Developers can use the Azure Cosmos DB .NET SDK to create and execute distributed transactions.
Disadvantages
- Preview limitations: The feature is not generally available and does not include an SLA.
- Additional coordination: Distributed transactions involve more coordination than single-partition operations.
- Account restrictions: Several Cosmos DB account configurations are not supported in the preview.
- Regional limitations: The current preview does not support multi-region write accounts.
- Operational complexity: Developers must handle transaction outcomes, retries, diagnostics, and application-level idempotency carefully.
Summary
Cross-partition transactions have traditionally been challenging in Azure Cosmos DB because transactional batch operations are limited to a single logical partition within one container.
Distributed transactions in Azure Cosmos DB for NoSQL extend this capability by allowing applications to execute atomic read and write operations across multiple logical partitions, containers, and databases within the same account and region.
Using the Azure Cosmos DB .NET SDK, developers can implement these operations through CreateDistributedWriteTransaction() and CreateDistributedReadTransaction().
These capabilities are particularly useful for banking applications, inventory management, order processing, financial ledgers, and other systems where related records must remain consistent.
Before adopting distributed transactions in production, review the preview limitations, account eligibility, retry behavior, regional considerations, and application-level idempotency requirements.
Join the conversation! Your thoughts help the community grow.