skip to content

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%

answer

  1. HttpClient.Timeout set to infinite
  2. registration order of ConfigureHttpClient
  3. attempt must not exceed total
  4. sampling at least twice the attempt
  5. OptionsValidationException at startup

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.

solid answer

~40 s

`TotalRequestTimeout` (30 s) wraps the retry and caps all attempts plus backoff; `AttemptTimeout` (10 s) caps each try and is retried as transient. Both throw Polly's `TimeoutRejectedException`. So that `HttpClient.Timeout` (100 s) cannot cut across them, the handler calls `ConfigureHttpClient(c => c.Timeout = Timeout.InfiniteTimeSpan)`. Client configuration runs in registration order, so a `Timeout` you set in the `AddHttpClient` delegate is overwritten, while a `ConfigureHttpClient` chained after the handler wins and can silently end retries early. The options are registered with `ValidateOnStart`: besides range checks, a custom validator fails startup with `OptionsValidationException` when `AttemptTimeout` exceeds `TotalRequestTimeout`, or when `CircuitBreaker.SamplingDuration` is less than twice `AttemptTimeout`. Raising the attempt timeout to 20 s without raising the 30-second sampling duration is the classic way to trip it.

code

csharp · 10 lines
csharp
builder.Services.AddHttpClient<PaymentGatewayClient>(c => c.BaseAddress = new Uri("https://gateway.example.com/"))
    .AddStandardResilienceHandler(o =>
    {
        o.AttemptTimeout.Timeout = TimeSpan.FromSeconds(20);
        o.CircuitBreaker.SamplingDuration = TimeSpan.FromSeconds(40); // >= 2 x attempt
        o.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(45);     // >= attempt
    });

// Do NOT add this after the handler: it re-enables a shorter HttpClient.Timeout
// .ConfigureHttpClient(c => c.Timeout = TimeSpan.FromSeconds(15));

go deeper

for a junior

Recall the two pipeline timeouts, 30 seconds total and 10 seconds per attempt, and that the handler disables HttpClient.Timeout.

for a middle

Explain why HttpClient.Timeout is set to infinite, how configuration order can undo that, and which exception each timeout throws.

for a senior

Tune timeouts for a slow dependency without breaking the validator's rules, and spot a late ConfigureHttpClient silently ending retries.

for a principal

Set timeout budgets per dependency against your own callers' limits and decide who owns those values in configuration.

## Three timeouts on one call A client with the standard resilience handler has three timeout settings that could apply to one logical call: | Setting | Where it lives | Default under the standard handler | What it bounds | |---|---|---|---| | `HttpClient.Timeout` | the `HttpClient` | `Timeout.InfiniteTimeSpan` (handler sets it) | the whole `SendAsync`, outside every handler | | `TotalRequestTimeout.Timeout` | strategy 2 of 5 | 30 seconds | all attempts plus retry waits | | `AttemptTimeout.Timeout` | strategy 5 of 5 | 10 seconds | one attempt | Both Polly timeouts throw **`TimeoutRejectedException`**, not `TaskCanceledException`. Because the attempt timeout sits inside the retry and the retry treats `TimeoutRejectedException` as transient, a slow attempt is abandoned and tried again. The total timeout sits outside the retry, so when it fires the operation ends. ## Why HttpClient.Timeout is switched off `HttpClient.Timeout` defaults to 100 seconds and wraps the entire handler chain. If it were shorter than the pipeline's own budget, it would cancel the call in the middle of a backoff wait and surface as a `TaskCanceledException` instead of the pipeline's exception. So `AddStandardResilienceHandler()` (and `AddStandardHedgingHandler()`) end with `ConfigureHttpClient(client => client.Timeout = Timeout.InfiniteTimeSpan)`. That call joins the client's list of configuration actions, which run **in registration order** every time a client is created: 1. `AddHttpClient<PaymentGatewayClient>(c => c.Timeout = TimeSpan.FromSeconds(15))` runs first. 2. The resilience handler's action runs next and sets the timeout to infinite, so the 15 seconds is lost. 3. A `.ConfigureHttpClient(c => c.Timeout = ...)` chained **after** the handler runs last and wins. The third case is the dangerous one: a 15-second `HttpClient.Timeout` under a 30-second total timeout kills the call during the second retry, and logs show cancellations instead of Polly timeouts. To change the budget, change `TotalRequestTimeout`, not `HttpClient.Timeout`. A custom `AddResilienceHandler` pipeline does not touch `HttpClient.Timeout`, so there the 100-second default stays in force around the whole pipeline, all attempts included. ## Startup validation The handler registers `HttpStandardResilienceOptions` per client with `AddOptionsWithValidateOnStart`, using two validators: - **Data annotations** on the nested options: every option object is `[Required]`, and Polly's own ranges apply (a timeout must lie between 10 ms and 24 hours, for instance). - **A custom validator** with two cross-field rules: - `AttemptTimeout.Timeout` must not be greater than `TotalRequestTimeout.Timeout`; - `CircuitBreaker.SamplingDuration` must be at least **twice** `AttemptTimeout.Timeout`, so the breaker's window can contain more than one timed-out attempt. Because validation runs when the host starts, a bad combination throws `OptionsValidationException` before the app serves a request, rather than producing a breaker that can never open. ## Tuning for a slow card-payment gateway Suppose the gateway's status endpoint sometimes needs 15 seconds: - Raising only `AttemptTimeout` to 20 s fails startup: 30 s sampling is less than 2 x 20 s. - Raise `CircuitBreaker.SamplingDuration` to at least 40 s as well. - Then check that `TotalRequestTimeout` (30 s) still allows a retry at all; one 20-second attempt plus a backoff leaves little room, so either raise it or accept a single attempt. - Keep the total below whatever your own caller waits for, or your endpoint times out before the pipeline gives up. ## Configuring from appsettings `.AddStandardResilienceHandler(builder.Configuration.GetSection("PaymentGateway:Resilience"))` binds the options from configuration with `ErrorOnUnknownConfiguration` switched on, so a misspelt key in that section is an error rather than silently ignored. The handler enables reloads for those named options, so an edited value rebuilds the pipeline. The validators run again whenever the options object is rebuilt: a reloaded value that breaks a rule makes the rebuild fail, Polly reports a `ReloadFailed` resilience event and the previous pipeline keeps running, so watch for that event rather than assuming the new values are live.

  • What exception reaches the typed client when the 30-second total timeout fires?
    Polly's `TimeoutRejectedException`, from the `Polly.Timeout` namespace. It is not a `TaskCanceledException` with an inner `TimeoutException`, which is what `HttpClient.Timeout` would raise, so catch blocks written for plain HttpClient timeouts miss it.
  • Why must the breaker's sampling duration be at least twice the attempt timeout?
    Attempts that time out are counted as failures, but each takes the full attempt timeout to report. If the sampling window were shorter than two attempt timeouts, it could barely hold one such failure, so the breaker would rarely gather enough samples to open. The validator enforces the factor of two at startup.

  • Sets HttpClient.Timeout after the handler to limit the whole call
  • Expects TaskCanceledException when a Polly timeout strategy fires
  • Raises AttemptTimeout without touching SamplingDuration or TotalRequestTimeout
  • Believes invalid timeout options only fail on the first request
  • Thinks the 10-second attempt timeout bounds the whole operation