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

📚 Interview question

Your service calls a downstream API through HttpClient with a timeout, retries, a circuit breaker and a concurrency limit. In what order do you compose these, and why does the order matter? How do timeout budgets and deadlines work when the call is one hop in a chain of services?

Composing resilience strategies in the right order (limiter, total timeout, retry, circuit breaker, attempt timeout), what goes wrong with the wrong order, and timeout budgets and deadline propagation across a chain of distributed .NET services.

Mid-Level Theory Intermediate circuit-breaker distributed-systems polly resilience retry timeouts

🎯 Key points

  • Outer to inner: concurrency limiter → total timeout → retry → circuit breaker → per-attempt timeout
  • Total timeout caps the whole operation including retry delays; attempt timeout caps one try
  • Breaker inside retry so each attempt is counted and an open breaker stops retries fast
  • AddStandardResilienceHandler (Microsoft.Extensions.Http.Resilience, built on Polly v8) defaults: 30 s total, 3 retries with jittered backoff, 10 s attempt, breaker at 10% failures over 30 s
  • Retries at every layer multiply: 3 layers × 4 attempts = 64 calls at the bottom
  • Deadline propagation: pass the remaining budget down (HttpContext.RequestAborted, gRPC deadlines) so inner calls never outlive the caller
  • Each hop's timeout must be shorter than its caller's
  • Every layer is a user-experience trade-off: longer budgets raise success odds but raise tail latency and downstream load

⏱ 30-second answer

Resilience strategies are wrappers, so order decides what each one sees. The order I use, outer to inner, is the one in AddStandardResilienceHandler: concurrency limiter → total timeout → retry → circuit breaker → per-attempt timeout. The total timeout caps the whole operation, retry delays included. The retry wraps the breaker, so every attempt counts towards the breaker's failure ratio, and once the breaker opens the retries fail at once instead of hammering. The attempt timeout sits innermost, so a hung call becomes a fast, retryable failure.

Across services, timeouts form a budget: each hop must give up before its caller does. You also propagate the deadline, so work stops when nobody is waiting for it. The trade-off: every retry layer you add improves the odds for one call but multiplies load on the dependency when it is already struggling.

🗣 Full answer (senior)

How I would answer this in an interview

"I think of resilience strategies as an onion. Each layer only sees what the layers inside it let through, so the order changes the behaviour, not just the style. The order I start from is the one Microsoft ships in AddStandardResilienceHandler. Outermost is a concurrency limiter, so we never have more calls in flight than the dependency can take. Then a total timeout, which is the user's patience: say 30 seconds for everything, retry delays included. Then retry with exponential backoff and jitter. Inside the retry is the circuit breaker, so every attempt is counted, and when the breaker opens the retry gets an immediate BrokenCircuitException instead of waiting out three more slow calls. Innermost is the per-attempt timeout. That turns one hung connection into a fast TimeoutRejectedException that the retry can handle.

The order matters because the mistakes are silent. Put the timeout outside the retry with no attempt timeout, and the first hung attempt eats the whole budget, so you never retry at all. Put the breaker outside the retry, and three failed attempts count as one failure, so the breaker opens far too late. And across services there's a second dimension: budgets. If the gateway gives up after 10 seconds but the order service lets its own call to pricing run for 30, pricing keeps working for a caller who has already gone. Each hop needs a shorter timeout than its caller, and ideally you pass the deadline down: HttpContext.RequestAborted into every outgoing call, and gRPC deadlines with call-context propagation.

The mistake I see most is retries at every layer. Three services that each try four times turn one user click into 64 calls at the bottom, right when the bottom is weakest. I retry in one place, close to the failing dependency, and everything above it fails fast."


The standard pipeline, layer by layer

Layer (outer → inner) Standard handler default What it protects against Wrong placement and its symptom
Rate / concurrency limiter 1,000 permits, no queue Too many in-flight calls to one dependency Inside retry: retries bypass the limit
Total request timeout 30 s The whole operation taking longer than the caller waits Inside retry: no cap on total time
Retry 3 retries, exponential backoff from 2 s, jitter Transient faults (5xx, 408, 429, HttpRequestException, attempt timeouts) Outside total timeout: retries run after the caller has given up
Circuit breaker Opens at 10% failures, at least 100 calls in a 30 s sample; stays open 5 s A dependency that is down; stops sending traffic into a fire Outside retry: a burst of attempts counts once, so it opens late
Attempt timeout 10 s One hung connection or a slow response Missing: the first hang uses the whole total budget

Timeout budgets across a chain

