Polly is the de facto .NET resilience library for expressing retry and other error-handling policies outside or alongside EF Core. Microsoft.Extensions.Http.Polly integrates those policies with HttpClientFactory, so an HTTP client can retry without embedding try/catch logic in each request method. section 11.3 section 11.4
Listing 11.15 Registering HttpClient with a Polly policy
services.AddHttpClient<IXkcdClient, XkcdClient>( client => client.BaseAddress = new Uri(baseAddr!)) #1 .AddPolicyHandler(GetRetryPolicy()); #2
Register a typed HttpClient and attach a Polly policy through AddPolicyHandler. section 11.3
Listing 11.16 Polly policy that retries on invalid HTTP response codes
using Polly; #1
using Polly.Extensions.Http;
static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy() #2
=> HttpPolicyExtensions #3
.HandleTransientHttpError() #4
.WaitAndRetryAsync(6, retryCount => #5
TimeSpan.FromMilliseconds( #6
100 * Math.Pow(2, retryCount))); #7
Build an asynchronous HTTP retry policy that handles transient failures and waits with exponential back-off. section 11.3
Listing 11.17 Custom HTTP response-code retry policy
static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
=> Policy<HttpResponseMessage> #1
.HandleResult(r => r.StatusCode ==
System.Net.HttpStatusCode.TooManyRequests) #2
.OrTransientHttpStatusCode() #3
.WaitAndRetryAsync(6, retryCount => #4
TimeSpan.FromMilliseconds(
100 * Math.Pow(2, retryCount)));
Customize the policy when retry conditions must include a specific response, such as HTTP 429 TooManyRequests. section 11.3
Polly extends beyond retries with resilience strategies for different failure patterns:
- Timeouts stop operations from waiting indefinitely. section 11.3.2
- Fallbacks return an alternative value when recovery is unlikely within a reasonable period. section 11.3.2
- Circuit breakers pause calls after failures exceed a threshold, then test the resource before closing. section 11.3.2
- Bulkheads limit concurrent requests and queue later work; rate limiting governs request volume over time. section 11.3.2
Testing an HTTP policy
Use a mocked HttpMessageHandler to simulate a 500 response and verify that the XkcdClient's policy retries as intended. section 11.3 section 11.4

