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.

Bart Tworek3 min readc#pollyhttpclientresilience

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:

dotnet add package Microsoft.Extensions.Http.Polly
dotnet add package Polly.Contrib.WaitAndRetry

Creating 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:

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 attempt

The 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

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.