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.
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.
"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 immediateBrokenCircuitExceptioninstead of waiting out three more slow calls. Innermost is the per-attempt timeout. That turns one hung connection into a fastTimeoutRejectedExceptionthat 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.RequestAbortedinto 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."
| 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 |
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 |
| 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 |
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.
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
CancellationToken / deadline propagationRed flags
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.
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:
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.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.
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:
HttpContext.RequestAborted (or the minimal API CancellationToken parameter) into every downstream call.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.
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.
AddStandardResilienceHandler and watch the attempt timeout trigger three retries, then the total timeout end the operation.TimeoutRejectedException and BrokenCircuitException through OnRetry and OnOpened telemetry, and view them with dotnet-counters monitor --counters Polly.RequestAborted.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"
}
}
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.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.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.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.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 |
A circuit breaker stops calling a dependency that is clearly failing, so you fail fast instead of wasting threads and sockets on timeouts.
BrokenCircuitException for the break duration.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.
Retry handles transient faults: a network blip, 503, 429 or a timeout that will probably succeed if you try again shortly.
Retry-After), connection errors and timeouts. Never retry 400, 401, 403, 404, 409 or validation failures.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.
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.
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].
Last updated 23 Nov 2026.