Understanding Cosmos DB Request Rate Too Large (429) Errors
The HTTP 429 “Request rate too large” error in Azure Cosmos DB means your operations have consumed more Request Units per second (RU/s) than provisioned. Cosmos DB throttles excess requests to protect the service. While 1-5% throttling is normal and expected, sustained 429 errors indicate you need to optimize queries, adjust throughput, or redesign your partition strategy.
Understanding the Root Cause
Resolving Azure Cosmos DB Request Rate Too Large (429) requires more than applying a quick fix to suppress error messages. The underlying cause typically involves a mismatch between your application’s expectations and the service’s actual behavior or limits. Azure services enforce quotas, rate limits, and configuration constraints that are documented but often overlooked during initial development when traffic volumes are low and edge cases are rare.
When this issue appears in production, it usually indicates that the system has crossed a threshold that was not accounted for during capacity planning. This could be a throughput limit, a connection pool ceiling, a timeout boundary, or a resource quota. The error messages from Azure services are designed to be actionable, but they sometimes point to symptoms rather than the root cause. For example, a timeout error might actually be caused by a DNS resolution delay, a TLS handshake failure, or a downstream dependency that is itself throttled.
The resolution strategies in this guide are organized from least invasive to most invasive. Start with configuration adjustments that do not require code changes or redeployment. If those are insufficient, proceed to application-level changes such as retry policies, connection management, and request patterns. Only escalate to architectural changes like partitioning, sharding, or service tier upgrades when the simpler approaches cannot meet your requirements.
Impact Assessment
Before implementing any resolution, assess the blast radius of the current issue. Determine how many users, transactions, or dependent services are affected. Check whether the issue is intermittent or persistent, as this distinction changes the urgency and approach. Intermittent issues often indicate resource contention or throttling near a limit, while persistent failures typically point to misconfiguration or a hard limit being exceeded.
Review your Service Level Objectives (SLOs) to understand the business impact. If your composite SLA depends on this service’s availability, calculate the actual downtime or degradation window. This information is critical for incident prioritization and for justifying the engineering investment required for a permanent fix versus a temporary workaround.
Consider the cascading effects on downstream services and consumers. When Azure Cosmos DB Request Rate Too Large (429) degrades, every service that depends on it may also experience failures or increased latency. Map out your service dependency graph to understand the full impact scope and prioritize the resolution accordingly.
How Request Units Work
| Operation | Approximate RU Cost |
|---|---|
| Point read (1 KB document by ID + partition key) | 1 RU |
| Write (1 KB document) | ~5.5 RU |
| Query (simple, returns 1 document) | ~3 RU |
| Cross-partition query | Higher — depends on partitions scanned |
| Stored procedure execution | Varies by complexity |
Diagnosing 429 Errors
-- KQL: Find throttled requests in diagnostic logs
CDBDataPlaneRequests
| where TimeGenerated > ago(24h)
| where StatusCode == 429
| summarize
ThrottledCount = count(),
TotalRUConsumed = sum(RequestCharge)
by DatabaseName, CollectionName, OperationName, bin(TimeGenerated, 5m)
| order by ThrottledCount desc
-- Find hot partitions
CDBPartitionKeyRUConsumption
| where TimeGenerated > ago(24h)
| where CollectionName == "MyContainer"
| summarize TotalRU = sum(RequestCharge) by PartitionKey, bin(TimeGenerated, 1m)
| order by TotalRU desc
| take 20
# Check current throughput settings
az cosmosdb sql container throughput show \
--account-name myAccount \
--database-name myDB \
--name myContainer \
--resource-group myRG
# Check consumed RU/s via metrics
az monitor metrics list \
--resource $(az cosmosdb show --name myAccount --resource-group myRG --query id -o tsv) \
--metric "TotalRequestUnits" "TotalRequests" \
--filter "StatusCode eq '429'" \
--interval PT5M
Fix 1: Scale Up Throughput
# Increase manual throughput
az cosmosdb sql container throughput update \
--account-name myAccount \
--database-name myDB \
--name myContainer \
--resource-group myRG \
--throughput 10000
# Switch to autoscale (scales between 10% and 100% of max)
az cosmosdb sql container throughput migrate \
--account-name myAccount \
--database-name myDB \
--name myContainer \
--resource-group myRG \
--throughput-type autoscale
# Set autoscale max throughput
az cosmosdb sql container throughput update \
--account-name myAccount \
--database-name myDB \
--name myContainer \
--resource-group myRG \
--max-throughput 20000
Fix 2: Optimize Queries
// C#: Always provide partition key for point reads
var response = await container.ReadItemAsync<MyDocument>(
id: "doc-123",
partitionKey: new PartitionKey("partition-value")
);
Console.WriteLine($"RU charge: {response.RequestCharge}");
// AVOID: Cross-partition queries
var query = container.GetItemQueryIterator<MyDocument>(
"SELECT * FROM c WHERE c.status = 'active'"
// No partition key = cross-partition scan!
);
// BETTER: Include partition key in query
var query = container.GetItemQueryIterator<MyDocument>(
new QueryDefinition("SELECT * FROM c WHERE c.customerId = @id AND c.status = 'active'")
.WithParameter("@id", customerId),
requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey(customerId) }
);
Fix 3: Optimize Indexing Policy
{
"indexingMode": "consistent",
"automatic": true,
"includedPaths": [
{ "path": "/customerId/?" },
{ "path": "/status/?" },
{ "path": "/createdDate/?" }
],
"excludedPaths": [
{ "path": "/largePayload/*" },
{ "path": "/metadata/*" },
{ "path": "/*" }
],
"compositeIndexes": [
[
{ "path": "/status", "order": "ascending" },
{ "path": "/createdDate", "order": "descending" }
]
]
}
# Update indexing policy
az cosmosdb sql container update \
--account-name myAccount \
--database-name myDB \
--name myContainer \
--resource-group myRG \
--idx @indexing-policy.json
Resilience Patterns for Long-Term Prevention
Once you resolve the immediate issue, invest in resilience patterns that prevent recurrence. Azure’s cloud-native services provide building blocks for resilient architectures, but you must deliberately design your application to use them effectively.
Retry with Exponential Backoff: Transient failures are expected in distributed systems. Your application should automatically retry failed operations with increasing delays between attempts. The Azure SDK client libraries implement retry policies by default, but you may need to tune the parameters for your specific workload. Set maximum retry counts to prevent infinite retry loops, and implement jitter (randomized delay) to prevent thundering herd problems when many clients retry simultaneously.
Circuit Breaker Pattern: When a dependency consistently fails, continuing to send requests increases load on an already stressed service and delays recovery. Implement circuit breakers that stop forwarding requests after a configurable failure threshold, wait for a cooldown period, then tentatively send a single test request. If the test succeeds, the circuit closes and normal traffic resumes. If it fails, the circuit remains open. Azure API Management provides a built-in circuit breaker policy for backend services.
Bulkhead Isolation: Separate critical and non-critical workloads into different resource instances, connection pools, or service tiers. If a batch processing job triggers throttling or resource exhaustion, it should not impact the real-time API serving interactive users. Use separate Azure resource instances for workloads with different priority levels and different failure tolerance thresholds.
Queue-Based Load Leveling: When the incoming request rate exceeds what the backend can handle, use a message queue (Azure Service Bus or Azure Queue Storage) to absorb the burst. Workers process messages from the queue at the backend’s sustainable rate. This pattern is particularly effective for resolving throughput-related issues because it decouples the rate at which requests arrive from the rate at which they are processed.
Cache-Aside Pattern: For read-heavy workloads, cache frequently accessed data using Azure Cache for Redis to reduce the load on the primary data store. This is especially effective when the resolution involves reducing request rates to a service with strict throughput limits. Even a short cache TTL of 30 to 60 seconds can dramatically reduce the number of requests that reach the backend during traffic spikes.
Fix 4: Choose Better Partition Key
# Good partition keys:
# - /customerId (high cardinality, even distribution)
# - /tenantId (multi-tenant apps)
# - /deviceId (IoT scenarios)
# Bad partition keys:
# - /status (low cardinality — few distinct values)
# - /country (skewed — most users from few countries)
# - /createdDate (sequential — all writes hit latest partition)
# Synthetic partition keys for mixed workloads:
# Combine multiple fields: /tenantId + /category
// Create documents with synthetic partition key
var document = new {
id = Guid.NewGuid().ToString(),
customerId = "cust-123",
category = "electronics",
partitionKey = $"cust-123-electronics", // Synthetic: customerId + category
data = "..."
};
Fix 5: Implement Retry Logic
// C#: CosmosClient has built-in retry for 429
var clientOptions = new CosmosClientOptions
{
MaxRetryAttemptsOnRateLimitedRequests = 9, // Default
MaxRetryWaitTimeOnRateLimitedRequests = TimeSpan.FromSeconds(30), // Default
// Connection settings
ConnectionMode = ConnectionMode.Direct, // Lower latency than Gateway
MaxRequestsPerTcpConnection = 10
};
var client = new CosmosClient(connectionString, clientOptions);
// JavaScript: Configure retry options
const { CosmosClient } = require('@azure/cosmos');
const client = new CosmosClient({
endpoint: 'https://myaccount.documents.azure.com:443/',
key: 'mykey',
connectionPolicy: {
retryOptions: {
maxRetryAttemptCount: 9,
maxWaitTimeInSeconds: 30
}
}
});
Fix 6: Use Bulk Operations
// C#: Enable bulk execution for batch writes
var clientOptions = new CosmosClientOptions
{
AllowBulkExecution = true // Batches requests for efficiency
};
var client = new CosmosClient(connectionString, clientOptions);
var container = client.GetContainer("myDB", "myContainer");
// Bulk insert with parallel tasks
var tasks = documents.Select(doc =>
container.CreateItemAsync(doc, new PartitionKey(doc.PartitionKey))
);
var responses = await Task.WhenAll(tasks);
var totalRU = responses.Sum(r => r.RequestCharge);
Console.WriteLine($"Total RU: {totalRU}");
Understanding Azure Service Limits and Quotas
Every Azure service operates within defined limits and quotas that govern the maximum throughput, connection count, request rate, and resource capacity available to your subscription. These limits exist to protect the multi-tenant platform from noisy-neighbor effects and to ensure fair resource allocation across all customers. When your workload approaches or exceeds these limits, the service enforces them through throttling (HTTP 429 responses), request rejection, or degraded performance.
Azure service limits fall into two categories: soft limits that can be increased through a support request, and hard limits that represent fundamental architectural constraints of the service. Before designing your architecture, review the published limits for every Azure service in your solution. Plan for the worst case: what happens when you hit the limit during a traffic spike? Your application should handle throttled responses gracefully rather than failing catastrophically.
Use Azure Monitor to track your current utilization as a percentage of your quota limits. Create dashboards that show utilization trends over time and set alerts at 70 percent and 90 percent of your limits. When you approach a soft limit, submit a quota increase request proactively rather than waiting for a production incident. Microsoft typically processes quota increase requests within a few business days, but during high-demand periods it may take longer.
For services that support multiple tiers or SKUs, evaluate whether upgrading to a higher tier provides the headroom you need. Compare the cost of the upgrade against the cost of engineering effort to work around the current limits. Sometimes, paying for a higher service tier is more cost-effective than building complex application-level sharding, caching, or load-balancing logic to stay within the lower tier’s constraints.
Disaster Recovery and Business Continuity
When resolving service issues, consider the broader disaster recovery and business continuity implications. If Azure Cosmos DB Request Rate Too Large (429) is a critical dependency, your Recovery Time Objective (RTO) and Recovery Point Objective (RPO) determine how quickly you need to restore service and how much data loss is acceptable.
Implement a multi-region deployment strategy for business-critical services. Azure paired regions provide automatic data replication and prioritized recovery during regional outages. Configure your application to failover to the secondary region when the primary region is unavailable. Test your failover procedures regularly to ensure they work correctly and meet your RTO targets.
Maintain infrastructure-as-code templates for all your Azure resources so you can redeploy your entire environment in a new region if necessary. Store these templates in a geographically redundant source code repository. Document the manual steps required to complete a region failover, including DNS changes, connection string updates, and data synchronization verification.
Metadata Request Throttling
// Metadata requests (create/list/update containers) have a separate
// system-reserved RU limit of ~20 RU/s
// WRONG: Creating client per request
foreach (var item in items) {
var client = new CosmosClient(connStr); // Each creates metadata requests!
var container = client.GetContainer("myDB", "myContainer");
await container.CreateItemAsync(item);
}
// CORRECT: Singleton CosmosClient
private static readonly CosmosClient _client = new CosmosClient(connStr);
private static readonly Container _container = _client.GetContainer("myDB", "myContainer");
Monitoring and Alerting
# Create alert for 429 rate
az monitor metrics alert create \
--name cosmos-throttle-alert \
--resource-group myRG \
--resource $(az cosmosdb show --name myAccount --resource-group myRG --query id -o tsv) \
--condition "total TotalRequests > 100 where StatusCode includes 429" \
--window-size 5m \
--evaluation-frequency 5m
# Use the capacity planner
# https://cosmos.azure.com/capacitycalculator/
Capacity Planning and Forecasting
The most effective resolution is preventing the issue from recurring through proactive capacity planning. Establish a regular review cadence where you analyze growth trends in your service utilization metrics and project when you will approach limits.
Use Azure Monitor metrics to track the key capacity indicators for Azure Cosmos DB Request Rate Too Large (429) over time. Create a capacity planning workbook that shows current utilization as a percentage of your provisioned limits, the growth rate over the past 30, 60, and 90 days, and projected dates when you will reach 80 percent and 100 percent of capacity. Share this workbook with your engineering leadership to support proactive scaling decisions.
Factor in planned events that will drive usage spikes. Product launches, marketing campaigns, seasonal traffic patterns, and batch processing schedules all create predictable demand increases that should be accounted for in your capacity plan. If your application serves a global audience, consider time-zone-based traffic distribution and scale accordingly.
Implement autoscaling where the service supports it. Azure autoscale rules can automatically adjust capacity based on real-time metrics. Configure scale-out rules that trigger before you reach limits (at 70 percent utilization) and scale-in rules that safely reduce capacity during low-traffic periods to optimize costs. Test your autoscale rules under load to verify that they respond quickly enough to protect against sudden traffic spikes.
Summary
Cosmos DB 429 errors are caused by exceeding provisioned RU/s, hot partitions concentrating load, inefficient queries consuming excessive RUs, or metadata throttling from non-singleton CosmosClient instances. Fix by enabling autoscale, optimizing queries with partition keys, tuning indexing policies to reduce write costs, choosing high-cardinality partition keys, and using bulk execution for batch operations. A 1-5% throttle rate is normal — only act when latency is impacted or the rate is higher.
For more details, refer to the official documentation: Azure Cosmos DB overview, Best practices for Azure Cosmos DB .NET SDK.