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

📚 Interview question

A third-party shipping-rates API starts taking 30 seconds instead of 200 ms. Within minutes your checkout API is timing out for every user, including requests that never call that API. How do you diagnose the cascade, and how do you fix it with timeouts, retry, a circuit breaker, a bulkhead and a fallback?

Real-world cascading failure: diagnosing with Application Insights dependency telemetry, dotnet-counters (thread pool, SqlClient pool, HTTP connections) and dotnet-dump; root causes (HttpClient 100 s default timeout, retries multiplying load, DB connections held across the external call, health checks including the dependency); mitigation with a feature flag; the real fix with attempt and total timeouts, a single jittered retry, a tuned circuit breaker, a concurrency-limit bulkhead, a flat-rate fallback, moving the call out of the transaction, and chaos testing.

Senior RealWorldScenario Advanced bulkhead circuit-breaker design-patterns incident-response polly resilience

🎯 Key points

  • A cascade means a slow dependency exhausted a shared resource, so unrelated requests fail too: DB connection pool (requests holding connections/transactions while waiting), sockets to a host, request slots, or thread-pool threads when there is sync-over-async (.Result) blocking
  • Diagnose with Application Insights dependency duration and failure maps, dotnet-counters (ThreadPool queue length, SqlClient connections, System.Net.Http connections), and dotnet-dump (dumpasync) for what requests are waiting on
  • HttpClient's default Timeout is 100 s; with 3 retries one request can wait minutes and hold resources the whole time
  • Mitigate first: feature flag to skip the dependency or use a fallback, then fix properly
  • Timeouts: per-attempt (2 s) inside a total budget (5 s) so permits and connections are released quickly
  • Retry at most once with jitter, outside a circuit breaker tuned to the dependency's traffic (default MinimumThroughput 100 may never be reached) so it opens within seconds
  • Bulkhead: a concurrency limiter on the shipping client so it can only use its own compartment; never hold DB connections or transactions across the external call
  • Fallback: cached or flat-rate shipping flagged for review; health checks must not include the third party in liveness, or pods restart in a loop

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"The clue is in 'including requests that never call that API'. A slow dependency on its own should only slow the requests that use it; if everything fails, the slow calls have exhausted something shared. So my first question is: what are those requests holding while they wait? In practice it's database connections held inside a transaction, a connection limit to a host, thread-pool threads if there's a .Result somewhere, or plain request capacity. I'd open Application Insights and look at the dependency map: the shipping dependency at 30 seconds, then SQL failures with 'timeout expired prior to obtaining a connection from the pool' across every endpoint. Then dotnet-counters on a live instance: SqlClient active connections pinned at the pool maximum of 100, ThreadPool queue length growing if there's blocking, and HTTP connections to the shipping host climbing. A dotnet-dump of async state machines shows hundreds of requests awaiting the shipping client. Then I'd read the code and config: the default HttpClient.Timeout of 100 seconds, a retry of three, and the call made inside the order transaction.

For example, at [company] we [hit exactly this during a carrier outage]: [checkout was down for [n] minutes]. The first move was mitigation, not a fix: I [flipped a feature flag to flat-rate shipping], which [restored checkout within [n] minutes]. Then I fixed it properly in layers. I moved the shipping call out of the transaction, so a slow carrier can't hold database connections. I set a 2-second attempt timeout and a 5-second total budget, one retry with jitter, a circuit breaker with thresholds suited to our traffic so it opens within seconds, and a concurrency limit of [30] on the shipping client as a bulkhead. When any of those reject, the client returns the cached rate for that postcode zone or a flat rate, flagged so the warehouse can reconcile. I also found our liveness probe called the carrier, so Kubernetes was restarting healthy pods, which made it worse; I moved that to a readiness or diagnostic check. Finally, I [added a chaos test that slows the carrier stub to 30 seconds and asserts checkout p95 stays under a second], and [the next carrier outage cost us nothing but [n] flat-rate orders].

The lesson I take from cascades is that resilience is about resource boundaries: every external call needs a time limit, a concurrency limit and an answer for when it fails."


Diagnosis checklist