Browser ──► Gateway (10 s) ──► Orders API (8 s) ──► Pricing API (3 s) ──► SQL (2 s command timeout)
             │                   │                    │
             └ gives up at 10 s  └ must give up < 10 s └ must give up < 8 s, incl. retries
Rule Why
Inner timeout < outer timeout, retries included Otherwise the inner hop does work for a caller who has left
Pass CancellationToken from HttpContext.RequestAborted Client disconnects and gateway timeouts cancel the downstream work
Retry in one layer only Retries multiply: (1 + r) to the power of the number of layers
Prefer the deadline over a fixed timeout A request with 1 s left should not start a 3 s call

When not to add the full pipeline

Situation What I do instead
Non-idempotent POST (take a payment) No automatic retry unless there is an idempotency key
Calls inside a message handler Let the broker redeliver; keep in-process retries short
In-cluster call that is already retried by a service mesh Retry in one place only, either the mesh or the code

Production example

In a checkout flow, the gateway timed out at 10 s, but the orders service had a 30 s total timeout towards pricing with three retries. During a pricing slowdown, orders kept up to four attempts in flight per user request for 20 s after users had gone. Pricing CPU sat at 100% and recovery took 15 minutes. Reducing the orders → pricing budget to 3 s total with one retry, and passing RequestAborted through, cut wasted downstream calls by about 70%. The next slowdown cleared in under two minutes.

🔍 What the interviewer is checking

Checks whether the candidate understands resilience strategies as nested wrappers whose order changes behaviour, and can reason about timeouts and retries across a whole call chain.

Green flags

  • Gives the standard order and explains why the breaker sits inside the retry
  • Separates the total timeout from the attempt timeout
  • Does the retry amplification arithmetic unprompted
  • Mentions passing CancellationToken / deadline propagation

Red flags

  • "Just add Polly with retries everywhere"
  • Cannot say what happens when the order is wrong
  • Treats timeouts as independent per service with no budget

📚 Learn in depth

1. Strategies are nested delegates

A Polly v8 ResiliencePipeline is a chain of strategies. Each one receives a callback that runs the rest of the chain:

ExecuteAsync(callback)
  └─ Limiter.Execute(next)
       └─ TotalTimeout.Execute(next)            // one CancellationTokenSource for everything
            └─ Retry.Execute(next)              // loops: next(), delay, next() ...
                 └─ CircuitBreaker.Execute(next) // records outcome of each attempt
                      └─ AttemptTimeout.Execute(next) // linked CTS per attempt
                           └─ HttpClient.SendAsync

Every outer strategy sees the result of the inner chain as one outcome. That is why order matters: the retry sees an open breaker as a BrokenCircuitException and can choose not to retry it. The breaker sees each attempt separately only because it sits inside the retry.

2. How timeouts are implemented

The timeout strategy creates a CancellationTokenSource linked to the incoming token and calls CancelAfter. It then passes the new token inward. If that token fires first, the strategy throws TimeoutRejectedException. Two consequences:

  • The code inside must honour the token. HttpClient.SendAsync does. A synchronous Thread.Sleep or a library that ignores the token does not, so the timeout returns control but the work keeps running.
  • Nested timeouts compose naturally: the attempt token is linked to the total token, so whichever fires first wins.

3. Retry amplification as arithmetic

If each layer makes 1 initial attempt plus r retries, a failure at the bottom of an n-layer chain produces (1 + r)^n calls:

Layers r = 1 r = 3
1 2 4
2 4 16
3 8 64
4 16 256

This is why "retry in one layer" is a rule and not a preference.

4. Deadline propagation

gRPC has deadlines built in: the client sends a grpc-timeout header, and with EnableCallContextPropagation() on a gRPC client factory registration, an outgoing call made inside a gRPC handler inherits the incoming deadline and cancellation. HTTP has no standard deadline header, so in ASP.NET Core you:

  1. Pass HttpContext.RequestAborted (or the minimal API CancellationToken parameter) into every downstream call.
  2. Optionally send a custom header with the remaining budget and read it on the other side to set the total timeout.

5. The circuit breaker's view

The breaker samples outcomes over SamplingDuration (30 s by default). It opens when the failure ratio passes FailureRatio (0.1) and at least MinimumThroughput (100) calls were seen. A low-traffic dependency may never reach 100 calls in 30 s, so the breaker never opens. Tune MinimumThroughput to the real traffic.

6. Hedging is a different shape

AddStandardHedgingHandler sends a second request in parallel if the first is slow, and takes whichever finishes first. It trades extra load for lower tail latency, so use it only for idempotent reads against a dependency with spare capacity.

