In ASP.NET Core, when would you use AddResilienceHandler instead of the standard handler, and what changes when you build the pipeline yourself?
answer
- one resilience handler per client
- ResiliencePipelineBuilder<HttpResponseMessage>
- Http*StrategyOptions carry the HTTP predicate
- plain RetryStrategyOptions ignores a 503
- HttpClient.Timeout stays at 100 s
basics
~20 sAddResilienceHandler 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.
solid answer
~40 s`AddResilienceHandler("status", pipeline => ...)` adds one resilience `DelegatingHandler` and hands you a Polly 8 `ResiliencePipelineBuilder<HttpResponseMessage>`; the first strategy you add is the outermost. Reach for it when the standard set does not fit: a fallback that returns a cached payment status, no retry for a charge client, or a shorter chain. Three things change. First, the options type matters: `HttpRetryStrategyOptions`, `HttpCircuitBreakerStrategyOptions` and `HttpTimeoutStrategyOptions` bring the HTTP transient predicate, while Polly's plain `RetryStrategyOptions<HttpResponseMessage>` handles only exceptions, so a 503 response is not retried, and backs off at a constant 2 s without jitter. Second, nothing switches `HttpClient.Timeout` off, so its 100 seconds still wrap the whole pipeline. Third, the standard handler's cross-field validation is gone. Keep one resilience handler per client; do not stack a custom one on the standard handler.
code
csharp · 14 linesbuilder.Services.AddHttpClient<PaymentStatusClient>(c => c.BaseAddress = new Uri("https://gateway.example.com/"))
.AddResilienceHandler("status", pipeline =>
{
// outermost: turns an open breaker or a timeout into a 503 response
pipeline.AddFallback(new FallbackStrategyOptions<HttpResponseMessage>
{
FallbackAction = _ => Outcome.FromResultAsValueTask(
new HttpResponseMessage(HttpStatusCode.ServiceUnavailable))
});
pipeline.AddTimeout(TimeSpan.FromSeconds(20)); // whole operation
pipeline.AddRetry(new HttpRetryStrategyOptions { MaxRetryAttempts = 2 });
pipeline.AddCircuitBreaker(new HttpCircuitBreakerStrategyOptions());
pipeline.AddTimeout(TimeSpan.FromSeconds(5)); // each attempt
});go deeper
Recall that AddResilienceHandler lets you build your own pipeline when the standard handler's fixed strategies do not fit.
Explain why the Http options classes matter, that strategies nest outermost first, and that HttpClient.Timeout stays active under a custom pipeline.
Show how you avoid stacked handlers, replace an existing one deliberately, and design a fallback that never hides caller cancellation.
Decide when a team may own a custom pipeline versus tuning the standard one, and how those pipelines are reviewed and observed.
## What AddResilienceHandler gives you `AddResilienceHandler` is the open-ended entry point of **`Microsoft.Extensions.Http.Resilience`**. Chained on an `IHttpClientBuilder`, it: - takes a **pipeline name**, combined with the client name (`PaymentStatusClient-status`), which identifies the pipeline in telemetry and lets one client hold more than one handler if it really must; - hands your callback a **`ResiliencePipelineBuilder<HttpResponseMessage>`**, the Polly 8 builder, so any Polly strategy can be added; - inserts a resilience `DelegatingHandler` into the client's chain through `AddHttpMessageHandler`, so it sits among your other handlers in registration order; - returns an `IHttpResiliencePipelineBuilder`, on which `SelectPipelineByAuthority()` or `SelectPipelineBy(...)` give each host its own pipeline instance. A second overload passes a **`ResilienceHandlerContext`** as well, which exposes `ServiceProvider`, `GetOptions<T>(name)` and `EnableReloads<T>(name)` so a pipeline can read bound options and rebuild itself when configuration changes. ## When the standard handler is not enough The standard handler's five strategies and their order are fixed. Typical reasons to build your own, in a shop that talks to a card-payment gateway: 1. **A fallback.** The status page should show the last known state, or a clear 503, instead of an exception when the breaker is open. 2. **A different shape.** A charge client wants a breaker and a timeout but **no retry at all**. 3. **Different predicates.** The gateway signals overload with a status the standard predicate does not cover, or a 503 that must never be retried. 4. **Fewer layers.** A low-volume internal call does not need a 1,000-permit limiter. If you only want other *values* (two retries, a 5-second attempt timeout), stay with the standard handler and call `.Configure(...)`; a custom pipeline is more code to own. ## Three things that change | Concern | Standard handler | Your own pipeline | |---|---|---| | What counts as a failure | HTTP predicate: status 500 and above, 408, 429, `HttpRequestException`, `TimeoutRejectedException` | whatever each options object's `ShouldHandle` says | | `HttpClient.Timeout` | set to infinite by the handler | left alone: 100 seconds unless you set it | | Validation | validate-on-start, plus cross-field timeout rules | Polly range checks when the pipeline is built, nothing cross-field | **The options type decides the predicate.** The `Http*` options classes in the package come preconfigured: `HttpRetryStrategyOptions` handles the transient HTTP outcomes, backs off exponentially with jitter and honours `Retry-After`. Polly's base `RetryStrategyOptions<HttpResponseMessage>` handles **any exception except `OperationCanceledException`** and **no results at all**, so a 503 *response* is returned unretried; its backoff is constant, 2 seconds, without jitter. The same split applies to the circuit breaker. **`HttpClient.Timeout` stays in force.** Only the standard resilience and hedging handlers switch it off. Under a custom pipeline, the 100-second default wraps every attempt and every backoff wait, and when it fires the caller sees `TaskCanceledException` rather than Polly's `TimeoutRejectedException`. **Order is yours to get right.** Strategies nest outermost first. A timeout added first bounds the whole operation; added last, it bounds each attempt. ## Do not stack handlers The .NET documentation advises one resilience handler per client. Chaining `AddStandardResilienceHandler()` and then `AddResilienceHandler("extra", ...)` nests two pipelines: the standard one is outermost, and each of its attempts runs the custom pipeline, so both retries multiply and two breakers count the same failures. To replace a handler that is already on the client, `RemoveAllResilienceHandlers()` (marked `[Experimental]`) removes every resilience handler registered before it, after which you add your own. ## A worked shape For the status endpoint the shop wants: fallback outermost, then a total timeout, a retry, a breaker and a per-attempt timeout, all with HTTP-aware options. That is the standard order with one extra layer, which is exactly when a custom pipeline earns its keep.
- How would a custom pipeline read its retry count from appsettings.json and pick up a change without a restart?Use the overload whose callback also receives `ResilienceHandlerContext`. Read the bound options with `context.GetOptions<StatusResilienceOptions>(name)` and call `context.EnableReloads<StatusResilienceOptions>(name)`; when the options change, the pipeline is rebuilt with the new values.
- Why does the fallback in the example catch an open breaker but not a request the caller cancelled?A fallback built from `FallbackStrategyOptions<HttpResponseMessage>` without its own `ShouldHandle` handles any exception except `OperationCanceledException`. `BrokenCircuitException` and `TimeoutRejectedException` qualify, so they become a 503 response; a cancellation from the caller's token propagates as cancellation.
- Uses plain RetryStrategyOptions and expects 5xx responses to be retried
- Stacks a custom handler on the standard one to change a single value
- Assumes AddResilienceHandler also switches HttpClient.Timeout off
- Expects the standard handler's timeout validation to cover a custom pipeline
- Adds the timeout strategy first and expects it to limit each attempt