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

📚 Interview question

Your API's timeout rate jumps from 0.1% to 8% at 10 am on a weekday. Your service calls SQL Server, Redis and two downstream HTTP APIs. How do you work out quickly whether the slowness is in your own code or in a dependency, using distributed traces, dependency metrics and runtime counters, and what do you do about it in each case?

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.

Mid-Level Debugging Intermediate application-insights distributed-tracing kql production resilience timeouts

🎯 Key points

  • Start broad: which endpoints, which instances, since when, and did anything deploy or change at 10 am
  • Compare request duration with the sum of dependency durations: if dependencies explain the time, it's them; if there's a gap, it's you
  • Dependency gap before a call starts points at queueing in your process (ThreadPool, connection pool, rate limiter)
  • Dependency metrics by target: p95/p99 duration and failure rate per dependency in KQL, never averages
  • Runtime counters rule your process in or out: CPU, GC time, ThreadPool queue, connection pool waits
  • Mitigate a slow dependency with per-attempt timeouts, a circuit breaker, a bulkhead and a fallback (AddStandardResilienceHandler)
  • Mitigate your own slowness with rollback, scale-out or shedding, then fix the hot path
  • Prevent: a written timeout budget (e.g. 10 s request, 5 s total and 2 s per attempt to a dependency) and per-dependency SLO alerts (e.g. p95 under 300 ms, failures under 1%)

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 dependencies table 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-counters tells me which: queue length, GC time, CPU and Microsoft.Data.SqlClient pool 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."


The playbook, in order

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

Reading the trace shape

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

Production example

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.

🔍 What the interviewer is checking

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

  • Checks what changed first, then splits request time into process time and dependency time
  • Recognises a gap before the first call as in-process queueing
  • Writes or describes KQL by dependency target and percentile
  • Uses per-attempt timeouts, breakers, bulkheads and fallbacks, with a timeout budget

Red flags

  • "Increase the timeout"
  • Relies on averages or a single trace
  • Retries everything with no breaker

📚 Learn in depth

1. Where the time in a request goes

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).

2. The KQL that answers it

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.

3. Why default timeouts make things worse

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).

4. The standard resilience handler

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.

5. Bulkheads

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.

6. Runtime counters that separate 'me' from 'them'

  • 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.

Try it yourself

  1. Build an API that calls a stub dependency; make the stub sleep 5 s on a toggle and watch the end-to-end view in Application Insights (or the Aspire dashboard locally).
  2. Write a KQL query that shows p95 duration per dependency target in 5-minute bins.
  3. Add AddStandardResilienceHandler() with a 1 s per-attempt timeout and a fallback, and compare error rates and latency with the stub slow.
  4. Run dotnet-counters monitor --counters System.Net.Http during the test and watch queued requests.
  5. Starve the ThreadPool with a blocking call and see the gap appear before the first dependency span.

💻 Code

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

⚠ Common mistakes

  • Mistake: Raising the timeout because requests time out. Why it is wrong: Users wait longer, threads and connections are held longer, and the error rate usually rises. Instead: Find where the time goes; contain slow dependencies with shorter per-attempt timeouts and fallbacks.
  • Mistake: Leaving 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.
  • Mistake: Looking at averages. Why it is wrong: If 92% of requests take 100 ms and 8% take 10 s, the mean is about 0.9 s, which looks like 'a bit slow' while one user in twelve is failing. Instead: Use p95/p99 and failure counts per dependency; the p95 here jumps straight to 10 s.
  • Mistake: Assuming the dependency is slow because its span is long. Why it is wrong: Client-side queueing (waiting for a connection or a pool thread) can inflate spans. Instead: Check the dependency's own metrics and whether other callers see it too.
  • Mistake: Retrying without a circuit breaker. Why it is wrong: Each retry adds load to a dependency that is already failing; three attempts per request can triple its traffic just as it struggles, delaying recovery and holding your threads and connections, so the failure cascades into your service. Instead: Limit retries, add jitter, and use a breaker that fails fast once the failure ratio crosses a threshold, then probes for recovery.
  • Mistake: Ignoring missing spans. Why it is wrong: A gap might be lost context, not queueing. Instead: Confirm propagation works before concluding.
  • Mistake: Not checking what changed at the time of the spike. Why it is wrong: Most incidents follow a change. Instead: Check deploys, config, feature flags and partner traffic first.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions timeouts at several layers Why: Checks end-to-end timeout and cancellation design
    How to 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.

  2. When: Candidate mentions circuit breakers or bulkheads Why: Checks handling of a cascading failure from a slow dependency
    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 relies on traces but some spans are missing Why: Checks how to find where trace context is lost
    How to answer

    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:

    • Header never sent: a hand-built HttpClient with propagation turned off, or an API gateway or proxy that strips or rewrites it (B3 vs W3C).
    • Sent but no span: the callee is missing instrumentation, AddSource, or exports to a different backend.
    • Orphan spans: a service uses a non-parent-based sampler, or ingestion sampling dropped the parent.
    • Lost in-process: work handed through Channel<T>, a queue or a new thread loses Activity.Current, so you pass the ActivityContext yourself.
    • Messaging: nobody injects context into Service Bus messages.

    The trade-off: fixing each hop by hand is quick; preventing it needs a shared template and a propagation test.

🛠 Real-world problems: how you handle them

Timeouts at 10 am caused by a slow pricing partner
Situation
A product API on [Azure App Service, six instances] calling Azure SQL, Azure Managed Redis and two partner HTTP APIs, [about 900 requests/s] at mid-morning peak. The API's request budget was 10 s.
Signals
An Azure Monitor alert on failed requests fired at [10:04]: timeout rate from [0.1%] to [8%] on the product detail and basket endpoints. CPU was [35%]. Support reported slow product pages.
Investigation
Checked deployment history and App Configuration: no changes. Opened slow requests in the end-to-end transaction view: one call to `pricing-api` filled 9 of 10 seconds. A KQL query by dependency target showed `pricing-api` p95 from [120 ms] to [9 s] at 10:02, with SQL and Redis flat. `dotnet-counters` showed `System.Net.Http` requests queued for connections growing, because the default 100 s timeout held connections open.
Resolution
Immediate: turned on a feature flag that served cached prices for the product page and contacted the partner. Real fix: per-attempt timeout of 2 s, total timeout of 5 s, a circuit breaker and a cached-price fallback through `AddStandardResilienceHandler`.
Prevention
A documented timeout budget per layer, a per-dependency p95 alert, a workbook showing dependency time per request, and a quarterly fault-injection test that slows each dependency in staging.

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.

↩ Usually asked after

More in Debugging Production Issues

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me