A production playbook for a spike in API timeouts: using Application Insights end-to-end traces, dependency duration and failure metrics, runtime counters and KQL to separate your own slowness from a dependency's, then mitigating with timeouts, circuit breakers and fallbacks.
I split the request into time in my code and time in dependencies. In Application Insights, the end-to-end transaction view and a KQL query comparing request duration with the sum of its dependency durations tell me quickly: if one dependency's p95 jumped at 10 am, it's them; if dependencies are normal but requests are slow, the time is in my process. A gap before a dependency call starts means queueing inside my service: ThreadPool starvation, an exhausted connection pool or a rate limiter. dotnet-counters confirms CPU, GC and queue lengths. For a slow dependency I contain it with per-attempt timeouts, a circuit breaker, a bulkhead and a fallback; for my own code I roll back or scale while I fix it. The trade-off: aggressive timeouts protect you but turn slowness into errors, so they need fallbacks.
"A timeout spike is a question about where the time went. I start broad for a minute: is it every endpoint or a few, every instance or one, and did anything change at 10 am: a deploy, a config change, a batch job, a partner's traffic? Ten o'clock on a weekday is also when a lot of reporting jobs and business users start, so I look at load too.
Then I use traces to split the time. In Application Insights I open a few slow requests in the end-to-end transaction view. If a request took 9 seconds and 8.7 of that was one call to the pricing API, the problem is the dependency, and I check whether it's slow for everyone with a KQL query on the
dependenciestable grouped by target. If the dependency calls add up to 200 ms but the request took 9 seconds, the time is in my process, and there are two shapes: a gap before the first call starts usually means queueing (the ThreadPool, the SQL connection pool or a rate limiter), and a gap between calls means CPU work, GC or a lock.dotnet-counterstells me which: queue length, GC time, CPU andMicrosoft.Data.SqlClientpool counters.The response depends on the answer. A slow dependency gets contained: per-attempt timeouts below my own request timeout, a circuit breaker so I stop waiting on something that's failing, a bulkhead so one dependency can't consume all my capacity, and a fallback such as cached prices. My own slowness gets a rollback if it lines up with a deploy, or scale-out and load shedding while I fix it. The mistake I see is raising the timeout because things are timing out. That just turns an 8% error rate into 100% of users waiting longer."
| Step | What I do | Tool or command |
|---|---|---|
| 1. Symptom | Timeout rate up; which endpoints and instances | App Insights Failures blade, requests table |
| 2. First five minutes | Check changes at 10 am; roll back if a deploy lines up | Deployment history, App Configuration audit |
| 3. Data to collect | Request vs dependency durations; runtime counters | KQL, end-to-end transaction view, dotnet-counters |
| 4. Rule out | Each dependency by its own p95 and failure rate; CPU, GC, pool queues | KQL by target, counters |
| 5. Root cause | The slow dependency, or the queue or hot path in your process | Traces, dumps or CPU traces as needed |
| 6. Fix | Contain the dependency, or fix your path | Resilience handler, code fix |
| 7. Prevention | Timeout budget, dependency SLO alerts, dashboard | Azure Monitor alerts, workbook |
| What the trace shows | Meaning | Next step |
|---|---|---|
| One dependency span fills the request | Dependency is slow | Check its p95 for all callers; contain it |
| Gap before the first dependency call | Queueing in your process | ThreadPool and connection pool counters |
| Gaps between calls | CPU, GC or lock contention | CPU sample, GC counters |
| Many short dependency calls | N+1 or chatty calls grew with data | Batch, cache or join |
| Dependency spans missing | Context lost, or the call never started | Check propagation; check pool waits |
In a typical case the KQL shows pricing-api p95 rising from 120 ms to 9 s at 10:02 while SQL and Redis stay flat. The request timeout is 10 s and the HttpClient timeout is the default 100 s, so threads wait the full request timeout. Adding a 2 s per-attempt timeout, a circuit breaker and cached prices as a fallback drops the timeout rate from 8% to 0.3% within one deployment, with 4% of responses using cached prices until the partner recovers.
Checks that the candidate can use traces, dependency metrics and runtime counters to locate latency quickly, understands queueing inside the process, and responds with containment rather than longer timeouts.
Green flags
Red flags
request received ──► [queue: Kestrel, ThreadPool] ──► middleware ──► handler
│
┌── wait for SQL connection from pool ──► SQL query ──┤
├── Redis GET ──┤ │
└── HttpClient: DNS, connect, TLS, send, wait, read ──┘
▼
serialise response ──► send
Application Insights (or any OpenTelemetry backend) records the request span and child dependency spans. Anything not covered by a child span is time in your process: queueing, CPU, GC, locks or waiting for a pooled connection (the SQL dependency span starts when the command runs, not when you ask for a connection).
Compare request duration with dependency time per operation, and look at each dependency's percentiles over time. Group by target (host or database) so one slow partner stands out. Join on operation_Id to see the gap per request.
HttpClient.Timeout defaults to 100 seconds. If your own request timeout (at the gateway or client) is 10 seconds, the caller gives up long before your code does, and your threads, sockets and connections stay busy for work nobody is waiting for. Each layer's timeout should be shorter than the one above it, and cancellation should flow down via CancellationToken (HttpContext.RequestAborted).
Microsoft.Extensions.Http.Resilience gives you AddStandardResilienceHandler(), built on Polly v8. In order, it applies a rate limiter, a total request timeout (default 30 s), retry (exponential backoff with jitter, three attempts), a circuit breaker, and a per-attempt timeout (default 10 s). You tune those to your own budget; the defaults are a starting point, not an answer.
Without isolation, one slow dependency eats every thread or connection and everything else times out too: the cascading failure. A bulkhead (a concurrency limiter per dependency) caps how much of your capacity one dependency can hold.
System.Runtime: cpu-usage, time-in-gc, threadpool-queue-length.Microsoft.AspNetCore.Hosting: current requests, request rate.Microsoft.Data.SqlClient.EventSource (or the Microsoft.Data.SqlClient metrics in newer versions): active and pooled connections, connections waiting.System.Net.Http: current requests, requests queued for a connection.target in 5-minute bins.AddStandardResilienceHandler() with a 1 s per-attempt timeout and a fallback, and compare error rates and latency with the stub slow.dotnet-counters monitor --counters System.Net.Http during the test and watch queued requests.Containing a slow dependency with explicit budgets, and the KQL to find it.
// Program.cs: per-dependency resilience with budgets below the request timeout.
using Microsoft.Extensions.Http.Resilience;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient<PricingClient>(c => c.BaseAddress = new("https://pricing.internal/"))
.AddStandardResilienceHandler(o =>
{
o.AttemptTimeout.Timeout = TimeSpan.FromSeconds(2); // one try never waits longer than 2 s
o.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(5); // all retries together, under the 10 s API budget
o.CircuitBreaker.SamplingDuration = TimeSpan.FromSeconds(30);
o.CircuitBreaker.FailureRatio = 0.2; // open after 20% failures in 30 s
o.Retry.MaxRetryAttempts = 2;
});
builder.Services.AddRequestTimeouts(o => o.DefaultPolicy = new() { Timeout = TimeSpan.FromSeconds(10) });
var app = builder.Build();
app.UseRequestTimeouts();
app.Run();
// A fallback so a broken dependency degrades instead of failing the request.
namespace Shop.Pricing;
using Microsoft.Extensions.Caching.Hybrid;
using Polly.CircuitBreaker;
public sealed record Price(string Sku, decimal Amount, bool IsCached);
public sealed class PricingClient(HttpClient http, HybridCache cache, ILogger<PricingClient> log)
{
public async Task<Price> GetAsync(string sku, CancellationToken ct)
{
try
{
var price = await http.GetFromJsonAsync<Price>($"prices/{Uri.EscapeDataString(sku)}", ct)
?? throw new InvalidOperationException("Empty price");
await cache.SetAsync($"price:{sku}", price, cancellationToken: ct);
return price;
}
catch (Exception ex) when (ex is TimeoutException or HttpRequestException or BrokenCircuitException
|| (ex is OperationCanceledException && !ct.IsCancellationRequested))
{
log.LogWarning(ex, "Pricing unavailable for {Sku}; using cached price", sku);
var cached = await cache.GetOrCreateAsync<Price?>($"price:{sku}", _ => ValueTask.FromResult<Price?>(null), cancellationToken: ct);
return cached is null ? throw new PriceUnavailableException(sku, ex) : cached with { IsCached = true };
}
}
}
public sealed class PriceUnavailableException(string sku, Exception inner)
: Exception($"No live or cached price for {sku}", inner);
// KQL (Application Insights): which dependency got slow, and when?
dependencies
| where timestamp > ago(2h)
| summarize p95 = percentile(duration, 95), failures = countif(success == false), calls = count()
by target, bin(timestamp, 5m)
| order by timestamp asc
// Gap between request time and dependency time per request
requests
| where timestamp > ago(1h) and duration > 5000
| join kind=leftouter (dependencies | summarize depTime = sum(duration) by operation_Id) on operation_Id
| project timestamp, name, duration, depTime, gap = duration - coalesce(depTime, 0.0), cloud_RoleInstance
| order by gap desc
HttpClient.Timeout at the default 100 s. Why it is wrong: Your code keeps waiting long after the caller has gone. Instead: Set per-attempt and total timeouts below your own request budget.The senior skill here is making the question "me or them?" answerable in under five minutes, before the incident. That means traces with dependency spans for every outbound call, a dashboard that shows dependency time per request, and per-dependency alerts. With that in place the incident is a lookup, not an investigation.
The second senior point is the timeout budget. Timeouts are a design decision: each layer shorter than the one above, cancellation flowing down, retries counted inside the total. Without a budget, every layer waits on every other and a slow partner becomes your outage.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Per-attempt timeout + retry | Transient slowness, idempotent calls | Extra load on retries | Non-idempotent calls without idempotency keys |
| Circuit breaker | Dependency failing broadly | Fast failures during the open period | Very low-traffic calls (not enough samples) |
| Bulkhead (concurrency limit) | One dependency must not eat all capacity | Rejections when the limit is hit | When the dependency is the whole request |
| Fallback (cached or default data) | Stale data is acceptable | Users see older data; must be labelled | Money movement, permissions |
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.
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.
I'd measure first: a KQL query for requests whose operation_ParentId points at a span that doesn't exist, grouped by service, tells me which hop breaks. Then I check the wire: does the caller send traceparent, and does the callee receive it? That splits the causes:
HttpClient with propagation turned off, or an API gateway or proxy that strips or rewrites it (B3 vs W3C).AddSource, or exports to a different backend.Channel<T>, a queue or a new thread loses Activity.Current, so you pass the ActivityContext yourself.The trade-off: fixing each hop by hand is quick; preventing it needs a shared template and a propagation test.
How to tell it (STAR)
**S:** At [company], our product API's timeout rate jumped from 0.1% to 8% at 10 am on a weekday, with no deploy. **T:** I needed to find out whether it was us or a dependency and stop the errors. **A:** I opened slow traces in Application Insights and saw one partner call taking 9 seconds; a KQL query by dependency confirmed the pricing partner's p95 had gone from 120 ms to 9 s. Our HttpClient still had the default 100-second timeout, so connections piled up. I switched on cached prices with a feature flag, then shipped a 2-second attempt timeout, a circuit breaker and a cached-price fallback. **R:** The timeout rate dropped to [0.3%] within the hour, [4%] of pages showed cached prices until the partner recovered, and the fault-injection test has since caught [two] dependencies with no timeout.
Last updated 23 Nov 2026.