skip to content

Resilience Handlers

Microsoft.Extensions.Http.Resilience layers Polly strategies onto HttpClient: a standard handler, hedging and custom pipelines. Interviewers probe its strategy order and retrying non-idempotent calls.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

6

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.

open as a page

In ASP.NET Core, which five strategies does AddStandardResilienceHandler stack, in what order from the outermost, and why does that order matter?

level: middleimportance: must knowfreq 50%

basics

~20 s

From the outside in: rate limiter, total request timeout (30 s), retry, circuit breaker, attempt timeout (10 s). The total timeout bounds every retry, the breaker counts each attempt, and an open breaker fails fast because its rejection is not retried.

open as a page

In ASP.NET Core, when would you use AddResilienceHandler instead of the standard handler, and what changes when you build the pipeline yourself?

level: middleimportance: should knowfreq 36%

basics

~20 s

AddResilienceHandler fits when the standard handler's fixed five strategies do not: a fallback, fewer layers or another order. You assemble the pipeline yourself, so predicates, defaults and timeouts are yours, and HttpClient.Timeout stays switched on.

open as a page

In ASP.NET Core's standard resilience handler, how do TotalRequestTimeout, AttemptTimeout and HttpClient.Timeout interact, and which timeout settings does startup validation reject?

level: seniorimportance: should knowfreq 34%

basics

~20 s

AddStandardResilienceHandler sets HttpClient.Timeout to infinite so its own 30-second total and 10-second attempt timeouts govern. Startup validation rejects an attempt timeout above the total timeout, and a breaker sampling duration shorter than twice the attempt timeout.

open as a page

An ASP.NET Core client POSTs card charges to a payment gateway through AddStandardResilienceHandler; what can go wrong by default, and how do DisableForUnsafeHttpMethods and DisableFor help?

level: seniorimportance: should knowfreq 38%

basics

~20 s

The standard handler retries every HTTP method, so a charge the gateway already processed can be resent after a timeout or 5xx and bill twice. DisableForUnsafeHttpMethods stops retries for POST, PATCH, PUT, DELETE and CONNECT; DisableFor takes your own list.

open as a page

In ASP.NET Core, how does AddStandardHedgingHandler differ from AddStandardResilienceHandler, and why does it keep a circuit breaker per authority?

level: seniorimportance: nice to knowfreq 24%

basics

~20 s

AddStandardHedgingHandler sends an extra copy of a request when the first is still running after 2 seconds or failed transiently, and keeps the first good answer. Its limiter, breaker and attempt timeout run per authority, so an unhealthy host is skipped.

open as a page