Cosmos DB SQL API – Best Practices

On this page Throughput & RU Management Indexing Strategies Effective Partitioning Data Modeling Query Design Security & Access Monitoring & Metrics

Throughput & RU Management

Provisioned vs. Autoscale

Choose provisioned throughput for predictable workloads and autoscale for variable traffic patterns. Autoscale automatically scales RU/s between minRU and maxRU, reducing manual intervention.

RU Optimisation Tips

Sample RU Calculator

function estimateRU(readSizeKB, opsPerSec) {
    const baseRU = 1; // point read
    const sizeFactor = Math.ceil(readSizeKB / 1);
    return (baseRU + sizeFactor) * opsPerSec;
}

Indexing Strategies

Automatic vs. Manual

Cosmos DB indexes all properties by default. Disable indexing for large, write‑heavy containers where queries are minimal.

Composite Indexes

Use composite indexes to improve ORDER BY and FILTER performance on multiple properties.

{
  "indexingPolicy": {
    "automatic": true,
    "includedPaths": [{ "path": "/*" }],
    "excludedPaths": [{ "path": "/\"_etag\"/?" }],
    "compositeIndexes": [
      [{ "path": "/category", "order": "Ascending" },
       { "path": "/timestamp", "order": "Descending" }]
    ]
  }
}

Spatial Indexes

Enable SpatialIndex for geo‑queries on properties storing GeoJSON.

Effective Partitioning

Example Synthetic Key

{
  "id": "order123",
  "tenantId": "tenantA",
  "orderDate": "2025-04-01",
  "pk": "tenantA_2025-04"
}

Data Modeling Best Practices

Embedding vs. Referencing

Embed small, frequently accessed child objects. Use id references for large collections to avoid oversized documents.

Query Design

Efficient Query Patterns

Parameterized Queries (JS SDK)

const query = {
  query: "SELECT c.id, c.name FROM c WHERE c.category = @cat AND c.status = @status",
  parameters: [
    { name: "@cat", value: "electronics" },
    { name: "@status", value: "active" }
  ]
};
const { resources } = await container.items.query(query).fetchAll();

Security & Access Control

Monitoring & Metrics

Sample Alert Rule (Azure CLI)

az monitor metrics alert create \
  --name "HighRUAlert" \
  --resource-group MyRG \
  --scopes /subscriptions/xxxx/resourceGroups/MyRG/providers/Microsoft.DocumentDB/databaseAccounts/mycosmosdb \
  --condition "max TotalRequestUnits > 3000" \
  --description "Triggered when RU consumption exceeds 3000 per minute"