Timeout Strategies in .NET: Per-Call, Per-Request, and Total Budget

aspnetcoredotnethttpclientresilience
Timeout Strategies in .NET: Per-Call, Per-Request, and Total Budget

"Set a 30-second timeout" sounds like one decision. It's actually three, and if you only make one of them, the other two default to something you didn't choose.

They cover how long a single outbound call may take, how long the whole retry sequence for that call may take, and how long the inbound request your user is waiting on may take.

Configure them in isolation and they compose badly. A 10-second per-attempt timeout, three retries, and a bit of backoff is a perfectly reasonable-looking config that can keep a caller waiting more than 40 seconds, while the ASP.NET Core request it's serving has no ceiling at all. The fix is to think in layers with a total budget.

The Three Layers

Before any code, get the model straight. A request that calls a downstream service has three timeout scopes nested inside each other:

  • Per-call (per-attempt): how long one single outbound call is allowed to run. This is a per-attempt timeout strategy inside the retry. HttpClient.Timeout plays this role only when the retry wraps the HttpClient call from outside.
  • Total operation: how long the entire resilient operation, including every retry and every backoff delay, is allowed to run. This is a timeout placed outside the retry.
  • Per-request: how long ASP.NET Core will let the inbound request run before it aborts. This is the request timeouts middleware.
Three timeout scopes nested inside each other: the per-request inbound timeout contains the total outbound budget, which contains the per-attempt timeout around a single outbound call

The mistake is setting only the per-call value and assuming it bounds everything. It bounds one attempt.

Per-Call: What Does HttpClient.Timeout Cover?

HttpClient.Timeout is a whole-operation timeout for one SendAsync call, defaulting to 100 seconds. With the default HttpCompletionOption.ResponseContentRead, which GetAsync, PostAsync, and SendAsync use unless you pass another option, it covers sending the request, receiving the headers, and buffering the whole response body. With ResponseHeadersRead it stops once the headers arrive, and reading the body is bounded only by the CancellationToken you pass.

builder.Services.AddHttpClient("catalog", client =>
{
    client.BaseAddress = new Uri("https://catalog.internal");
    client.Timeout = TimeSpan.FromSeconds(10);
});

The trap shows up when you add resilience. A resilience handler added with AddResilienceHandler is a DelegatingHandler, so every retry and every backoff delay runs inside that one SendAsync call. HttpClient.Timeout is therefore one overall cap on all attempts combined, not a per-attempt timeout. With the 10-second value above, a first attempt that hangs uses the whole 10 seconds, HttpClient cancels the call, and the retry never gets a second attempt.

AddStandardResilienceHandler handles this differently: it sets HttpClient.Timeout to Timeout.InfiniteTimeSpan, overwriting the value from the AddHttpClient callback, so the pipeline's own timeouts are the ones that fire. HttpClient.Timeout acts as a per-attempt timeout only when the retry wraps the HttpClient call from outside, as in pipeline.ExecuteAsync(async ct => await client.GetAsync(url, ct)).

Worse, HttpClient.Timeout throws a TaskCanceledException, which is easy to mistake for ordinary cancellation. For anything beyond a trivial client, prefer Polly timeout strategies over HttpClient.Timeout, because they throw a clear TimeoutRejectedException and their position in the pipeline states exactly what they bound. Set HttpClient.Timeout above the pipeline's total timeout, so it never fires first and the pipeline owns the real timeouts. The general HttpClient guidance is in the right way to use HttpClient in .NET.

Total Budget: The Timeout That Caps Everything

This is the layer that stops the stacking. A total timeout goes outside the retry, so it bounds the entire sequence of attempts and delays, not one attempt.

In Polly v8, timeout is a strategy, and its position in the pipeline decides what it bounds. For an HttpClient, put both timeouts and the retry in one resilience handler:

dotnet add package Microsoft.Extensions.Http.Resilience
using Microsoft.Extensions.Http.Resilience;
using Polly;

builder.Services.AddHttpClient("catalog", client =>
{
    client.BaseAddress = new Uri("https://catalog.internal");
    // Above the 15-second total budget, so the pipeline fires first.
    client.Timeout = TimeSpan.FromSeconds(30);
})
.AddResilienceHandler("catalog-timeouts", pipeline =>
{
    // Total budget: caps ALL attempts + backoff combined.
    pipeline.AddTimeout(TimeSpan.FromSeconds(15));

    // Retries transient HTTP failures, including TimeoutRejectedException.
    pipeline.AddRetry(new HttpRetryStrategyOptions
    {
        MaxRetryAttempts = 3,
        Delay = TimeSpan.FromSeconds(1),
        BackoffType = DelayBackoffType.Exponential,
        UseJitter = true
    });

    // Per-attempt: caps a single try.
    pipeline.AddTimeout(TimeSpan.FromSeconds(3));
});

