End-to-end timeout budgets in .NET 10: HttpClient.Timeout vs per-attempt and total timeouts in the standard resilience handler, the request timeouts middleware, SQL command timeouts, infrastructure timeouts, and propagating cancellation and deadlines.
A timeout is a budget, and budgets must shrink as you go inward. The client's timeout is the largest; the API's own request timeout (the .NET 8+ request timeouts middleware, which cancels HttpContext.RequestAborted) is smaller; each outbound call gets a per-attempt timeout inside its retries and a total timeout outside them (the standard resilience handler defaults to 10 s and 30 s, while raw HttpClient.Timeout is 100 s); SQL gets a command timeout (30 s by default) plus the CancellationToken. One token flows from the request to every call so abandoned work stops. The trade-off: short timeouts fail fast and protect threads but cut off legitimately slow work, so slow operations should become async (202 plus a status resource) rather than get longer timeouts.
"I treat timeouts as a budget that has to fit inside the caller's budget. If the mobile app gives up after 15 seconds, there is no point in my API waiting 100 seconds for a downstream service, because nobody is listening for the answer and I'm holding a connection, memory and maybe a database lock for nothing. So the numbers shrink inward: the client waits longest, my endpoint has a request timeout a bit under that, and each dependency call has a per-attempt timeout times the number of attempts that fits inside my endpoint's budget.
In .NET 10 there are concrete tools for each layer. For inbound requests, the request timeouts middleware (
AddRequestTimeouts,UseRequestTimeouts,WithRequestTimeout) cancelsHttpContext.RequestAbortedafter the limit and returns 504 if the endpoint throwsOperationCanceledException. For outbound HTTP, I don't rely onHttpClient.Timeout, which defaults to 100 seconds and covers all retries together; I useAddStandardResilienceHandler, which puts a 10-second attempt timeout inside the retry and a 30-second total timeout outside it, and I tune both. For SQL, the command timeout defaults to 30 seconds, and I always pass the cancellation token so a cancelled request also cancels the query on the server.The mistake I see is setting timeouts in isolation: a 30-second SQL timeout behind a 10-second HTTP timeout behind a 5-second gateway. The outer layer gives up and the inner layers carry on working, sometimes completing a write the client thinks failed. Timeouts only work if cancellation propagates, so one
CancellationTokengoes from the endpoint to every call."
| Layer | Setting | Default | Notes |
|---|---|---|---|
| Browser / mobile client | Fetch/HttpClient timeout | Varies (often none or 60-100 s) | Agree a number with client teams |
| Azure Front Door | Origin response timeout | 60 s (configurable) | Returns 504 to the client |
| Azure API Management | forward-request timeout |
300 s | Set per API |
| App Service front end | Request timeout | 230 s, not configurable | Long operations must be async |
| Kestrel | RequestHeadersTimeout, KeepAliveTimeout |
30 s, 130 s | Protect against slow clients, not slow handlers |
| Request timeouts middleware | RequestTimeoutPolicy.Timeout |
None until configured | Not enforced when a debugger is attached |
| HttpClient | HttpClient.Timeout |
100 s | Total for the call, including handler retries |
| Standard resilience handler | Attempt / total timeout | 10 s / 30 s | Attempt timeout inside retry, total outside |
| SqlClient / EF Core | CommandTimeout |
30 s | Plus Connect Timeout 15 s |
client 15 s > gateway 12 s > endpoint 10 s > (attempt 3 s x 2 attempts + backoff) ; SQL 5 s
A [quote API] had a 100-second default HttpClient timeout towards a pricing service. When pricing slowed to 60 s, threads and connections piled up and the API's own p99 went past 90 s, although the mobile app gave up at 20 s. Setting a 2 s attempt / 8 s total budget and a 10 s request timeout dropped the API's p99 during the next pricing slowdown to 8.5 s and kept the rest of the API healthy.
Checks whether the candidate sees timeouts as a coordinated budget with cancellation, not isolated settings.
Green flags
Red flags
A request without a timeout can wait forever on a dead TCP connection, a stuck lock or an overloaded dependency. Each waiting request holds resources: a Kestrel connection, async state, pooled DB connections (default pool size 100), sometimes locks. When a dependency slows, these pile up until the service itself fails: a cascading failure. A timeout converts "wait forever" into a fast, handleable error.
builder.Services.AddRequestTimeouts(o =>
{
o.DefaultPolicy = new RequestTimeoutPolicy { Timeout = TimeSpan.FromSeconds(10) };
o.AddPolicy("reports", TimeSpan.FromSeconds(30));
});
app.UseRequestTimeouts();
It does not abort the thread: it cancels the token in HttpContext.RequestAborted. Code that ignores the token keeps running. If the endpoint lets the resulting OperationCanceledException escape, the middleware writes the TimeoutStatusCode (504 by default). It is skipped while a debugger is attached so breakpoints don't trip it.
HttpClient.Timeout (100 s default, outermost)
-> standard resilience handler
rate limiter (1,000 concurrent)
total timeout (30 s)
retry (3 retries, exponential + jitter, 2 s base)
circuit breaker
attempt timeout (10 s)
-> SocketsHttpHandler -> network
The attempt timeout bounds a single try; the total timeout bounds the whole call including backoff. If HttpClient.Timeout is shorter than the total timeout, it wins, so raise it (or set it to Timeout.InfiniteTimeSpan) when the pipeline owns timeouts.
SqlCommand.CommandTimeout (30 s) is enforced by the client, which sends an attention signal to cancel the batch. Passing a CancellationToken to ExecuteReaderAsync / EF Core's ToListAsync(ct) does the same when the request is cancelled. Without it, a cancelled HTTP request leaves the query running on the server, still holding locks and a pooled connection.
A fixed timeout per hop wastes budget: if the gateway has used 8 of 10 seconds, the next hop shouldn't start a fresh 10-second wait. gRPC sends the remaining time in the grpc-timeout header and the server enforces it (ServerCallContext.Deadline). HTTP has no standard equivalent; teams either pass a custom header (remaining milliseconds) and link a CancellationTokenSource.CancelAfter from it, or simply size per-hop timeouts so they nest.
A timeout tells you you stopped waiting, not that the operation failed. A POST that timed out may have committed. That is why timeouts and retries need idempotency keys, and why a write's own timeout should be longer than its dependency's, never shorter.
await Task.Delay(5000, ct); call it with curl -i and see the 504.ct from Task.Delay and observe that the work continues after the timeout.AddStandardResilienceHandler at a delay endpoint and log each attempt; change the attempt timeout and watch the count change.WAITFOR DELAY '00:00:20' through EF Core with CommandTimeout(5) and capture the SqlException number (-2).sys.dm_exec_requests to confirm the query was cancelled.One budget, nested inward, with a single cancellation token flowing through:
using Microsoft.AspNetCore.Http.Timeouts;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Inbound: 10 s by default for the endpoint.
builder.Services.AddRequestTimeouts(o =>
o.DefaultPolicy = new RequestTimeoutPolicy { Timeout = TimeSpan.FromSeconds(10) });
// Outbound HTTP: 3 s per attempt, 8 s total including retries and backoff.
builder.Services.AddHttpClient<PricingClient>(c =>
{
c.BaseAddress = new Uri("https://pricing.internal");
c.Timeout = Timeout.InfiniteTimeSpan; // let the resilience pipeline own timeouts
})
.AddStandardResilienceHandler(o =>
{
o.AttemptTimeout.Timeout = TimeSpan.FromSeconds(3);
o.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(8);
o.CircuitBreaker.SamplingDuration = TimeSpan.FromSeconds(30); // must be >= 2 x attempt timeout
});
// SQL: 5 s per command.
builder.Services.AddDbContext<QuotesDb>(o => o.UseSqlServer(
builder.Configuration.GetConnectionString("Quotes"),
sql => sql.CommandTimeout(5)));
var app = builder.Build();
app.UseRequestTimeouts();
app.MapGet("/quotes/{id:int}", async (int id, QuotesDb db, PricingClient pricing, CancellationToken ct) =>
{
// ct is HttpContext.RequestAborted: cancelled by client disconnect OR the 10 s request timeout.
var quote = await db.Quotes.AsNoTracking().FirstOrDefaultAsync(q => q.Id == id, ct);
if (quote is null) return Results.NotFound();
var price = await pricing.GetPriceAsync(quote.ProductCode, ct);
return Results.Ok(quote with { Price = price });
});
app.Run();
public sealed record Quote(int Id, string ProductCode, decimal? Price);
public sealed class QuotesDb(DbContextOptions<QuotesDb> options) : DbContext(options)
{
public DbSet<Quote> Quotes => Set<Quote>();
}
public sealed class PricingClient(HttpClient http)
{
public async Task<decimal> GetPriceAsync(string productCode, CancellationToken ct) =>
await http.GetFromJsonAsync<decimal>($"/prices/{Uri.EscapeDataString(productCode)}", ct);
}
HttpClient.Timeout's 100 s default. Why it is wrong: the caller gave up long ago, while your API holds connections and threads. Instead: set explicit attempt and total timeouts sized to the endpoint's budget.HttpClient.Timeout shorter than the resilience total timeout. Why it is wrong: the client times out first and you get TaskCanceledException without the retries you configured. Instead: make HttpClient.Timeout larger or infinite when the pipeline owns timeouts.CancellationToken to EF Core and HttpClient calls. Why it is wrong: the request timeout fires but queries and downstream calls keep running. Instead: thread ct through every async call.The question I ask is "what is the user's patience?" and I work backwards from there. A checkout click might have a 10-second budget; a nightly batch call might have 5 minutes. Once the outer number is fixed, everything inside is arithmetic: attempts x attempt timeout + backoff must fit in the endpoint budget, and the endpoint must fit inside the gateway and the client. I write those numbers in one place (an ADR or the service's resilience config) because scattered defaults are how a 100-second timeout ends up behind a 15-second client.
Measure to set them: take the dependency's p99 from Application Insights dependency telemetry, set the attempt timeout a little above it (say 1.5x p99), and alert on timeout counts. A timeout that fires on 5% of calls is too tight; one that never fires during an incident is too loose.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Fixed per-hop timeouts | Most services, shallow call chains | Wasted budget on deep chains | Chains of 4+ hops |
| Deadline propagation (gRPC deadlines, custom header) | Deep or fan-out chains | Every service must honour it | Mixed or third-party services |
| Async operation (202 + status) | Work longer than a few seconds | More endpoints and state | Interactive calls under ~2 s |
A circuit breaker stops calling a dependency that is clearly failing, so you fail fast instead of wasting threads and sockets on timeouts.
BrokenCircuitException for the break duration.In Polly v8 it opens when the failure ratio (default 10%) is exceeded over a 30 s sampling window with at least 100 calls, and it breaks for 5 s. AddStandardResilienceHandler puts it inside the retry (each attempt counts, and an open circuit stops retries) and outside the 10 s attempt timeout (a hung call counts as a failure).
Pair it with a fallback and alert when it opens. The trade-off is protection and fast failure against rejecting some calls that would have succeeded.
Unrelated requests failing means the slow API exhausted a shared resource: usually database connections held while waiting, sockets, or thread-pool threads (from sync-over-async).
Diagnose: Application Insights dependency durations, then dotnet-counters for the thread pool, SqlClient pool and HTTP connections, then dotnet-dump to see what requests are waiting on. Look for the 100 s HttpClient default timeout multiplied by retries.
Mitigate: a feature flag that switches to a fallback (flat-rate shipping).
Fix:
The trade-off is a slightly degraded feature against a whole service going down.
Treat state transitions with business rules as commands: POST /orders/{id}/cancellation (a sub-resource, or /cancel if you prefer verbs for actions) makes intent explicit, lets you validate and authorise that transition, and returns 409 Conflict when it isn't allowed. PATCH {"status":"Cancelled"} looks RESTful but hides intent and invites invalid transitions.
For long-running work, use the asynchronous request-reply pattern: return 202 Accepted with a Location (or Operation-Location) pointing at a status resource and a Retry-After header; a background worker does the job and updates the status (Running, Succeeded, Failed), and the finished status links to the result. The trade-off is extra state and polling versus holding HTTP requests open and hitting gateway timeouts.
How to tell it (STAR)
**S:** At [company], our pricing service slowed to about [60 seconds] a call, and within minutes the whole [quote API] was failing, even endpoints that never called pricing. **T:** I needed to stop the cascade and make sure a slow dependency couldn't do that again. **A:** In Application Insights I saw requests waiting the full 100-second HttpClient default while the app had given up at [20 seconds]. I switched to cached prices behind a flag, then set a timeout budget: 10 seconds per request, 2 seconds per pricing attempt with 8 seconds total, 5 seconds per SQL command, with one cancellation token through the lot. **R:** In the next pricing slowdown the API's p99 stayed around [8.5 seconds] and the other endpoints were unaffected.
Last updated 23 Nov 2026.