Rust is becoming an important choice for building high-performance backend services, cloud applications, and distributed systems. Its memory safety, predictable performance, and concurrency model make it suitable for applications that handle large amounts of data and concurrent requests.
When these applications need a globally distributed NoSQL database, Azure Cosmos DB is one option worth considering. It provides managed database infrastructure, automatic scaling, multiple consistency levels, and global data distribution.
Microsoft provides a native Azure Cosmos DB SDK for Rust that allows developers to connect Rust applications directly to Azure Cosmos DB for NoSQL. The SDK supports common database operations such as creating items, reading documents, updating records, and executing queries.
An important development is that the Azure Cosmos DB SDK for Rust reached general availability in November 2026. The GA release introduced production-focused improvements, including Gateway v2, binary serialization, automatic retry behavior, and per-partition availability features.
This article explains how to connect a Rust application to Azure Cosmos DB, configure authentication, create and read documents, execute queries, handle errors, and prepare the integration for production workloads.
Why Use Rust With Azure Cosmos DB?
Rust is designed for applications where performance, reliability, and resource efficiency matter.
Azure Cosmos DB complements Rust by providing a managed NoSQL database that can scale across regions and handle changing application workloads.
Combining the two technologies is useful for several application types.
High-Performance Backend Services
Rust is suitable for API services that handle a large number of concurrent requests. Its ownership model helps prevent common memory-related problems, while its asynchronous runtime supports efficient I/O operations.
When an application needs to read and write documents frequently, the native Cosmos DB SDK provides a direct integration without requiring a separate language bridge.
Distributed Applications
Azure Cosmos DB supports global distribution and multiple consistency levels. Applications can access data through configured regions and use the database's availability features.
Rust applications can use these capabilities to build distributed services, event-processing systems, and globally available APIs.
Microservices and Event-Driven Systems
Rust is often used for lightweight services that process messages, handle background jobs, or expose APIs.
Azure Cosmos DB can store application state, event metadata, customer information, and other JSON-based records required by these services.
AI and Data-Driven Applications
Azure Cosmos DB supports vector search and other capabilities for modern AI applications. Rust services can use the database as a storage layer for application data, metadata, and retrieval workflows.
The exact AI and vector features available to an application depend on the selected Cosmos DB API and SDK capabilities.
Understanding the Azure Cosmos DB SDK for Rust
The official Azure Cosmos DB SDK for Rust is available through the azure_data_cosmos crate.
It provides a native interface for interacting with Azure Cosmos DB for NoSQL.
The SDK reached general availability on November 17, 2026. This release is an important milestone because the earlier public preview was not recommended for production workloads.
The GA release includes several improvements.
Gateway v2
The SDK uses Gateway v2 by default. This provides a performance-optimized gateway path without requiring developers to configure direct-mode networking.
It reduces the client-side complexity associated with managing connections to individual physical partitions.
Binary Serialization
The GA SDK enables Cosmos Binary serialization by default.
Instead of relying exclusively on JSON serialization for the network communication path, the SDK uses a binary representation designed to reduce serialization overhead and the amount of data transferred.
This can improve network efficiency and reduce serialization costs. Actual RU consumption still depends on the database operation, indexing, document size, and workload.
Automatic Retry Behavior
The SDK automatically retries read and write operations when retrying is considered safe.
However, not every operation can be retried safely. Stored procedure execution and certain patch operations may require special handling because repeating an operation could produce unexpected results.
Developers should understand the retry behavior of the operation they are using instead of assuming that every failed request is automatically recoverable.
Per-Partition Automatic Failover
The GA release includes per-partition automatic failover (PPAF) and the per-partition circuit breaker (PPCB).
These capabilities help isolate availability problems to individual partitions instead of unnecessarily failing over an entire container.
This is particularly useful for applications with large numbers of partitions and demanding availability requirements.
SDK Features at a Glance
Capability | Description |
|---|
Native Rust client | Direct integration with Azure Cosmos DB for NoSQL |
Gateway v2 | Optimized gateway communication |
Binary serialization | More efficient data transfer and parsing |
Automatic retries | Retries operations when considered safe |
PPAF | Supports automatic failover at partition level |
PPCB | Helps isolate unhealthy partition communication |
Cross-partition queries | Supports queries across multiple partitions |
Request hedging | Optional mechanism to reduce tail latency |
These capabilities are enabled by default where applicable. Request hedging is optional and should be evaluated against the application's latency and RU consumption requirements.
Prerequisites
Before connecting a Rust application to Azure Cosmos DB, prepare the development environment.
You need:
A working Rust development environment.
Rust and Cargo installed.
An Azure subscription.
An Azure Cosmos DB for NoSQL account.
Appropriate database permissions.
A code editor such as Visual Studio Code.
You can also use the Azure Cosmos DB Emulator for local development and testing.
Check the Rust installation:
rustc --version
cargo --version
If Rust is not installed, use rustup to install the stable toolchain.
Create a new Rust project:
cargo new cosmos-rust-app
cd cosmos-rust-app
The project structure will look similar to this:
cosmos-rust-app/
├── Cargo.toml
└── src/
└── main.rs
Installing Azure Cosmos DB Dependencies
The Azure Cosmos DB Rust SDK is distributed as a Cargo crate.
Add the required dependencies:
cargo add azure_data_cosmos
cargo add azure_identity
cargo add serde --features derive
cargo add serde_json
cargo add tokio --features full
cargo add futures
The dependencies serve different purposes.
Crate | Purpose |
|---|
azure_data_cosmos
| Connects to Azure Cosmos DB and performs database operations |
azure_identity
| Provides Microsoft Entra ID authentication |
serde
| Serializes and deserializes Rust structures |
serde_json
| Works with JSON values |
tokio
| Provides the asynchronous runtime |
futures
| Provides stream utilities for processing query results |
For a reproducible production build, commit Cargo.lock and review dependency updates before upgrading SDK versions.
A simplified Cargo.toml dependency section looks like this:
[dependencies]
azure_data_cosmos = "1.0.0"
azure_identity = "1.0.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tokio = { version = "1", features = ["full"] }
futures = "0.3"
The examples in this article use the GA SDK 1.0 API. Keep the Cosmos DB and Azure Identity crate versions aligned with the compatible stable releases available in your environment.
Configuring Azure Cosmos DB
Before writing Rust code, create a Cosmos DB for NoSQL account or select an existing account.
In the Azure portal:
Open Azure Cosmos DB.
Create a new Azure Cosmos DB for NoSQL account or select an existing account.
Create a database named OrdersDatabase.
Create a container named Orders.
Set /tenantId as the partition key.
Configure the required throughput.
The container will store documents such as:
{
"id": "order-1001",
"tenantId": "tenant-25",
"customerId": "customer-101",
"status": "Pending",
"totalAmount": 1250.50
}
The tenantId property is the partition key. Every operation that needs to identify an individual item must provide the corresponding partition key value.
For production applications, select a partition key based on actual query patterns, data distribution, and expected growth.
Authenticating With Microsoft Entra ID
Authentication is one of the most important parts of a production database integration.
The Azure Cosmos DB Rust SDK supports Microsoft Entra ID authentication through the Azure Identity library.
The recommended starting point is DefaultAzureCredential.
This credential can use supported authentication sources depending on the execution environment.
For local development, it can use an authenticated Azure CLI session. In supported Azure hosting environments, it can use an available managed identity.
First, sign in using Azure CLI:
az login
Set the subscription if your account has access to multiple subscriptions:
az account set --subscription "My Azure Subscription"
Next, assign the appropriate Cosmos DB data-plane role to the identity used by your application.
For read and write access to NoSQL data, the built-in Cosmos DB data contributor role is commonly used. Assign it at the narrowest practical scope, such as the database or account.
The application identity must have the required data-plane permissions. Being able to sign in to Azure does not automatically grant permission to read or modify Cosmos DB documents.
Creating a Cosmos DB Client in Rust
The CosmosClient type is the main entry point for communicating with Azure Cosmos DB.
The following example creates a client using Microsoft Entra ID authentication.
use azure_data_cosmos::CosmosClient;
use azure_identity::DefaultAzureCredential;
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let credential = DefaultAzureCredential::new()?;
let client = CosmosClient::new(
"myCosmosAccount",
credential,
None
)?;
println!("Cosmos DB client initialized successfully");
Ok(())
}
Replace myCosmosAccount with the actual Cosmos DB account name.
The DefaultAzureCredential instance handles authentication. The client can then be used to access databases and containers.
The final argument is an optional client configuration. Passing None uses the SDK's default configuration.
In production, create the client during application startup and reuse it instead of creating a new client for every request.
Accessing a Database and Container
After creating the client, retrieve the database and container clients.
use azure_data_cosmos::CosmosClient;
use azure_identity::DefaultAzureCredential;
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let credential = DefaultAzureCredential::new()?;
let client = CosmosClient::new(
"myCosmosAccount",
credential,
None
)?;
let database = client.database_client("OrdersDatabase");
let container = database.container_client("Orders");
println!("Database and container clients created");
Ok(())
}
The SDK provides different client types for different resource levels.
Client | Responsibility |
|---|
CosmosClient
| Represents the Cosmos DB account |
DatabaseClient
| Represents a database |
ContainerClient
| Performs container and item operations |
Creating these client handles does not necessarily create the database or container. The corresponding resources must already exist unless you explicitly call supported resource-management operations.
Creating a Rust Data Model
Rust applications commonly use structures to represent database documents.
The Serde library provides serialization and deserialization support.
Create an order structure:
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, Clone)]
struct Order {
id: String,
tenant_id: String,
customer_id: String,
status: String,
total_amount: f64,
}
The Rust field tenant_id uses snake_case naming, while the Cosmos DB document uses tenantId.
Add a Serde rename attribute to match the database property:
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, Clone)]
struct Order {
id: String,
#[serde(rename = "tenantId")]
tenant_id: String,
#[serde(rename = "customerId")]
customer_id: String,
status: String,
#[serde(rename = "totalAmount")]
total_amount: f64,
}
This keeps Rust naming conventions while maintaining the JSON structure expected by the database.
The Serialize trait allows Rust objects to be converted into JSON-compatible data. The Deserialize trait allows query results and database responses to be converted back into Rust structures.
Inserting Documents Into Azure Cosmos DB
The SDK provides methods such as create_item and upsert_item for inserting documents.
Use create_item when a new document should be created and an existing document with the same ID and partition key should not be replaced.
The following example creates an order:
use azure_data_cosmos::{CosmosClient, PartitionKey};
use azure_identity::DefaultAzureCredential;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, Clone)]
struct Order {
id: String,
#[serde(rename = "tenantId")]
tenant_id: String,
#[serde(rename = "customerId")]
customer_id: String,
status: String,
#[serde(rename = "totalAmount")]
total_amount: f64,
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let credential = DefaultAzureCredential::new()?;
let client = CosmosClient::new(
"myCosmosAccount",
credential,
None
)?;
let database = client.database_client("OrdersDatabase");
let container = database.container_client("Orders");
let order = Order {
id: "order-1001".to_string(),
tenant_id: "tenant-25".to_string(),
customer_id: "customer-101".to_string(),
status: "Pending".to_string(),
total_amount: 1250.50,
};
let partition_key = PartitionKey::from(
order.tenant_id.clone()
);
let response = container
.create_item(partition_key, order, None)
.await?;
println!("Order created successfully");
Ok(())
}
The PartitionKey::from method creates the partition key value from the document's tenant_id property.
The partition key must match the container configuration. If the container uses /tenantId, the application must provide the corresponding tenant ID.
The example uses create_item because the operation is intended to create a new order. If the application needs create-or-replace behavior, use upsert_item instead.
Reading Documents From Azure Cosmos DB
A point read is one of the most efficient ways to retrieve a known document.
It requires two values:
For example, the application can retrieve an order using its ID and tenant ID.
let item_id = "order-1001";
let partition_key = "tenant-25";
let response = container
.read_item(partition_key, item_id, None)
.await?;
let order: Order = response.into_json_body().await?;
println!("Order details: {:#?}", order);
The read_item method performs a point read instead of executing a query across the container.
This is particularly useful for API endpoints that retrieve individual records.
For example, an order service can accept an order ID and tenant ID, then perform a direct lookup.
If the application does not know the partition key, it may need to execute a query instead.
Querying Documents Using Rust
Azure Cosmos DB for NoSQL supports a SQL-like query language.
The Rust SDK provides query_items for retrieving matching documents.
For example, the following query retrieves orders belonging to a particular tenant:
SELECT * FROM c
WHERE c.tenantId = @tenantId
The SDK supports parameterized queries, which are preferable to building query strings through manual concatenation.
The following example executes the query and processes the returned pages:
use azure_data_cosmos::{PartitionKey, Query};
use futures::StreamExt;
let tenant_id = "tenant-25";
let query = Query::from(
"SELECT * FROM c WHERE c.tenantId = @tenantId"
)
.with_parameter("@tenantId", tenant_id)?;
let partition_key = PartitionKey::from(tenant_id);
let mut pager = container.query_items::<Order>(
query,
partition_key,
None
)?;
while let Some(page_response) = pager.next().await {
let page = page_response?.into_body().await?;
for order in page.items {
println!("{:#?}", order);
}
}
The query uses a parameter instead of inserting the tenant ID directly into the SQL string.
The partition key argument also helps route the query to the relevant logical partition.
The pager returns results in pages. Processing pages asynchronously prevents the application from having to load every matching document into memory at once.
For queries that must search across multiple partitions, use the cross-partition query support available in the GA SDK and configure the appropriate query scope. Do not assume that passing one partition key will search every partition.
Updating and Replacing Documents
Applications frequently need to update an existing document.
The SDK provides operations such as replace_item and upsert_item.
A replace operation updates an existing document using its ID and partition key.
For example, an order status can be changed from Pending to Shipped:
let mut order = Order {
id: "order-1001".to_string(),
tenant_id: "tenant-25".to_string(),
customer_id: "customer-101".to_string(),
status: "Shipped".to_string(),
total_amount: 1250.50,
};
let partition_key = PartitionKey::from(
order.tenant_id.clone()
);
container
.replace_item(
partition_key,
order.id.clone(),
order,
None
)
.await?;
A replace operation sends the complete document representation. Fields that are not included may be removed from the stored document.
For applications that update only a few properties, consider using a supported patch operation instead.
Use ETag-based optimistic concurrency when multiple services may update the same document. This helps prevent one request from silently overwriting another request's changes.
Handling Errors and Retries
Database operations can fail for different reasons.
Common causes include:
Authentication failures.
Missing database or container resources.
Invalid partition key values.
Network interruptions.
Request throttling.
Conflicting document updates.
Temporary regional availability problems.
Rust's Result type provides a straightforward way to handle errors.
For a simple application, the ? operator propagates errors to the calling function:
async fn process_order() -> Result<(), Box<dyn std::error::Error>> {
// Cosmos DB operations
Ok(())
}
In a production service, use a structured error-handling approach.
Classify errors into categories such as authentication, validation, throttling, transient network failure, and permanent application errors.
The GA Rust SDK automatically retries operations when a retry is considered safe. This reduces the amount of custom retry logic required by applications.
However, developers should still understand the operation's retry behavior.
For example, stored procedure execution and certain patch operations cannot be safely retried automatically. A failed response does not always prove that the server did not process the request.
For operations that must be safe when repeated, design application-level idempotency using stable operation identifiers and appropriate conditional updates.
Avoid adding another aggressive retry loop around the SDK. Multiple retry layers can increase latency, create unnecessary traffic, and make throttling worse.
Using Rust With the Azure Cosmos DB Emulator
The Azure Cosmos DB Emulator provides a local development environment for testing Cosmos DB applications.
It is useful when developers want to:
Test document serialization.
Validate partition key values.
Execute NoSQL queries.
Test create, read, update, and delete operations.
Develop without using a production database account.
The emulator can run locally through its supported Windows installation or container-based environment.
Before connecting a Rust application, start the emulator and create the required database and container.
The emulator has its own endpoint and authentication configuration. Follow the current Rust SDK and emulator documentation for the supported connection method.
Do not assume that production Microsoft Entra ID authentication works identically against a local emulator.
Also, emulator performance does not represent production Cosmos DB performance. Use an Azure test account to evaluate real throughput, partition distribution, regional behavior, and latency.
Performance Optimization for Production Applications
A working connection is only the first step. Production applications need to consider client reuse, partitioning, concurrency, query efficiency, and network behavior.
Reuse the Cosmos DB Client
Create the Cosmos DB client once during application initialization and share it across requests.
Do not create a new client for every database operation.
Client reuse helps avoid unnecessary connection and initialization overhead.
Design Partition Keys Carefully
Choose a partition key that matches the application's common access patterns.
A poor partition key can create hot partitions and increase request latency.
For a multi-tenant application, a tenant identifier may be a good starting point, but large tenants and uneven traffic should also be considered.
Use Point Reads When Possible
If the application knows both the document ID and partition key, use read_item.
A point read is generally more efficient than a query that searches for the same document.
Process Query Results in Pages
Avoid collecting large query results into a single in-memory collection.
Use the SDK's paging interface to process results incrementally.
This helps keep memory usage predictable.
Control Application Concurrency
Rust supports concurrent asynchronous operations through Tokio.
However, sending too many concurrent requests can increase RU consumption and cause throttling.
Use bounded concurrency, such as a semaphore, when processing large batches of database operations.
Monitor RU Consumption and Latency
Monitor request unit consumption, response latency, HTTP status codes, and throttling behavior.
A query can be functionally correct but still be expensive.
Review query patterns and indexing policies when RU consumption is higher than expected.
Test Regional Failover
The GA SDK includes per-partition availability features, but applications should still test their recovery expectations.
Validate behavior under network interruptions, regional issues, and high request volume.
Do not assume that automatic failover removes the need for application-level timeouts and operational monitoring.
Common Mistakes to Avoid
Using Account Keys in Source Code
Hardcoding Cosmos DB account keys creates a security risk.
Use Microsoft Entra ID authentication and managed identities where supported. If account keys are required for a particular environment, store them in a secure secret-management service.
Ignoring the Partition Key
A document can contain the correct ID but still fail to be retrieved if the application provides an incorrect partition key.
Keep the partition key available wherever the application performs point reads, updates, or deletes.
Creating a New Client for Every Request
Repeated client creation adds unnecessary overhead.
Reuse the client across the application's lifetime.
Treating Upsert and Create as the Same Operation
create_item creates a new item and fails when an item with the same ID and partition key already exists.
upsert_item creates the item if it does not exist or replaces it if it does.
Choose the operation based on the application's expected behavior.
Ignoring Query Paging
Large queries can return multiple pages.
Always process the pager until all required results have been consumed.
Adding Unnecessary Retry Logic
The SDK already retries operations when it is safe to do so.
Adding multiple retry layers can increase traffic and make recovery slower.
Understand the SDK's retry behavior before implementing additional retries.
Assuming Every Cosmos DB API Is Supported
The native Rust SDK discussed in this article targets Azure Cosmos DB for NoSQL.
Do not assume that the same crate supports the MongoDB, Cassandra, Gremlin, or Table APIs. Those APIs require their respective compatible drivers or tools.
Advantages and Disadvantages of Using Rust With Azure Cosmos DB
Advantages
Native integration between Rust applications and Azure Cosmos DB for NoSQL.
Memory-safe application development.
Efficient asynchronous operations.
Gateway v2 enabled by default.
Binary serialization support.
Automatic retries for operations that are safe to retry.
Per-partition availability and circuit breaker capabilities.
Support for cross-partition queries in the GA release.
Microsoft Entra ID authentication through Azure Identity.
Suitable for high-performance services and distributed applications.
Disadvantages
The SDK targets the NoSQL API rather than every Cosmos DB API.
Developers need familiarity with Rust ownership, borrowing, and asynchronous programming.
Some database operations require careful retry and idempotency handling.
Production applications still need monitoring and workload-specific performance testing.
Existing applications written in other languages may require additional migration and testing work.
Some Azure management and data-plane capabilities may differ from those available in more mature SDK ecosystems.
Conclusion
Connecting Rust applications to Azure Cosmos DB provides developers with a combination of memory safety, performance, asynchronous programming, and managed NoSQL database capabilities.
The official azure_data_cosmos SDK provides the main building blocks for authentication, database access, document creation, point reads, updates, and queries. Its general availability release in November 2026 introduced important production-focused improvements, including Gateway v2, binary serialization, automatic safe retries, and per-partition availability features.
For production applications, start with Microsoft Entra ID authentication, reuse the Cosmos DB client, select a suitable partition key, and process query results asynchronously. Monitor request units and latency, and design application-level error handling for operations that cannot be safely retried.
Rust and Azure Cosmos DB can work well together for high-performance APIs, distributed services, and data-intensive applications when the database design and operational requirements are considered from the beginning.
Join the conversation! Your thoughts help the community grow.