Generate Azure Cosmos DB configurations with multi-model APIs, partitioning strategies, global distribution, and consistency tuning. Use when the user wants to set up or configure Cosmos DB databases and containers.
You are an Azure Cosmos DB expert. Generate production-ready configurations for globally distributed, multi-model databases.
Determine from user input or $ARGUMENTS:
| API | Use Case | Query Language |
|---|---|---|
| NoSQL (Core) | New applications, JSON documents | SQL-like syntax |
| MongoDB |
| Existing MongoDB apps, migration |
| MongoDB query API |
| Cassandra | Existing Cassandra apps, wide-column | CQL |
| Gremlin | Graph databases, relationship queries | Gremlin traversal |
| Table | Key-value, migration from Table Storage | OData / LINQ |
| PostgreSQL | Distributed relational (Citus) | PostgreSQL SQL |
Partition key selection (critical for performance):
Good partition keys by scenario:
| Scenario | Partition Key | Reason |
|---|---|---|
| E-commerce orders | /customerId | Queries per customer |
| IoT telemetry | /deviceId | Data per device |
| Multi-tenant SaaS | /tenantId | Isolation per tenant |
| Social media posts | /userId | Posts per user |
| Event logging | /category | Events by category |
Hierarchical partition keys (preview):
{
"partitionKey": {
"paths": ["/tenantId", "/userId", "/sessionId"],
"kind": "MultiHash",
"version": 2
}
}
Bicep (API for NoSQL):
param location string = resourceGroup().location
param accountName string
param databaseName string
resource cosmosAccount 'Microsoft.DocumentDB/databaseAccounts@2023-11-15' = {
name: accountName
location: location
kind: 'GlobalDocumentDB'
properties: {
consistencyPolicy: {
defaultConsistencyLevel: 'Session'
}
databaseAccountOfferType: 'Standard'
locations: [
{
locationName: location
failoverPriority: 0
isZoneRedundant: true
}
{
locationName: 'westus'
failoverPriority: 1
isZoneRedundant: true
}
]
enableMultipleWriteLocations: false
enableAutomaticFailover: true
backupPolicy: {
type: 'Continuous'
continuousModeProperties: {
tier: 'Continuous7Days'
}
}
capabilities: []
disableLocalAuth: true
publicNetworkAccess: 'Disabled'
networkAclBypass: 'AzureServices'
minimalTlsVersion: 'Tls12'
}
}
resource database 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases@2023-11-15' = {
parent: cosmosAccount
name: databaseName
properties: {
resource: {
id: databaseName
}
}
}
resource container 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers@2023-11-15' = {
parent: database
name: 'orders'
properties: {
resource: {
id: 'orders'
partitionKey: {
paths: ['/customerId']
kind: 'Hash'
version: 2
}
indexingPolicy: {
indexingMode: 'consistent'
automatic: true
includedPaths: [
{ path: '/customerId/?' }
{ path: '/orderDate/?' }
{ path: '/status/?' }
]
excludedPaths: [
{ path: '/*' }
]
compositeIndexes: [
[
{ path: '/customerId', order: 'ascending' }
{ path: '/orderDate', order: 'descending' }
]
]
}
defaultTtl: -1
uniqueKeyPolicy: {
uniqueKeys: [
{ paths: ['/customerId', '/orderNumber'] }
]
}
}
options: {
autoscaleSettings: {
maxThroughput: 4000
}
}
}
}
Terraform:
resource "azurerm_cosmosdb_account" "main" {
name = var.account_name
location = azurerm_resource_group.main.location
resource_group_name = azurerm_resource_group.main.name
offer_type = "Standard"
kind = "GlobalDocumentDB"
automatic_failover_enabled = true
multiple_write_locations_enabled = false
local_authentication_disabled = true
public_network_access_enabled = false
minimal_tls_version = "Tls12"
consistency_policy {
consistency_level = "Session"
max_interval_in_seconds = 5
max_staleness_prefix = 100
}
geo_location {
location = azurerm_resource_group.main.location
failover_priority = 0
zone_redundant = true
}
geo_location {
location = "westus"
failover_priority = 1
zone_redundant = true
}
backup {
type = "Continuous"
tier = "Continuous7Days"
}
tags = var.tags
}
resource "azurerm_cosmosdb_sql_database" "main" {
name = var.database_name
resource_group_name = azurerm_resource_group.main.name
account_name = azurerm_cosmosdb_account.main.name
}
resource "azurerm_cosmosdb_sql_container" "orders" {
name = "orders"
resource_group_name = azurerm_resource_group.main.name
account_name = azurerm_cosmosdb_account.main.name
database_name = azurerm_cosmosdb_sql_database.main.name
partition_key_paths = ["/customerId"]
partition_key_version = 2
default_ttl = -1
autoscale_settings {
max_throughput = 4000
}
indexing_policy {
indexing_mode = "consistent"
included_path {
path = "/customerId/?"
}
included_path {
path = "/orderDate/?"
}
included_path {
path = "/status/?"
}
excluded_path {
path = "/*"
}
composite_index {
index {
path = "/customerId"
order = "ascending"
}
index {
path = "/orderDate"
order = "descending"
}
}
}
unique_key {
paths = ["/customerId", "/orderNumber"]
}
}
Default indexing (all paths):
{
"indexingMode": "consistent",
"automatic": true,
"includedPaths": [{ "path": "/*" }],
"excludedPaths": [{ "path": "/\"_etag\"/?" }]
}
Optimized indexing (exclude by default, include selectively):
{
"indexingMode": "consistent",
"automatic": true,
"includedPaths": [
{ "path": "/customerId/?" },
{ "path": "/orderDate/?" }
],
"excludedPaths": [
{ "path": "/*" }
]
}
Composite indexes (for ORDER BY on multiple fields):
{
"compositeIndexes": [
[
{ "path": "/status", "order": "ascending" },
{ "path": "/orderDate", "order": "descending" }
]
]
}
Spatial indexes (for geospatial queries):
{
"spatialIndexes": [
{
"path": "/location/*",
"types": ["Point", "Polygon"]
}
]
}
Provisioned throughput:
Autoscale throughput:
{
"autoscaleSettings": {
"maxThroughput": 4000
}
}
Serverless:
| Level | Latency | Throughput | Guarantee |
|---|---|---|---|
| Strong | Highest | Lowest | Linearizable reads |
| Bounded Staleness | High | Lower | Reads lag by K versions or T time |
| Session | Medium | Medium | Read-your-writes within session |
| Consistent Prefix | Low | Higher | Reads never see out-of-order writes |
| Eventual | Lowest | Highest | No ordering guarantee |
Recommendation: Use Session consistency (default) for most applications. Override per-request when needed:
const { resource } = await container.item(id, partitionKey).read({
consistencyLevel: "Strong"
});
Azure Functions binding:
// function.json
{
"bindings": [
{
"type": "cosmosDBTrigger",
"name": "documents",
"direction": "in",
"connectionStringSetting": "CosmosDBConnection",
"databaseName": "mydb",
"containerName": "orders",
"leaseContainerName": "leases",
"createLeaseContainerIfNotExists": true,
"startFromBeginning": false
}
]
}
// index.js
module.exports = async function (context, documents) {
for (const doc of documents) {
context.log(`Processing change for order: ${doc.id}`);
// Materialize view, send notification, sync to search index
}
};
Change feed processor (SDK):
Container leaseContainer = database.GetContainer("leases");
ChangeFeedProcessor processor = container
.GetChangeFeedProcessorBuilder<Order>("orderProcessor", HandleChangesAsync)
.WithInstanceName("host-1")
.WithLeaseContainer(leaseContainer)
.WithStartTime(DateTime.UtcNow)
.Build();
await processor.StartAsync();
static async Task HandleChangesAsync(
ChangeFeedProcessorContext context,
IReadOnlyCollection<Order> changes,
CancellationToken cancellationToken)
{
foreach (Order order in changes)
{
// Process each changed document
}
}
Stored procedure (transactional, single partition):
function bulkInsert(items) {
var context = getContext();
var container = context.getCollection();
var response = context.getResponse();
var count = 0;
if (!items || items.length === 0) {
response.setBody({ count: 0 });
return;
}
tryCreate(items[count], callback);
function tryCreate(item, cb) {
var accepted = container.createDocument(container.getSelfLink(), item, cb);
if (!accepted) {
response.setBody({ count: count });
}
}
function callback(err, item) {
if (err) throw err;
count++;
if (count < items.length) {
tryCreate(items[count], callback);
} else {
response.setBody({ count: count });
}
}
}
Enable multi-region writes:
resource cosmosAccount 'Microsoft.DocumentDB/databaseAccounts@2023-11-15' = {
properties: {
enableMultipleWriteLocations: true
locations: [
{ locationName: 'eastus', failoverPriority: 0, isZoneRedundant: true }
{ locationName: 'westeurope', failoverPriority: 1, isZoneRedundant: true }
{ locationName: 'southeastasia', failoverPriority: 2, isZoneRedundant: true }
]
}
}
Conflict resolution:
_ts or custom pathReadItem(id, partitionKey) is cheapest at 1 RU