skip to content

In an ASP.NET Core 10 app, how do you give an HttpClient automatic retries for transient failures, and which package provides them?

level: juniorimportance: must knowfreq 58%

answer

  1. not in the shared framework
  2. Microsoft.Extensions.Http.Resilience
  3. chained on the IHttpClientBuilder
  4. 5xx, 408, 429 and HttpRequestException
  5. Microsoft.Extensions.Http.Polly is deprecated

basics

~10 s

Add the Microsoft.Extensions.Http.Resilience package and chain AddStandardResilienceHandler() onto the client's AddHttpClient registration. It retries 5xx, 408 and 429 responses and HttpRequestException, alongside a circuit breaker and timeouts, built on Polly 8.

solid answer

~40 s

Resilience is not in the ASP.NET Core shared framework, so you add `Microsoft.Extensions.Http.Resilience` (10.10.1 at the time of writing, built on Polly 8). Then chain it on the client's builder: `builder.Services.AddHttpClient<PaymentGatewayClient>(...).AddStandardResilienceHandler();`. That inserts a `DelegatingHandler` running a ready-made pipeline: a concurrency limiter, a 30-second total timeout, a retry, a circuit breaker and a 10-second per-attempt timeout. The retry makes up to three extra attempts with exponential backoff and jitter, honours a `Retry-After` header, and treats as transient any 5xx, 408 or 429 response, an `HttpRequestException` and Polly's `TimeoutRejectedException`. Calling code does not change: the typed client still just calls `GetFromJsonAsync`. The older `Microsoft.Extensions.Http.Polly` package with `AddTransientHttpErrorPolicy` and Polly v7 policies is deprecated.

code

csharp · 14 lines
csharp
// Program.cs (package: Microsoft.Extensions.Http.Resilience)
builder.Services.AddHttpClient<PaymentGatewayClient>(client =>
{
    client.BaseAddress = new Uri("https://gateway.example.com/");
})
.AddStandardResilienceHandler();

public sealed class PaymentGatewayClient(HttpClient http)
{
    public Task<PaymentStatus?> GetStatusAsync(string paymentId, CancellationToken ct) =>
        http.GetFromJsonAsync<PaymentStatus>($"v1/payments/{paymentId}", ct);
}

public record PaymentStatus(string Id, string State);

go deeper

for a junior

Recall the package name, that AddStandardResilienceHandler is chained on AddHttpClient's builder, and which statuses count as transient.

for a middle

Explain the five strategies the handler adds, their headline defaults, and why the Polly v7 based package was replaced.

for a senior

Show you check which methods get retried, how the handler changes HttpClient.Timeout, and how retries load a struggling dependency.

for a principal

Decide which downstream calls deserve the standard handler, a custom pipeline or none, and standardise that choice across teams.

## Where retries come from in .NET 10 `HttpClient` itself never retries a failed request. In an ASP.NET Core app you add retries per client through `IHttpClientFactory`, by inserting a **resilience handler** into that client's handler chain. The supported package is **`Microsoft.Extensions.Http.Resilience`**, shipped from the dotnet/extensions repository (10.10.1 here) and built on **Polly 8**. It is not part of the shared framework and the `webapi` template does not reference it, so you add it yourself: ```bash dotnet add package Microsoft.Extensions.Http.Resilience ``` ## Turning it on 1. Register the client as usual with `AddHttpClient`, named or typed. 2. Chain **`AddStandardResilienceHandler()`** on the returned `IHttpClientBuilder`. 3. Optionally tune it with `.Configure(o => ...)` or bind an `IConfigurationSection`. For a shop that charges cards through a flaky payment gateway and polls it for payment status, the registration is two lines, and the typed client's methods stay exactly as they were. ## What the standard handler gives you The handler runs a pipeline of five strategies around every request sent through that client: | Strategy | Default | |---|---| | Rate limiter (concurrency) | 1,000 concurrent requests, no queue | | Total request timeout | 30 seconds for the whole call, all attempts included | | Retry | 3 retries, exponential backoff from 2 s with jitter, honours `Retry-After` | | Circuit breaker | opens at a 10% failure ratio over 30 s with at least 100 calls; stays open 5 s | | Attempt timeout | 10 seconds per attempt | ## What counts as transient The retry decides with the package's `HttpClientResiliencePredicates`. An outcome is **transient** when it is: - an HTTP response with status **500 or above**; - **408 Request Timeout** or **429 Too Many Requests**; - an **`HttpRequestException`**, for example a refused connection or a DNS failure; - a **`TimeoutRejectedException`**, which Polly throws when an attempt runs past its timeout; - a cancellation carrying an inner `TimeoutException` while the caller's own token is still live, which the package treats as an HTTP connection timeout. The circuit breaker counts the same outcomes except the last one. A 400, 401, 404 or 422 is a real answer, not a glitch, and is returned to your code untouched. That matters: retrying a 401 would only repeat the same rejection. ## What changed from older code Older code often looks like `AddTransientHttpErrorPolicy(p => p.WaitAndRetryAsync(3, ...))` or `AddPolicyHandler(...)`. Those come from **`Microsoft.Extensions.Http.Polly`**, which wraps Polly v7's static `Policy` API; the .NET documentation now marks that package deprecated. The replacements are: - `AddStandardResilienceHandler()` for a sensible default pipeline; - `AddStandardHedgingHandler()` when parallel attempts against slow endpoints are wanted; - `AddResilienceHandler("name", builder => ...)` for a pipeline you assemble from Polly 8 strategies. ## Things to know before you ship it - **Every HTTP method is retried by default**, including `POST`. A card charge needs `DisableForUnsafeHttpMethods()` or a separate client without retries. - **The handler switches `HttpClient.Timeout` off** (sets it to `Timeout.InfiniteTimeSpan`) so its own timeouts govern. - **Options are validated at startup**; an inconsistent timeout configuration stops the app from starting rather than failing later. - **Retries add load** to a struggling dependency; the circuit breaker and the total timeout exist to bound that.

  • Does AddStandardResilienceHandler retry a 404 from the gateway?
    No. Its transient predicate covers status 500 and above, 408 and 429, plus `HttpRequestException` and `TimeoutRejectedException`. A 404 is returned to the caller after one attempt, and `GetFromJsonAsync` then throws `HttpRequestException` with `StatusCode` set to `NotFound`.
  • How do you lower the retry count for one client?
    Configure the options on the returned builder: `.AddStandardResilienceHandler().Configure(o => o.Retry.MaxRetryAttempts = 1)`, or bind an `IConfigurationSection` with `.Configure(section)`. The options are named per client, so other clients keep their defaults.

  • Says HttpClient retries failed requests on its own
  • Reaches for AddTransientHttpErrorPolicy as the current .NET 10 approach
  • Believes the standard handler also retries 404 and 400 responses
  • Thinks resilience ships in the ASP.NET Core shared framework
  • Assumes POST requests are never retried by the standard handler

Assumes ASP.NET Core 10 with Microsoft.Extensions.Http.Resilience 10.10.1 on Polly 8; Microsoft.Extensions.Http.Polly and Polly v7 policies are the deprecated predecessors.