Running inefficient SQL queries against Cosmos DB can quickly consume your allocated throughput budget. Understanding index mechanics and query patterns allows you to write lean, low-cost queries.
Indexing Policy Customization
By default, Cosmos DB automatically indexes every path in every item. While convenient for prototyping, indexing unnecessary strings and arrays inflates write latency and storage costs. Excluding heavy fields significantly lowers operational costs.
{
"indexingMode": "consistent",
"automatic": true,
"includedPaths": [
{
"path": "/*"
}
],
"excludedPaths": [
{
"path": "/\"description\"/?"
},
{
"path": "/\"rawPayload\"/?"
}
]
}Key Optimization Rules
- Avoid Cross-Partition Queries: Always include the partition key in your
WHEREclause when possible to prevent queries from fanning out to every physical partition. - Project Specific Fields: Replace
SELECT *with targeted field projections (e.g.,SELECT c.id, c.status FROM c) to minimize serialization and bandwidth costs. - Use Composite Indexes: Create composite indexes for queries containing multiple
ORDER BYor filter clauses across different properties.
Why RU Economics Matter
Azure Cosmos DB bills you per Request Unit. A single inefficient query can burn through your monthly allowance in minutes. Understanding how RU consumption works is the first step toward keeping costs predictable.
The RU Breakdown
Every query consumes read RUs if it touches items, plus write RUs if it modifies them. The total depends on the logical data size processed, not the physical size on disk. Cosmos DB scans only the partition key range specified in your filter, so narrow filters save RU. Broad scans across partitions are expensive.
Practical Tuning Steps
Start with your most frequent queries. Check the metrics in Azure Portal or via the SDK to see average RU per operation. If a query consistently spikes, look for missing or misaligned indexes.
Index Strategy
Query Rewrites
Replace client-side filtering with server-side
WHEREclauses. Pull only the columns you need instead ofSELECT *. Use parameterized queries to benefit from plan caching and reduce RU overhead.Partitioning
Design your partition key so related data lands in the same logical partition. This keeps cross-partition queries out of your workload. If your key causes hotspots, redistribute data by using a hash suffix or a composite key.
Monitoring and Iterating
Set up alerts on RU consumption per second. Run the Azure Cosmos DB emulator locally to test changes without burning production RUs. Review your RU graph weekly; small regressions compound quickly.
There is no magic bullet. Tuning is iterative. Measure, change one variable, measure again, and keep what works.