HttpClient retry policy with Polly
How to make outgoing HTTP calls resilient to transient failures using Polly retry policies with IHttpClientFactory — including jittered backoff, the modern Microsoft.Extensions.Http.Resilience approach, and common pitfalls.
Network calls fail. A downstream service restarts, a load balancer drops a connection, or an API briefly returns 503 Service Unavailable while it scales up. Most of these failures are transient — the exact same request would succeed a moment later. A retry policy lets your application absorb these blips instead of surfacing them as errors to your users.
Polly is the de facto resilience library for .NET, and it plugs straight into IHttpClientFactory, so every request made through a configured HttpClient gets retries automatically — no try/catch loops scattered through your code.
Required packages
Install the following NuGet packages:
Microsoft.Extensions.Http.Polly— integrates Polly withIHttpClientFactoryand providesHttpPolicyExtensions.Polly.Contrib.WaitAndRetry— provides theBackoff.DecorrelatedJitterBackoffV2helper used below.
dotnet add package Microsoft.Extensions.Http.Polly
dotnet add package Polly.Contrib.WaitAndRetryCreating the retry policy
The snippet below builds a retry policy using Decorrelated Jitter Backoff V2. Unlike a fixed delay, jittered backoff grows the wait time exponentially and randomises each interval. That randomness matters: if hundreds of clients all fail at the same moment and all retry after exactly 1 second, they hit the struggling service again at exactly the same moment — a so-called retry storm. Jitter spreads those retries out and gives the downstream service room to recover.
DecorrelatedJitterBackoffV2 takes two parameters: the median delay before the first retry (TimeSpan.FromMilliseconds(100)) and the maximum number of retries (5).
var retryPolicy =
HttpPolicyExtensions
.HandleTransientHttpError()
.OrResult(response => response.StatusCode == HttpStatusCode.TooManyRequests)
.WaitAndRetryAsync(
Backoff.DecorrelatedJitterBackoffV2(
medianFirstRetryDelay: TimeSpan.FromMilliseconds(100),
retryCount: 5),
onRetryAsync: (outcome, delay, retryAttempt, _) =>
{
// Log the retry so failures are visible, not silently swallowed
Console.WriteLine(
$"Retry {retryAttempt} in {delay.TotalMilliseconds:N0} ms " +
$"due to {outcome.Exception?.Message ?? outcome.Result.StatusCode.ToString()}");
return Task.CompletedTask;
});What counts as a transient error?
HandleTransientHttpError() handles the failures that are almost always worth retrying:
- An
HttpRequestException(DNS failures, refused connections, dropped sockets, etc.) - Any
5xxserver error response 408 Request Timeout
On line 4 we've also added 429 Too Many Requests with OrResult, since rate-limited requests are a classic case where waiting and trying again is the right response. Client errors like 400 Bad Request or 404 Not Found are deliberately not retried — sending the same bad request again will just produce the same error.
Applying the retry policy
Register the policy against a typed client such as SomeApiClient. The factory injects a configured HttpClient into the client's constructor, and the policy applies to every call made through that instance.
services.AddHttpClient<ISomeApiClient, SomeApiClient>(client =>
{
client.BaseAddress = new Uri("https://api.example.com");
})
.AddPolicyHandler(retryPolicy);The typed client itself stays completely unaware of the retry logic:
public class SomeApiClient(HttpClient httpClient) : ISomeApiClient
{
public async Task<Order?> GetOrderAsync(int id, CancellationToken cancellationToken = default)
{
// If this call hits a transient error, Polly retries it transparently
return await httpClient.GetFromJsonAsync<Order>($"orders/{id}", cancellationToken);
}
}Adding a per-attempt timeout
By default, HttpClient.Timeout (100 seconds) applies to the whole operation, including every retry. If a single attempt hangs, it can eat the entire budget before a retry ever gets a chance. Adding a Polly timeout policy inside the retry policy limits how long each individual attempt can take:
var timeoutPolicy = Policy.TimeoutAsync<HttpResponseMessage>(TimeSpan.FromSeconds(10));
services.AddHttpClient<ISomeApiClient, SomeApiClient>()
.AddPolicyHandler(retryPolicy) // outer: decides whether to try again
.AddPolicyHandler(timeoutPolicy); // inner: limits each individual attemptThe order matters: handlers are applied outermost first, so the retry wraps the timeout. Note that HandleTransientHttpError() does not handle the TimeoutRejectedException thrown when an attempt times out, so add .Or<TimeoutRejectedException>() to the retry policy if you want timed-out attempts to be retried.
Things to watch out for
-
Only retry idempotent requests. Retrying a
GETis safe. Retrying aPOSTthat creates an order might create it twice if the first attempt actually succeeded but the response was lost on the way back. Either make the endpoint idempotent (e.g. with an idempotency key) or only apply the retry policy to safe requests:var noOpPolicy = Policy.NoOpAsync().AsAsyncPolicy<HttpResponseMessage>(); services.AddHttpClient<ISomeApiClient, SomeApiClient>() .AddPolicyHandler(request => request.Method == HttpMethod.Get ? retryPolicy : noOpPolicy); -
Keep the total retry time reasonable. Five retries with exponential backoff can add up. Make sure the worst case still fits within whatever timeout your own callers have.
-
Log retries. A system that silently retries can hide a degrading dependency for a long time. Logging in
onRetryAsyncmakes the problem visible before it becomes an outage.
The modern alternative: Microsoft.Extensions.Http.Resilience
Since .NET 8, Microsoft recommends Microsoft.Extensions.Http.Resilience, which is built on Polly v8. Microsoft.Extensions.Http.Polly still works, but it's based on the older Polly v7 API. If you're starting fresh, the new package is the better choice.
The simplest option is the standard resilience handler, which adds sensible defaults for retries, timeouts, rate limiting and circuit breaking in a single line:
services.AddHttpClient<ISomeApiClient, SomeApiClient>()
.AddStandardResilienceHandler();If you want a retry policy equivalent to the one above, you can build your own pipeline:
services.AddHttpClient<ISomeApiClient, SomeApiClient>()
.AddResilienceHandler("some-api", builder =>
{
builder.AddRetry(new HttpRetryStrategyOptions
{
MaxRetryAttempts = 5,
Delay = TimeSpan.FromMilliseconds(100),
BackoffType = DelayBackoffType.Exponential,
UseJitter = true
});
builder.AddTimeout(TimeSpan.FromSeconds(10));
});HttpRetryStrategyOptions already handles transient HTTP errors (including 429) by default and respects the Retry-After header when the server sends one, so there's less to configure by hand.