Question Tool What it shows
Which dependency is slow? Application Insights application map, dependency durations Shipping p95 30 s
Why are unrelated endpoints failing? Application Insights failures, exception messages SQL pool timeouts across all endpoints
What's exhausted? dotnet-counters monitor (System.Runtime, Microsoft.Data.SqlClient.EventSource, System.Net.Http) SQL connections at 100, HTTP connections climbing, ThreadPool queue
What are requests waiting on? dotnet-dump analyze + dumpasync Hundreds of awaits on the shipping client inside a transaction
Why so long? Code/config review 100 s default timeout x retries; call inside transaction
Why are pods restarting? Kubernetes events, probe config Liveness probe calls the carrier

The layered fix

Layer Setting Effect
Architecture Shipping call outside the DB transaction DB pool no longer shared with the carrier
Attempt timeout 2 s Hung calls end quickly and count as failures
Total timeout 5 s User never waits longer than the budget
Retry 1, jittered Survives blips without multiplying load
Circuit breaker Thresholds sized to traffic Fails fast during sustained outage
Bulkhead 30 concurrent calls, no queue Carrier can only use its compartment
Fallback Cached zone rate or flat rate, flagged Checkout keeps working
Health checks Third party excluded from liveness No restart loops

Production example

Before the fix, a 40-minute carrier slowdown caused about 25 minutes of checkout outage. After it, a similar slowdown opened the breaker within 10 seconds, about 1,900 orders used flat-rate shipping (reconciled the next day at a cost of roughly A$2,300 in shipping differences), and checkout p95 stayed at 520 ms.

🔍 What the interviewer is checking

Checks structured incident diagnosis (finding the shared resource), mitigation before fixing, and a correctly layered resilience design.

Green flags

  • Spots that unrelated failures mean a shared resource is exhausted.
  • Uses concrete tools: Application Insights, dotnet-counters, dotnet-dump.
  • Mitigates first with a flag or fallback.
  • Layers timeouts, one retry, a tuned breaker, a bulkhead and a fallback, and moves the call out of the transaction.
  • Mentions health-check restart loops and chaos testing.

Red flags

  • "Add more retries" or "scale out" as the fix.
  • Doesn't consider what requests hold while waiting.
  • Relies on default timeouts.
  • No verification that the fix works.

📚 Learn in depth

1. Anatomy of a cascade

 Carrier API slows (0.2 s -> 30 s)
        |
 Checkout requests wait 100 s (default timeout) x up to 4 attempts
        |                      while holding a DB connection inside the order transaction
        v
 SqlClient pool (Max Pool Size = 100) exhausted
        |
 Every endpoint needing the DB times out acquiring a connection   <- unrelated requests fail
        |
 Liveness probe (calls carrier) fails -> pods restart -> cold starts -> less capacity

Cascades almost always follow this shape: a slow dependency, no time limit, no concurrency limit, and a shared resource held during the wait.

2. Diagnosis in more detail

  • Application Insights: application map for the slow edge; dependency duration percentiles; failures blade grouped by exception message; end-to-end transaction for one slow request.
  • dotnet-counters: dotnet-counters monitor -p <pid> --counters System.Runtime,Microsoft.Data.SqlClient.EventSource,System.Net.Http. Watch threadpool-queue-length, threadpool-thread-count, SqlClient active-hard-connections, number-of-pooled-connections, and HTTP current-requests/http11-connections-current-total.
  • dotnet-dump: dotnet-dump collect, then dumpasync in dotnet-dump analyze to list awaiting async state machines and what they're waiting on; clrstack -all for blocked threads if sync-over-async is suspected.
  • Config review: HttpClient.Timeout (100 s default), retry settings, Max Pool Size, probes.

3. Why each pattern is needed

Pattern Without it
Timeout Calls hold resources for 100 s each
Retry (bounded) Blips fail requests; too many retries multiply load
Circuit breaker Every request still pays the timeout during an outage
Bulkhead In-flight calls can grow until a shared resource is exhausted
Fallback Breaker and bulkhead rejections still fail the user

They're complementary: timeouts bound each call, the breaker stops calling when it's clearly down, the bulkhead caps how much can be waiting at once, and the fallback turns all rejections into a degraded success.

4. Ordering in the pipeline

Outer to inner: concurrency limiter (bulkhead) → total timeout → retry → circuit breaker → attempt timeout. That's the shape of AddStandardResilienceHandler; the fallback sits outside the pipeline in the client (catching TimeoutRejectedException, BrokenCircuitException and RateLimiterRejectedException) or as a Polly fallback strategy outermost.

5. Transactions and external calls

