📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you design timeouts end to end for an ASP.NET Core API that calls other services and SQL Server? Explain HttpClient's timeout vs a per-attempt timeout, the request timeouts middleware, database command timeouts, how the layers should relate to each other, and how cancellation and deadlines propagate through the call chain.

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.

Mid-Level Theory Intermediate aspnet-core cancellation httpclient resilience timeouts web-api

🎯 Key points

  • Every outbound call needs an explicit timeout; HttpClient.Timeout is 100 s unless you set it, far too long for a request path
  • Standard resilience handler: 10 s attempt timeout inside retries, 30 s total timeout outside
  • Request timeouts middleware (.NET 8+): AddRequestTimeouts, WithRequestTimeout, cancels HttpContext.RequestAborted, 504 by default
  • SqlCommand / EF Core CommandTimeout defaults to 30 s; pass the CancellationToken so the query is cancelled
  • Budgets nest: attempts x attempt timeout + backoff delays must fit in the remaining inbound request budget
  • Infrastructure timeouts too: App Service 230 s, Front Door origin timeout, APIM forward-request
  • Size from data: attempt timeout around 1.5x the dependency's measured p99, alert on timeout rate
  • Propagate one CancellationToken; HTTP has no standard deadline header, gRPC does (grpc-timeout)

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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) cancels HttpContext.RequestAborted after the limit and returns 504 if the endpoint throws OperationCanceledException. For outbound HTTP, I don't rely on HttpClient.Timeout, which defaults to 100 seconds and covers all retries together; I use AddStandardResilienceHandler, 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 CancellationToken goes from the endpoint to every call."


The layers and their defaults

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

How the numbers should relate

client 15 s > gateway 12 s > endpoint 10 s > (attempt 3 s x 2 attempts + backoff) ; SQL 5 s

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate sees timeouts as a coordinated budget with cancellation, not isolated settings.

Green flags

  • Knows HttpClient's 100 s default and why it is dangerous
  • Distinguishes attempt and total timeouts and their position around retries
  • Mentions the request timeouts middleware and that it only cancels a token
  • Passes CancellationToken to EF Core and HttpClient
  • Nests timeouts inward and knows infrastructure limits such as App Service's 230 s

Red flags

  • "Just increase the timeout"
  • Believes a timeout means the operation did not happen
  • No mention of cancellation

📚 Learn in depth

1. Why timeouts exist

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.

2. Inbound: the request timeouts middleware

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.

3. Outbound: the resilience pipeline

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.

4. SQL Server

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.

5. Deadline propagation

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.

6. Timeouts and side effects

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.

Try it yourself

  1. Add the request timeouts middleware with a 2 s policy and an endpoint that does await Task.Delay(5000, ct); call it with curl -i and see the 504.
  2. Remove ct from Task.Delay and observe that the work continues after the timeout.
  3. Point an HttpClient with AddStandardResilienceHandler at a delay endpoint and log each attempt; change the attempt timeout and watch the count change.
  4. Run WAITFOR DELAY '00:00:20' through EF Core with CommandTimeout(5) and capture the SqlException number (-2).
  5. Cancel that request from the client and check sys.dm_exec_requests to confirm the query was cancelled.

💻 Code

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);
}

⚠ Common mistakes

  • Mistake: Relying on 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.
  • Mistake: Configuring retries without a per-attempt timeout. Why it is wrong: the first hung attempt consumes the whole budget, so the retry never happens. Instead: put an attempt timeout inside the retry, as the standard resilience handler does.
  • Mistake: Forgetting backoff when sizing the budget. Why it is wrong: 3 attempts x 3 s plus exponential backoff of 0.5 s and 1 s is 10.5 s, which overruns a 10 s endpoint budget. Instead: add attempt timeouts and backoff delays together and keep the sum under the inbound budget.
  • Mistake: Leaving 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.
  • Mistake: Not passing the 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.
  • Mistake: Inner timeouts longer than outer ones. Why it is wrong: the outer layer reports failure while the inner layer may still complete a write, so client and server disagree. Instead: nest timeouts so each layer fits inside its caller.
  • Mistake: Picking numbers by feel. Why it is wrong: too tight and healthy calls fail (an HTTP dependency with a 900 ms p99 behind a 1 s timeout fails on every slow GC pause); too loose and the timeout never protects you. Instead: read p99 latency per dependency from Application Insights or Query Store for SQL, set timeouts around 1.5x p99, and verify with a fault-injection test that delays the dependency.
  • Mistake: Raising timeouts to fix slow operations. Why it is wrong: App Service cuts requests at 230 s anyway, and long requests hog resources. Instead: make long work asynchronous: 202 Accepted plus a status resource.
  • Mistake: Treating a timeout as a definite failure. Why it is wrong: the operation may have succeeded. Instead: make writes idempotent and reconcile.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate describes the standard resilience handler's pipeline order Why: Checks where the circuit breaker sits relative to retry and attempt timeout
    How to answer

    A circuit breaker stops calling a dependency that is clearly failing, so you fail fast instead of wasting threads and sockets on timeouts.

    • Closed: calls flow and outcomes are sampled.
    • Open: when failures pass a threshold, calls are rejected straight away with BrokenCircuitException for the break duration.
    • Half-open: a trial call decides whether to close the circuit or open it again.

    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.

  2. When: Candidate mentions cascading failure from a slow dependency Why: Checks they can apply timeouts, bulkheads and fallbacks in an incident
    How to answer

    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:

    • Timeouts: 2 s per attempt, 5 s total.
    • One jittered retry, outside a circuit breaker tuned to the traffic.
    • A bulkhead: a concurrency limit on the shipping client.
    • No external calls inside DB transactions.
    • Liveness checks that don't include the third party.

    The trade-off is a slightly degraded feature against a whole service going down.

  3. When: Candidate says long operations should not just get longer timeouts Why: Checks the 202 Accepted plus status resource pattern
    How to answer

    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.

🛠 Real-world problems: how you handle them

A slow pricing service takes the whole quote API down
Situation
A [quote API] on [4] App Service instances serves the [mobile app], calling an internal pricing service with a default HttpClient and SQL Server. The mobile app gives up after [20 s].
Signals
Application Insights shows pricing dependency duration jumping to [60 s], API p99 above [90 s], a rising count of 504s from Front Door, SQL connection pool timeouts, and thread pool queue length climbing in dotnet-counters.
Investigation
Looked at the end-to-end transaction view in Application Insights to see where time was spent, compared dependency durations with request durations, ran `dotnet-counters monitor` for ThreadPool queue length and connection counts, and checked the HttpClient registration: no resilience handler, so the 100 s default applied.
Resolution
Immediately reduced replicas' traffic to pricing via a feature flag returning cached prices. Then added the standard resilience handler with a 2 s attempt and 8 s total timeout, the request timeouts middleware at 10 s, a 5 s SQL command timeout, and passed the cancellation token through every call.
Prevention
Documented the timeout budget per endpoint in an ADR, added a chaos test that injects a 30 s delay into pricing in the test environment, and alerted on dependency timeouts per minute and on requests exceeding the 10 s budget.

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.

↩ Usually asked after

More in API Reliability

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me