Try it yourself

  1. Build a minimal API that calls a fake downstream which sleeps for 20 s. Add AddStandardResilienceHandler and watch the attempt timeout trigger three retries, then the total timeout end the operation.
  2. Swap the order so the breaker sits outside the retry. Send 200 failing requests and compare when the breaker opens.
  3. Count the calls reaching the bottom of a three-service chain where each layer retries three times. Then remove two of the retry layers and count again.
  4. Log TimeoutRejectedException and BrokenCircuitException through OnRetry and OnOpened telemetry, and view them with dotnet-counters monitor --counters Polly.
  5. Disconnect the browser mid-request and confirm the downstream call is cancelled when you pass RequestAborted.

💻 Code

A typed client with an explicit pipeline in the standard order, and a call that passes the caller's cancellation down.

// Program.cs (.NET 10, Microsoft.Extensions.Http.Resilience)
using Microsoft.Extensions.Http.Resilience;
using Polly;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddHttpClient<PricingClient>(c => c.BaseAddress = new Uri("https://pricing.internal"))
    .AddResilienceHandler("pricing", pipeline =>
    {
        // 1. Outermost: cap in-flight calls so we cannot flood pricing.
        pipeline.AddConcurrencyLimiter(permitLimit: 50, queueLimit: 0);

        // 2. Total budget for the whole operation, retry delays included.
        //    Must be shorter than OUR caller's timeout (gateway: 10 s).
        pipeline.AddTimeout(TimeSpan.FromSeconds(3));

        // 3. One retry only: we are the single retrying layer in this chain.
        pipeline.AddRetry(new HttpRetryStrategyOptions
        {
            MaxRetryAttempts = 1,
            BackoffType = DelayBackoffType.Exponential,
            UseJitter = true,
            Delay = TimeSpan.FromMilliseconds(200)
        });

        // 4. Inside retry: every attempt is counted; open circuit stops retries at once.
        pipeline.AddCircuitBreaker(new HttpCircuitBreakerStrategyOptions
        {
            FailureRatio = 0.2,
            MinimumThroughput = 20,           // tuned to real traffic (~5 rps)
            SamplingDuration = TimeSpan.FromSeconds(30),
            BreakDuration = TimeSpan.FromSeconds(10)
        });

        // 5. Innermost: one hung attempt becomes a fast, retryable failure.
        pipeline.AddTimeout(TimeSpan.FromSeconds(1));
    });

var app = builder.Build();

// The minimal API CancellationToken is HttpContext.RequestAborted:
// if the client or gateway gives up, the pricing call is cancelled too.
app.MapGet("/quote/{sku}", async (string sku, PricingClient pricing, CancellationToken ct) =>
    await pricing.GetPriceAsync(sku, ct) is { } price ? Results.Ok(price) : Results.NotFound());

app.Run();

public sealed record Price(string Sku, decimal Amount, string Currency);

public sealed class PricingClient(HttpClient http)
{
    public Task<Price?> GetPriceAsync(string sku, CancellationToken ct) =>
        http.GetFromJsonAsync<Price>($"/prices/{Uri.EscapeDataString(sku)}", ct);
}
// appsettings.json: the same budget written down so reviewers can check the chain
{
  "Timeouts": {
    "Gateway": "00:00:10",
    "OrdersToPricingTotal": "00:00:03",
    "OrdersToPricingAttempt": "00:00:01"
  }
}

⚠ Common mistakes

  • Mistake: One timeout outside the retry and no per-attempt timeout. Why it is wrong: The first hung attempt uses the whole budget, so the retry never runs. Instead: Use both a total timeout (outer) and an attempt timeout (inner).
  • Mistake: Circuit breaker outside the retry. Why it is wrong: Four failed attempts count as one failure, so the breaker opens late and the retries keep hammering. Instead: Put the breaker inside the retry, as the standard handler does.
  • Mistake: Retrying at every layer of a call chain. Why it is wrong: Load multiplies to (1 + r)^n at the bottom during an outage. Instead: Retry in one layer and fail fast above it.
  • Mistake: Inner timeouts longer than outer ones. Why it is wrong: Downstream work continues after the caller has gone, which wastes capacity during incidents. Instead: Write the budget down per hop and make each one shorter than its caller's.
  • Mistake: Not passing CancellationToken into HttpClient calls. Why it is wrong: Client disconnects and timeouts do not cancel the downstream work. Instead: Pass RequestAborted (the minimal API CancellationToken) through every call.
  • Mistake: Leaving MinimumThroughput at 100 for a low-traffic dependency. Why it is wrong: The breaker never sees enough calls in the sampling window to open. Instead: Size it from real traffic, for example 20 calls in 30 s.
  • Mistake: Accepting the standard handler defaults without reading them. Why it is wrong: AddStandardResilienceHandler (Microsoft.Extensions.Http.Resilience on Polly v8) uses a 1,000-permit concurrency limiter, a 30 s total timeout, 3 retries with exponential backoff from 2 s plus jitter, a breaker at a 10% failure ratio with at least 100 calls in 30 s (5 s break), and a 10 s attempt timeout. A 30 s total is often longer than your caller's own timeout. Instead: Configure the options (o.TotalRequestTimeout, o.Retry, o.AttemptTimeout) to fit the hop's budget.
  • Mistake: Adding a second resilience handler on top of AddStandardResilienceHandler. Why it is wrong: Stacked pipelines repeat retries and timeouts in ways nobody intended. Instead: Configure one pipeline per client, or remove the defaults first.

