PollyCosmosDb 1.0.2
dotnet add package PollyCosmosDb --version 1.0.2
NuGet\Install-Package PollyCosmosDb -Version 1.0.2
<PackageReference Include="PollyCosmosDb" Version="1.0.2" />
<PackageVersion Include="PollyCosmosDb" Version="1.0.2" />
<PackageReference Include="PollyCosmosDb" />
paket add PollyCosmosDb --version 1.0.2
#r "nuget: PollyCosmosDb, 1.0.2"
#:package PollyCosmosDb@1.0.2
#addin nuget:?package=PollyCosmosDb&version=1.0.2
#tool nuget:?package=PollyCosmosDb&version=1.0.2
PollyCosmosDb
Polly v8 resilience for Azure Cosmos DB — retry, timeout, and circuit-breaker for Container operations, plus a built-in CosmosTransientErrors predicate covering rate limiting (429), timeouts (408), partition failovers (410), and service unavailability (503). Zero changes to your existing Cosmos code.
// Before
await container.CreateItemAsync(order, new PartitionKey(order.CustomerId));
// After — automatic retry + timeout on every operation
var resilient = container.WithPolly(pipeline =>
pipeline
.AddRetry(new RetryStrategyOptions
{
MaxRetryAttempts = 3,
ShouldHandle = CosmosTransientErrors.IsTransient, // built-in ✔
})
.AddTimeout(TimeSpan.FromSeconds(30)));
await resilient.CreateItemAsync(order, new PartitionKey(order.CustomerId));
Installation
dotnet add package PollyCosmosDb
Targets net6.0, net8.0, and net9.0.
Dependencies: Polly.Core 8.*, Microsoft.Azure.Cosmos 3.*, Microsoft.Extensions.DependencyInjection.Abstractions 8.*
CosmosTransientErrors — the key feature
Cosmos DB has its own built-in retry for throttling (429s), but it does not cover timeouts, partition failovers, or service unavailability. PollyCosmosDb ships CosmosTransientErrors.IsTransient so you don't have to look up which HttpStatusCode values are safe to retry.
new RetryStrategyOptions
{
MaxRetryAttempts = 3,
ShouldHandle = CosmosTransientErrors.IsTransient,
}
Covered status codes
| Code | Name | Description |
|---|---|---|
408 |
RequestTimeout | Request timed out at Cosmos |
410 |
Gone | Partition split or replica failover |
429 |
TooManyRequests | RU/s exhausted (rate limited) |
449 |
RetryWith | Cosmos-specific sub-status — retry immediately |
503 |
ServiceUnavailable | Cosmos temporarily unavailable |
Note: Cosmos DB already retries 429s internally. Adding Polly on top gives you control over how many times and how long to retry across all transient failure modes.
The raw set is also available for extension:
var myErrors = CosmosTransientErrors.StatusCodes.ToHashSet();
myErrors.Add(HttpStatusCode.InternalServerError); // retry 500s too
new RetryStrategyOptions
{
ShouldHandle = new PredicateBuilder()
.Handle<CosmosException>(ex => myErrors.Contains(ex.StatusCode))
}
Quick start
Inline pipeline
using PollyCosmosDb;
var resilient = container.WithPolly(pipeline =>
pipeline
.AddRetry(new RetryStrategyOptions
{
MaxRetryAttempts = 3,
Delay = TimeSpan.FromMilliseconds(200),
BackoffType = DelayBackoffType.Exponential,
UseJitter = true,
ShouldHandle = CosmosTransientErrors.IsTransient,
})
.AddTimeout(TimeSpan.FromSeconds(30)));
// CRUD
var created = await resilient.CreateItemAsync(order, new PartitionKey(order.Id));
var read = await resilient.ReadItemAsync<Order>(id, new PartitionKey(id));
var upserted = await resilient.UpsertItemAsync(order, new PartitionKey(order.Id));
var replaced = await resilient.ReplaceItemAsync(order, order.Id, new PartitionKey(order.Id));
var deleted = await resilient.DeleteItemAsync<Order>(id, new PartitionKey(id));
// Query
var query = new QueryDefinition("SELECT * FROM c WHERE c.customerId = @id")
.WithParameter("@id", customerId);
var orders = await resilient.QueryAsync<Order>(query);
From CosmosClient directly
var resilient = cosmosClient.WithPolly("ecommerce", "orders", pipeline =>
pipeline
.AddRetry(new RetryStrategyOptions
{
MaxRetryAttempts = 3,
ShouldHandle = CosmosTransientErrors.IsTransient,
})
.AddTimeout(TimeSpan.FromSeconds(30)));
Dependency injection
// Program.cs
builder.Services.AddSingleton(new CosmosClient(connectionString));
builder.Services.AddPollyCosmosDb("ecommerce", "orders", pipeline =>
pipeline
.AddRetry(new RetryStrategyOptions
{
MaxRetryAttempts = 3,
Delay = TimeSpan.FromMilliseconds(200),
BackoffType = DelayBackoffType.Exponential,
UseJitter = true,
ShouldHandle = CosmosTransientErrors.IsTransient,
})
.AddTimeout(TimeSpan.FromSeconds(30))
.AddCircuitBreaker(new CircuitBreakerStrategyOptions
{
FailureRatio = 0.5,
MinimumThroughput = 10,
SamplingDuration = TimeSpan.FromSeconds(30),
BreakDuration = TimeSpan.FromSeconds(15),
}));
// Repository
public class OrderRepository(ResilientCosmosContainer container)
{
public Task<ItemResponse<Order>> SaveAsync(Order order) =>
container.UpsertItemAsync(order, new PartitionKey(order.Id));
public async Task<List<Order>> GetByCustomerAsync(string customerId)
{
var query = new QueryDefinition(
"SELECT * FROM c WHERE c.customerId = @id")
.WithParameter("@id", customerId);
return await container.QueryAsync<Order>(query);
}
}
Supported operations
| Method | Description |
|---|---|
CreateItemAsync<T> |
Create an item |
ReadItemAsync<T> |
Read item by id + partition key |
UpsertItemAsync<T> |
Insert or replace an item |
ReplaceItemAsync<T> |
Replace an existing item |
DeleteItemAsync<T> |
Delete item by id + partition key |
QueryAsync<T> |
Query with QueryDefinition, returns List<T> |
Pipeline order
[Timeout] → [Retry] → [Circuit Breaker] → [CosmosClient]
pipeline
.AddTimeout(TimeSpan.FromSeconds(30)) // 1. Overall deadline
.AddRetry(retryOptions) // 2. Retry transient failures
.AddCircuitBreaker(cbOptions) // 3. Open circuit under load
Related Packages
| Package | Downloads | Description |
|---|---|---|
| PollyHealthChecks | ASP.NET Core health checks for Polly v8 circuit breakers — expose circuit-breaker state (Closed, HalfOpen, Open, Isolated) as /health endpoint responses | |
| PollyBackoff | Backoff delay strategies for Polly v8 resilience pipelines | |
| PollyEFCore | Polly v8 resilience pipelines for Entity Framework Core — wrap every EF Core query and SaveChanges with retry, timeout and circuit-breaker via a single AddPollyResilience() call | |
| PollyMailKit | Polly v8 resilience pipelines for MailKit — retry, timeout, and circuit-breaker for SmtpClient.SendAsync and any MailKit SMTP operation | |
| PollyMassTransit | Polly v8 resilience pipelines for MassTransit — retry, timeout, and circuit-breaker for IBus.Publish and ISendEndpointProvider.Send | |
| PollyNpgsql | Polly v8 resilience pipelines for Npgsql (PostgreSQL) — retry, timeout, and circuit-breaker for NpgsqlConnection queries and commands, plus a built-in PostgresTransientErrors predicate covering all common PostgreSQL transient SQLSTATE codes | |
| PollyOpenAI | Polly v8 resilience for OpenAI and Azure OpenAI API calls | |
| PollyAzureEventHub | Polly v8 resilience pipelines for Azure Event Hubs — retry, timeout, and circuit-breaker for EventHubProducerClient and EventHubConsumerClient | |
| PollyElasticsearch | Polly v8 resilience pipelines for Elastic.Clients.Elasticsearch 8+ — retry, timeout, and circuit-breaker for any Elasticsearch operation, plus a built-in ElasticTransientErrors predicate covering rate limiting (429), service unavailability (503), gateway timeouts (504), and connection failures | |
| PollyHangfire | Polly v8 resilience pipelines for Hangfire — retry, timeout, and circuit-breaker for IBackgroundJobClient.Enqueue and Schedule | |
| PollySendGrid | Polly v8 resilience pipelines for SendGrid — retry, timeout, and circuit-breaker for ISendGridClient.SendEmailAsync | |
| PollyMongo | Polly v8 resilience pipelines for MongoDB.Driver — wrap Find, InsertOne, UpdateOne, DeleteOne and other IMongoCollection calls with retry, timeout, circuit-breaker, and more using a single ResilientMongoCollection decorator | |
| PollyDapper | Polly v8 resilience pipelines for Dapper — wrap QueryAsync, ExecuteAsync, and other Dapper calls with retry, timeout, circuit-breaker, and more using a single ResilientDbConnection decorator | |
| PollyMediatR | Polly v8 resilience pipelines for MediatR — add retry, timeout, circuit-breaker, rate-limiting, hedging, and chaos engineering to any MediatR request handler with a single line of DI registration | |
| PollySqlClient | Polly v8 resilience pipelines for Microsoft.Data.SqlClient (SQL Server and Azure SQL) — retry, timeout, and circuit-breaker for SqlConnection queries and commands, plus a built-in SqlServerTransientErrors predicate covering all common SQL Server and Azure SQL transient error numbers | |
| PollyAzureKeyVault | Polly v8 resilience pipelines for Azure Key Vault — retry, timeout, and circuit-breaker for SecretClient, KeyClient, and CertificateClient | |
| PollyAzureQueueStorage | Polly v8 resilience pipelines for Azure Queue Storage — retry, timeout, and circuit-breaker for Azure.Storage.Queues QueueClient | |
| PollyRedis | Polly v8 resilience for StackExchange.Redis | |
| PollyAzureServiceBus | Polly v8 resilience for Azure Service Bus — retry, circuit breaker, and timeout for sending and receiving messages | |
| PollyAzureBlob | Polly v8 resilience pipelines for Azure Blob Storage — wrap BlobClient and BlobContainerClient operations with retry, timeout, circuit-breaker, and more using ResilientBlobClient and ResilientBlobContainerClient decorators | |
| PollyAzureTableStorage | Polly v8 resilience pipelines for Azure Table Storage — retry, timeout, and circuit-breaker for Azure.Data.Tables TableClient |
💼 Need .NET consulting?
The author of this package is available for consulting on Polly v8 resilience, Azure cloud architecture, and clean .NET design.
→ solidqualitysolutions.com · LinkedIn
License
MIT
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net6.0 is compatible. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Microsoft.Azure.Cosmos (>= 3.62.1)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.2)
- Newtonsoft.Json (>= 13.0.4)
- Polly.Core (>= 8.7.0)
-
net6.0
- Microsoft.Azure.Cosmos (>= 3.62.1)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.2)
- Newtonsoft.Json (>= 13.0.4)
- Polly.Core (>= 8.7.0)
-
net8.0
- Microsoft.Azure.Cosmos (>= 3.62.1)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.2)
- Newtonsoft.Json (>= 13.0.4)
- Polly.Core (>= 8.7.0)
-
net9.0
- Microsoft.Azure.Cosmos (>= 3.62.1)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.2)
- Newtonsoft.Json (>= 13.0.4)
- Polly.Core (>= 8.7.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
1.0.1: Fix package icon (was showing an incorrect/placeholder image). 1.0.0: Initial release. ResilientCosmosContainer wraps Azure Cosmos DB Container operations in a Polly v8 ResiliencePipeline. Includes CosmosTransientErrors helper with pre-built ShouldHandle predicate covering rate limiting (429), timeouts (408), partition splits (410), and service unavailability (503). Supports net6.0, net8.0, and net9.0.