Never await an external service inside a database transaction. Get the rate before starting the transaction, or record the intent in an outbox and call the carrier asynchronously. This one change removes the DB pool from the blast radius.

6. Health checks

Liveness should answer "is this process able to run?", and never depend on third parties; failing it restarts pods. Readiness can reflect critical internal dependencies; third parties belong in a separate diagnostic health endpoint or monitoring.

7. Fallback design

The product owner chooses: last known rate for the postcode zone (HybridCache), a flat rate, or "shipping calculated later". Flag such orders so finance or the warehouse can reconcile.

8. Proving it

Chaos testing: inject latency into the carrier stub (Polly's chaos strategies AddChaosLatency/AddChaosFault, or a fault-injecting proxy) in staging under load (k6), and assert unrelated endpoints keep their p95.

Try it yourself

  1. Reproduce the cascade locally: a stub with a 30 s delay, a handler calling it inside a transaction, and 200 concurrent requests; watch SqlClient counters hit the pool limit.
  2. Use dotnet-dump and dumpasync to find the waiting calls.
  3. Move the call outside the transaction and repeat.
  4. Add the layered pipeline and fallback; repeat and compare an unrelated endpoint's p95.
  5. Add AddChaosLatency to the pipeline in a staging configuration and run a k6 test.

💻 Code

Before: the call inside the transaction with defaults. After: rate fetched first, a layered pipeline, and a fallback.

// BEFORE (the cascade): external call inside the transaction, 100 s default timeout, retries x3
// await using var tx = await db.Database.BeginTransactionAsync(ct);
// db.Orders.Add(order);
// await db.SaveChangesAsync(ct);
// order.ShippingCost = await shipping.GetRateAsync(order.Postcode, order.WeightKg, ct);   // holds a DB connection for up to minutes
// await db.SaveChangesAsync(ct);
// await tx.CommitAsync(ct);
using Microsoft.Extensions.Http.Resilience;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddHybridCache();
builder.Services.AddHttpClient<ShippingRatesClient>(c => c.BaseAddress = new Uri("https://rates.carrier.example"))
    .AddStandardResilienceHandler(o =>
    {
        o.RateLimiter.DefaultRateLimiterOptions.PermitLimit = 30;     // bulkhead: carrier gets its own compartment
        o.RateLimiter.DefaultRateLimiterOptions.QueueLimit = 0;
        o.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(5);      // user-facing budget
        o.Retry.MaxRetryAttempts = 1;                                  // one jittered retry, no amplification
        o.CircuitBreaker.MinimumThroughput = 20;                       // sized to our traffic so it opens fast
        o.CircuitBreaker.SamplingDuration = TimeSpan.FromSeconds(10); // >= 2x attempt timeout
        o.CircuitBreaker.BreakDuration = TimeSpan.FromSeconds(30);
        o.AttemptTimeout.Timeout = TimeSpan.FromSeconds(2);
    });

// Liveness never depends on third parties (a failing carrier must not restart pods)
builder.Services.AddHealthChecks();

var app = builder.Build();
app.MapHealthChecks("/health/live", new() { Predicate = _ => false });
app.Run();
using Microsoft.Extensions.Caching.Hybrid;
using Polly.CircuitBreaker;
using Polly.RateLimiting;
using Polly.Timeout;

public sealed record ShippingQuote(decimal Amount, bool IsFallback);

public sealed class ShippingRatesClient(HttpClient http, HybridCache cache, ILogger<ShippingRatesClient> logger)
{
    private const decimal FlatRate = 14.95m;

    public async Task<ShippingQuote> GetRateAsync(string postcode, decimal weightKg, CancellationToken ct)
    {
        var zoneKey = $"rate:{postcode[..1]}:{Math.Ceiling(weightKg)}";   // zone + weight band
        try
        {
            var amount = await http.GetFromJsonAsync<decimal>($"/rates?postcode={postcode}&kg={weightKg}", ct);
            await cache.SetAsync(zoneKey, amount, cancellationToken: ct);  // keep the fallback warm
            return new ShippingQuote(amount, IsFallback: false);
        }
        catch (Exception ex) when (ex is BrokenCircuitException or TimeoutRejectedException or RateLimiterRejectedException or HttpRequestException)
        {
            logger.LogWarning("Shipping rates unavailable ({Reason}); using fallback", ex.GetType().Name);
            var cached = await cache.GetOrCreateAsync(zoneKey, _ => ValueTask.FromResult(FlatRate), cancellationToken: ct);
            return new ShippingQuote(cached, IsFallback: true);            // order flagged for reconciliation
        }
    }
}

// AFTER: quote first, then a short transaction with no external calls inside
public sealed class PlaceOrderHandler(ShopDbContext db, ShippingRatesClient shipping)
{
    public async Task<Guid> HandleAsync(PlaceOrder command, CancellationToken ct)
    {
        var quote = await shipping.GetRateAsync(command.Postcode, command.WeightKg, ct);
        var order = Order.Place(command, quote.Amount, shippingNeedsReview: quote.IsFallback);
        db.Orders.Add(order);
        await db.SaveChangesAsync(ct);   // one short implicit transaction
        return order.Id;
    }
}

⚠ Common mistakes

  • Mistake: Leaving HttpClient.Timeout at the 100-second default. Why it is wrong: Each slow call holds resources for up to 100 s, multiplied by retries. Instead: Per-attempt and total timeouts sized to the user's budget.
  • Mistake: Calling an external API inside a database transaction. Why it is wrong: DB connections are held during the wait, so a slow third party exhausts the pool for every endpoint. Instead: Call before the transaction, or asynchronously via an outbox.
  • Mistake: Adding more retries during an outage. Why it is wrong: Retries multiply load and waiting time. Instead: At most one jittered retry, with a circuit breaker.
  • Mistake: A circuit breaker with default thresholds that never open at your traffic. Why it is wrong: Every request still pays the full timeout. Instead: Tune minimum throughput and sampling to the call rate.
  • Mistake: No concurrency limit on the client. Why it is wrong: In-flight calls grow until something shared runs out. Instead: A bulkhead (concurrency limiter) per dependency.
  • Mistake: Including third-party checks in liveness probes. Why it is wrong: Kubernetes restarts healthy pods, reducing capacity during the incident. Instead: Keep liveness process-only; monitor third parties separately.
  • Mistake: Fixing code during the incident before mitigating. Why it is wrong: Users stay down while you write and deploy a fix. Instead: Use a feature flag or fallback to restore service first.
  • Mistake: No fallback when the breaker or bulkhead rejects. Why it is wrong: Fast failures are still failures for the user. Instead: A product-approved degraded path (cached or flat rate), flagged for reconciliation.

🏛 Senior insight: trade-offs

Cascades are rarely caused by the dependency; they're caused by our lack of boundaries around it. I review every external call with three questions: how long can it take (timeout), how many can be in flight (bulkhead), and what happens when it fails (breaker plus fallback). And I check what each call holds while it waits; a transaction or a lock turns a local slowdown into a global outage.

Option When it fits Cost When not to
Standard handler tuned per dependency Most third-party HTTP calls Tuning and review Calls needing custom classification
Feature flag kill switch Any non-critical dependency Flag management Critical path with no alternative
Cached/flat-rate fallback Prices, quotes, enrichment Reconciliation, stale data Values that must be exact (e.g. payment amounts)
Async processing via outbox/queue Work that needn't block the user Eventual completion, UX changes Data the user needs before confirming
Chaos tests in staging Critical user journeys Test infrastructure Never skipped for checkout-level flows

I measure success by unrelated endpoints' p95 during dependency incidents, time-to-open for breakers, fallback rate, and incident duration; the goal is that a third-party outage shows up as a degraded-feature metric, not an outage.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate tunes the breaker so it opens quickly Why: Checks circuit breaker states, thresholds and placement
    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 reduces retries to one with jitter Why: Checks retry amplification and why only one retry is used
    How to answer

    Retry handles transient faults: a network blip, 503, 429 or a timeout that will probably succeed if you try again shortly.

    • What to retry: 5xx, 408, 429 (honour Retry-After), connection errors and timeouts. Never retry 400, 401, 403, 404, 409 or validation failures.
    • How: exponential backoff with jitter, so thousands of clients don't retry in lockstep. Cap the attempts, and keep the whole thing inside a total timeout.
    • Safety: retry only idempotent operations. For POST, use an idempotency key or disable retries for unsafe methods.

    The danger is amplification: retries at the API, service and client layers multiply, which creates a retry storm against a recovering dependency. Retry at one layer and pair it with a circuit breaker.

    In .NET 10 it's Polly v8 (AddRetry) or AddStandardResilienceHandler (3 retries, exponential, jitter, 2 s base). The trade-off is higher success rates against extra load and latency.

  3. When: Candidate mentions the 100-second HttpClient default Why: Checks attempt vs total timeouts and HttpClient's default timeout
    How to answer

    A timeout should cancel the work, not just stop waiting. Use a CancellationTokenSource with CancelAfter (linked to the caller's token) and pass it down. Task.WaitAsync(timeout) only stops waiting. For HTTP, HttpClient.Timeout is a single total timeout (100 seconds by default) that throws TaskCanceledException with an inner TimeoutException; in production I prefer AddStandardResilienceHandler, which sets attempt and total timeouts plus retries. In ASP.NET Core 8+, the request timeouts middleware cancels RequestAborted after a configured time. Timeouts must be layered: each inner timeout shorter than the outer one.

  4. When: Candidate adds a concurrency limit to the shipping client Why: Checks sizing and placing bulkheads so one dependency can't exhaust shared resources
    How to answer

    A bulkhead partitions shared resources so one failing dependency can only exhaust its own share, like the watertight compartments in a ship. In .NET the shared resources are thread-pool threads, sockets, database connection-pool slots, memory and request slots.

    • Outbound: a concurrency limiter per dependency. Use Polly's AddConcurrencyLimiter, or the standard handler's limiter (1,000 permits, queue 0 by default). Give each dependency a separate named HttpClient with MaxConnectionsPerServer.
    • Inbound: ASP.NET Core AddRateLimiter concurrency policies per endpoint group.
    • Messaging: separate queues and consumers with their own MaxConcurrentCalls.

    A bulkhead limits concurrent work. Rate limiting limits requests per time window. Size limits with Little's Law (concurrency = rate x latency) plus headroom, and pair them with timeouts. The trade-off is containment against rejecting work when a compartment is full.

🛠 Real-world problems: how you handle them

Carrier rates API slowdown took down all of checkout
Situation
Checkout API at [company] on AKS, [8] pods, about [250] requests a second at peak, Azure SQL backend. The place-order handler called a third-party carrier rates API inside the order transaction, via an `HttpClient` with default timeout and a 3-retry policy.
Signals
Carrier p95 rose from [200 ms] to [30 s]; within [4] minutes checkout and account endpoints failed with SQL pool timeout exceptions; Application Insights failure rate [~70%]; Kubernetes events showed liveness probe failures and pod restarts; on-call paged by the availability alert.
Investigation
Application Insights application map showed the slow carrier edge and SQL failures on every endpoint. `dotnet-counters` on a pod showed SqlClient active connections pinned at 100 and HTTP current requests to the carrier at [~400]. `dotnet-dump` with `dumpasync` showed requests awaiting the carrier client inside an open transaction. Config review found the 100 s default timeout, 3 retries, and a liveness probe that called the carrier.
Resolution
Immediate: feature flag switched to flat-rate shipping and the liveness probe was changed to process-only; checkout recovered in [6] minutes. Real fix: rate fetched before the transaction, standard resilience handler tuned (2 s attempt, 5 s total, 1 retry, breaker min throughput 20 / 10 s sampling / 30 s break, bulkhead 30), cached zone-rate fallback with orders flagged for review.
Prevention
Chaos test in staging that injects 30 s latency into the carrier stub under k6 load and asserts checkout p95 < [1 s]; code review rule and analyser against external calls inside transactions; dashboards for fallback rate and breaker state; runbook entry for the shipping kill switch; quarterly review of resilience settings per dependency.

How to tell it (STAR)

**S:** At [company], a carrier's rates API slowed to 30 seconds and within four minutes our whole checkout, and even account pages, were failing for about [25] minutes. **T:** I was incident lead and then owned the fix. **A:** Application Insights and `dotnet-counters` showed the SQL pool pinned at 100: we called the carrier inside the order transaction with a 100-second timeout and three retries, and the liveness probe was restarting pods. I mitigated with the flat-rate feature flag and a process-only liveness probe, then moved the call out of the transaction, added 2 s/5 s timeouts, one retry, a tuned breaker, a 30-call bulkhead and a cached fallback, and a chaos test to prove it. **R:** In the next carrier slowdown the breaker opened in about [10] seconds, [~1,900] orders used fallback rates, and checkout p95 stayed at [520 ms] with no outage.

↩ Usually asked after

More in Enterprise Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me