Read it outermost-to-innermost:

  • The outer 15-second timeout is the hard ceiling. No matter how the retries and backoff play out, the operation cannot exceed 15 seconds. When it fires, it cancels whatever attempt is in flight and the whole pipeline gives up.
  • The inner 3-second timeout caps each individual attempt. A single slow call is abandoned after 3 seconds so the retry can try a fresh one, instead of one hung call eating the entire budget.

Without that outer timeout, the per-attempt timeouts add up. MaxRetryAttempts = 3 means four attempts (the first try plus three retries), so four 3-second attempts plus the jittered backoff between them take roughly 15 to 18 seconds against a hung dependency, and nothing caps the total if you raise the retry count or the base delay.

The same inside/outside ordering applies to retry vs circuit breaker placement.

Per-Request: Bound What the Caller Waits On

The outbound side is only half of it. The inbound ASP.NET Core request has its own clock, and by default it's unbounded. A request that calls three slow dependencies in sequence will hold a connection for minutes.

.NET 8 added request timeouts middleware for exactly this:

using Microsoft.AspNetCore.Http.Timeouts;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRequestTimeouts(options =>
{
    options.DefaultPolicy = new RequestTimeoutPolicy
    {
        Timeout = TimeSpan.FromSeconds(20),
        TimeoutStatusCode = StatusCodes.Status504GatewayTimeout
    };
});

builder.Services.AddScoped<ReportService>();

var app = builder.Build();

app.UseRequestTimeouts();

// Override per endpoint.
app.MapGet("/reports/{id}", GenerateReport)
    .WithRequestTimeout(TimeSpan.FromSeconds(30));

app.Run();

When the policy fires, it cancels HttpContext.RequestAborted, so a handler that honors cancellation stops promptly and the client gets a 504 instead of hanging. The catch, as always with cooperative cancellation, is that your handler has to pass the token down for it to mean anything:

static async Task<IResult> GenerateReport(
    Guid id,
    HttpContext http,
    ReportService reports)
{
    // RequestAborted fires when the request timeout elapses.
    var data = await reports.BuildAsync(id, http.RequestAborted);

    return Results.Ok(data);
}

A timeout that never reaches an await that observes it does nothing. This is the same class of bug as an ignored CancellationToken anywhere else. It's also why a saturated connection pool can look like a timeout: the request is real, it's just waiting for a connection, as I cover in connection pool exhaustion timeouts. For the middleware in depth, see request timeouts in ASP.NET Core.

The Budget Model: Make the Layers Agree

The layers only behave if their numbers are consistent. One failure mode is a per-request timeout shorter than the total outbound budget: the request aborts while the pipeline still thinks it has time, and the pipeline's ceiling never matters. The opposite mistake is a per-request timeout that is missing or so long that it never bounds anything, so the caller waits as long as the slowest dependency allows.

Think of the inbound request as holding a budget that it spends on downstream calls. Each layer must fit inside the one above it:

  • Per-request (inbound) > total outbound budget > per-attempt timeout.
  • HttpClient.Timeout, when your resilience handler leaves it in place, sits above the total outbound budget so it can't cut the retries short.
  • Example that adds up: 20-second request timeout, a 15-second total budget for the outbound call, 3-second per-attempt timeouts. The request has 5 seconds of headroom for its own work, the outbound operation can never exceed 15, and no single attempt exceeds 3.

For a request that makes several downstream calls, don't give each one a full fixed timeout, or they sum past the request budget. Instead, propagate the remaining budget: derive a CancellationToken from the request that carries the time left, and let each call run against it.

static async Task<IResult> Checkout(
    HttpContext http,
    PricingClient pricing,
    InventoryClient inventory)
{
    // One budget for the whole handler, linked to the request.
    using var budget = CancellationTokenSource.CreateLinkedTokenSource(
        http.RequestAborted);
    budget.CancelAfter(TimeSpan.FromSeconds(12));

    // Both calls share the remaining time; the second inherits
    // whatever the first left behind, so they can't sum past 12s.
    var price = await pricing.QuoteAsync(budget.Token);
    var stock = await inventory.CheckAsync(budget.Token);

    return Results.Ok(new { price, stock });
}

CreateLinkedTokenSource plus CancelAfter gives you a single deadline that both the request abort and the elapsed budget can trip. The second call doesn't get a fresh clock; it inherits what's left. That's what prevents two "reasonable" 10-second timeouts from stacking into a 20-second wait.

