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
- Prefer point reads (
ReadDocumentAsync) over queries when fetching a single item. - Cache frequently accessed items at the client side to avoid repeated RU consumption.
- Batch write operations using
TransactionalBatchto reduce overhead.
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
- Select a high‑cardinality, evenly distributed partition key (e.g.,
tenantId,region). - Avoid hot partitions by ensuring write traffic is spread.
- Use synthetic keys when a single field isn’t sufficient.
Example Synthetic Key
{
"id": "order123",
"tenantId": "tenantA",
"orderDate": "2025-04-01",
"pk": "tenantA_2025-04"
}
Data Modeling Best Practices
- Denormalize where read performance outweighs storage cost.
- Group related entities in the same container when they share a partition key.
- Limit document size to 2 MB to keep latency low.
Embedding vs. Referencing
Embed small, frequently accessed child objects. Use id references for large collections to avoid oversized documents.
Query Design
Efficient Query Patterns
- Prefer equality filters on indexed properties.
- Avoid
SELECT *– project only required fields. - Leverage
OFFSET LIMITsparingly; use continuation tokens for pagination.
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
- Use Azure AD for role‑based access via
CosmosDB RBAC. - Enable
Network ACLsandPrivate Endpointsto restrict traffic. - Encrypt data at rest (default) and use client‑side encryption for highly sensitive fields.
Monitoring & Metrics
- Set alerts for RU consumption spikes, latency > 10 ms, and throttled requests.
- Use
Azure MonitorandLog Analyticsdashboards for real‑time insights. - Enable diagnostic logs for request‑level tracing.
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"