Skip to content

Repository files navigation

Polly.Contrib.Caching

NuGet NuGet Downloads CI License: MIT .NET 10 Ready

A caching resilience strategy for Polly v8 pipelines. Restores the beloved Polly v7 caching policy for the new DelayGenerator-based API.

Polly v8 dropped the built-in caching policy. This package brings it back as a proper ResilienceStrategy<T> that plugs into any ResiliencePipelineBuilder<TResult>.

Install

dotnet add package Polly.Contrib.Caching

Usage

With IMemoryCache (recommended)

using Microsoft.Extensions.Caching.Memory;
using Polly.Contrib.Caching;

var cache = new MemoryCache(new MemoryCacheOptions());

var pipeline = new ResiliencePipelineBuilder<HttpResponseMessage>()
    .AddCaching(
        cache,
        cacheKeyProvider: ctx => ctx.Properties.TryGetValue(new ResiliencePropertyKey<string>("url"), out var url) ? url : null,
        ttl: TimeSpan.FromMinutes(5))
    .AddRetry(new RetryStrategyOptions<HttpResponseMessage>
    {
        MaxRetryAttempts = 3,
    })
    .Build();

With CachingStrategyOptions

var pipeline = new ResiliencePipelineBuilder<string>()
    .AddCaching(new CachingStrategyOptions<string>
    {
        CacheProvider = new MemoryCacheProvider<string>(cache),
        CacheKeyProvider = ctx => ctx.OperationKey,
        Ttl = TimeSpan.FromMinutes(10),
    })
    .Build();

Custom ICacheProvider

Implement ICacheProvider<TResult> to use any cache store β€” distributed cache, Redis, etc.

public sealed class RedisCacheProvider<TResult>(IConnectionMultiplexer redis) : ICacheProvider<TResult>
{
    public bool TryGet(string key, out TResult? value) { /* ... */ }
    public void Set(string key, TResult? value, TimeSpan ttl) { /* ... */ }
}

Behaviour

Scenario Outcome
Cache hit Returns cached result; downstream not called
Cache miss Calls downstream; caches result on success
Downstream throws Exception propagates; nothing cached
CacheKeyProvider returns null Caching skipped; downstream always called

Composition with other strategies

Place AddCaching before retry/circuit-breaker so a cached result short-circuits the entire pipeline:

var pipeline = new ResiliencePipelineBuilder<string>()
    .AddCaching(cache, ctx => ctx.OperationKey)   // 1. check cache first
    .AddRetry(...)                                  // 2. retry on failure
    .AddCircuitBreaker(...)                         // 3. protect downstream
    .Build();

Support

If Polly.Contrib.Caching saves you time restoring the v7 caching policy, consider supporting the project:

Sponsor

πŸ’Ό Need .NET resilience help? Visit solidqualitysolutions.com for consulting and architecture services.

Related Packages

Package Downloads Description
PollyHealthChecks Downloads ASP.NET Core health checks for Polly v8 circuit breakers β€” expose circuit-breaker state (Closed, HalfOpen, Open, Isolated) as /health endpoint responses
PollyOpenTelemetry Downloads OpenTelemetry instrumentation for Polly v8 resilience pipelines
PollyBackoff Downloads Backoff delay strategies for Polly v8 resilience pipelines
PollyGrpc Downloads Polly v8 resilience interceptor for gRPC
PollyEFCore Downloads 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
PollyRabbitMQ Downloads Polly v8 resilience for RabbitMQ.Client v7+ β€” retry, circuit-breaker, and timeout for IChannel operations, with built-in RabbitMqTransientErrors predicate covering AlreadyClosedException, BrokerUnreachableException, OperationInterruptedException, and ConnectFailureException
PollyOpenAI Downloads Polly v8 resilience for OpenAI and Azure OpenAI API calls
PollySignalR Downloads Polly v8 reconnect policy for SignalR
PollyMediatR Downloads 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
PollyRedis Downloads Polly v8 resilience for StackExchange.Redis
PollyAzureServiceBus Downloads Polly v8 resilience for Azure Service Bus β€” retry, circuit breaker, and timeout for sending and receiving messages
PollyKafka Downloads Polly v8 resilience for Confluent.Kafka β€” retry, circuit breaker, and timeout for producers and consumers
PollyRateLimiter Downloads Convenience extension methods for Polly v8 resilience pipelines: AddFixedWindowRateLimiter, AddSlidingWindowRateLimiter, and AddTokenBucketRateLimiter
PollyChaos Downloads Chaos engineering and fault-injection resilience strategies for Polly v8 pipelines
PollyBulkhead Downloads Bulkhead isolation strategy for Polly v8 resilience pipelines

Also by the same author

🌐 swevo.github.io

Package Description
AutoLog.Generator Compile-time high-performance logging β€” [Log(Level, Message)] generates LoggerMessage.Define. AOT-safe.
AutoHttpClient.Generator Compile-time typed HTTP client β€” [HttpClient] on an interface generates a strongly-typed client. AOT-safe Refit alternative.
AutoDispatch.Generator Compile-time CQRS dispatcher β€” [Handler] generates a strongly-typed IDispatcher. MediatR alternative.
AutoWire Compile-time DI auto-registration β€” [Scoped]/[Singleton]/[Transient] generates IServiceCollection registration code.
AutoMap.Generator Compile-time object mapping β€” [Map(typeof(Dto))] generates ToDto() extension methods. AutoMapper alternative.

License

MIT

Releases

Packages

Contributors

Languages