For HTTP specifically, AddStandardResilienceHandler already ships a sane layered default (a 30-second total timeout and a 10-second per-attempt timeout, with HttpClient.Timeout disabled), and you can retune it as shown in overriding the default resilience handlers. The wider set of patterns is in building resilient cloud applications with .NET.

Summary

"Timeout" is three separate settings, and they only behave when their values agree.

  • Per-call bounds one attempt. Use a Polly per-attempt timeout inside the retry. HttpClient.Timeout wraps the whole resilience handler, retries included, and throws TaskCanceledException, so keep it above the total budget (AddStandardResilienceHandler disables it for you).
  • Total budget goes outside the retry and is the hard ceiling on the whole operation. Forget it and per-attempt timeouts stack past what you intended.
  • Per-request bounds the inbound ASP.NET Core request with the .NET 8 request timeouts middleware, cancelling RequestAborted so the caller gets a 504 instead of a hang.
  • Keep them nested: per-request > total > per-attempt, and propagate the remaining budget with a linked CancellationTokenSource so multiple downstream calls can't sum past the request's ceiling.

Frequently Asked Questions

What does HttpClient.Timeout actually cover?

HttpClient.Timeout is the total time for one SendAsync call, defaulting to 100 seconds. With the default ResponseContentRead option it covers sending the request, receiving the headers, and buffering the whole response body; with ResponseHeadersRead it stops once the headers arrive. It throws a TaskCanceledException when it fires. A resilience handler added with AddResilienceHandler runs inside that one SendAsync call, so HttpClient.Timeout caps all attempts and backoff delays together, not each attempt. AddStandardResilienceHandler sets it to infinite and lets its own timeouts decide.

Why do nested timeouts stack into long waits?

Because a per-attempt timeout multiplies by the number of attempts. A 10-second per-attempt timeout with 3 retries means 4 attempts, so the caller can wait more than 40 seconds once the backoff delays are added. If a total timeout is not placed outside the retry, the individual timeouts add up instead of being capped, which is how a "10-second timeout" turns into a wait of nearly a minute.

What is the difference between a per-attempt and a total timeout?

A per-attempt timeout caps a single try and lets the retry decide whether to attempt again. A total timeout caps the entire operation including all retries and backoff delays. You want both: the per-attempt timeout keeps one slow call from hogging the budget, and the total timeout is the hard ceiling the caller can rely on.

How do I set a request timeout in ASP.NET Core?

Use the request timeouts middleware added in .NET 8. Call AddRequestTimeouts with a default or named policy, add UseRequestTimeouts to the pipeline, and apply per-endpoint with WithRequestTimeout or the RequestTimeout attribute. When the timeout fires it cancels HttpContext.RequestAborted so your handler observes cancellation.

  • One slow downstream service can take out your entire application without returning a single error, by tying up the connections, memory, and blocked threads every other request needs. The bulkhead pattern caps how much of your capacity any single dependency can use. Here is how to build bulkheads in .NET with semaphores, Polly concurrency limiters, and partitioned HttpClients.

  • Your vendor allows 100 requests per second, and your app has no idea. It bursts, gets a wall of 429s, retries into the same wall, and eventually gets your API key throttled harder. System.Threading.RateLimiting on the outbound path, plus honoring Retry-After, keeps you inside the quota.

  • Polly v8 replaced policies with resilience pipelines: a rewritten core with allocation-free execution, built-in telemetry, and one composition model instead of PolicyWrap. Here is how the new API maps to the old one, how to register pipelines with DI, and why the order you add strategies changes what your pipeline does.

Browse all Resilience guides →
Loading comments...

Go deeper

Whenever you're ready, there are 5 ways I can help you:

  1. Learn to deploy and run your apps on a VPS with Dokploy and Tailscale. Keep administration private, automate releases, and practice restoring backups, with source code and a runbook you can reuse.

  2. Join 5,000+ students in this comprehensive course that will teach you the system I use to ship production-ready applications using Clean Architecture. Learn how to apply the best practices of modern software architecture.

  3. Join 2,800+ engineers in this in-depth course that will transform the way you build modern systems. You will learn the best practices for applying the Modular Monolith architecture in a real-world scenario.

  4. Join 1,900+ students in this course that will teach you how to build production-ready REST APIs using the latest ASP.NET Core features and best practices. It includes a fully functional UI application that we'll integrate with the REST API.

  5. Join a community of 5,000+ engineers and software architects. You will also unlock access to the source code I use in my YouTube videos, early access to future videos, and exclusive discounts for my courses.

The .NET Weekly

One practical .NET tip, every Saturday.

Join 66,000+ engineers who read it. Free, and you can unsubscribe any time.