🏛 Senior insight: trade-offs

The senior point is that resilience is a system property, not a per-client setting. Each team adds a sensible-looking pipeline, and the sum of them is an amplifier. So I write the timeout and retry budget for the whole call chain down in one place, an ADR or a table in the service catalogue, and review new clients against it. Everything here is Polly v8, the current major version, which Microsoft.Extensions.Http.Resilience builds on. It emits metrics and events (retries, breaker state, timeouts) through System.Diagnostics.Metrics, so dashboards show when the breaker opens and how many calls are retries.

Each layer is also a user-experience and capacity decision. A longer total budget raises the chance that one request succeeds, but it raises p99 latency for everyone and keeps more work in flight downstream. Every retry adds load to a dependency at the moment it is weakest: at 1,000 rps with a 20% failure rate, one retry layer adds 200 rps. I measure both sides: the success rate and p95/p99 seen by users, and the retry share of calls seen by the dependency. A retry share above about 10% means the retries are now part of the problem.

Option When it fits Cost When not to
AddStandardResilienceHandler defaults Most outbound HTTP calls 30 s total may be longer than your caller allows Inside a call chain with tight budgets: tune it
Custom AddResilienceHandler pipeline Known budgets, tight latency targets More config to review Teams without ownership of the numbers
Hedging handler Idempotent reads, tail latency matters Extra load on the dependency Writes, or a dependency without spare capacity
Mesh-level retries (Istio, Linkerd) Polyglot estates, central control Hidden from code; can double up with Polly When code already retries

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the circuit breaker states or thresholds Why: Checks depth on closed, open and half-open states and how thresholds are tuned
    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 backoff, jitter or retry storms Why: Checks which faults are safe to retry and why idempotency is required
    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 CancellationToken or HttpClient timeouts Why: Checks how timeouts are implemented correctly in async .NET code
    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.

🛠 Real-world problems: how you handle them

Downstream work outliving the caller during a pricing slowdown
Situation
An e-commerce checkout of [three services] behind an API gateway with a 10 s timeout, [~800 requests per second] at peak. Orders called pricing with a 30 s total timeout and three retries.
Signals
Pricing CPU at 100%, the gateway logging 504s, Application Insights showing pricing requests still completing 20 s after the gateway returned 504, and calls per checkout to pricing rising from 1 to about 3.5.
Investigation
Used the Application Insights end-to-end transaction view to compare span durations per hop. A KQL query counted dependency calls per operation_Id. Read the resilience configuration in Program.cs and the Polly metrics for retry counts and timeouts.
Resolution
Immediate: cut the orders → pricing total timeout to 3 s and retries to one through configuration, then redeployed. Real fix: wrote a timeout budget per hop, passed RequestAborted through every call, and added a 1 s attempt timeout.
Prevention
An ADR with the timeout budget table, a review checklist item for every new HttpClient registration, and dashboards on Polly retry and timeout metrics with an alert when retries pass 10% of calls.

How to tell it (STAR)

**S:** At [company], our checkout went down for [15 minutes] during a pricing slowdown, even though the gateway was timing out quickly. **T:** I was asked to find out why the outage lasted much longer than the slowdown. **A:** I compared span durations in Application Insights and saw pricing calls finishing 20 seconds after the gateway had already returned 504. Our orders service had a 30-second budget with three retries, so it kept retrying for users who had already left. I cut the budget to 3 seconds with one retry and an attempt timeout, passed RequestAborted through, and wrote the budget for each hop into an ADR. **R:** Wasted downstream calls dropped by [about 70%], and the next pricing slowdown cleared in [under two minutes].

↩ Usually asked after

More in Reliability Patterns

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me