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

📚 Interview question

Explain the Retry pattern for transient faults in .NET 10: exponential backoff with jitter, which failures to retry and which never to retry, why retries need idempotency, how retry storms and retry amplification across layers happen, and how Polly v8 and Microsoft.Extensions.Http.Resilience implement it.

Retry pattern: transient vs permanent faults (5xx, 408, 429 with Retry-After, timeouts vs 400/401/404/409), exponential backoff with jitter (Polly's decorrelated jitter), retrying only idempotent operations (DisableForUnsafeHttpMethods, idempotency keys), retry storms and multiplicative amplification across layers, retry budgets, Polly v8 ResiliencePipeline and RetryStrategyOptions, HttpRetryStrategyOptions defaults in AddStandardResilienceHandler, EF Core EnableRetryOnFailure, and telemetry.

Mid-Level Theory Intermediate design-patterns httpclient idempotency polly resilience retry

🎯 Key points

  • Retry only transient faults: 5xx, 408, 429 (honour Retry-After), HttpRequestException and timeouts; never 400, 401, 403, 404, 409 or validation errors
  • Exponential backoff spaces attempts (e.g. 2 s, 4 s, 8 s); jitter randomises them so many clients don't retry in lockstep (Polly uses decorrelated jitter when UseJitter = true)
  • Only retry idempotent operations: GET, HEAD, PUT and DELETE are idempotent by HTTP semantics; POST/PATCH need an idempotency key, or DisableForUnsafeHttpMethods() (disables POST, PATCH, PUT, DELETE, CONNECT)
  • Retry amplification: retries at each layer multiply (4 attempts x 3 layers = 64 calls); retry at one layer, usually closest to the failing dependency
  • Retry storms hit a recovering dependency; cap attempts, use a circuit breaker and keep retries inside a total timeout
  • Polly v8 replaced v7's Policy/WaitAndRetry/PolicyWrap with ResiliencePipelineBuilder.AddRetry(new RetryStrategyOptions { MaxRetryAttempts, BackoffType = Exponential, UseJitter, Delay, ShouldHandle }), built once and reused, with built-in metrics
  • AddStandardResilienceHandler retry defaults: 3 retries, exponential, jitter, 2 s base delay, inside a 30 s total timeout and outside a 10 s attempt timeout
  • EF Core EnableRetryOnFailure retries transient SQL errors; with user transactions use the execution strategy

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

🗣 Full answer (senior)

How I would answer this in an interview

"Retry is for transient faults: things that fail now and will probably work in a second. A 503 during a deployment, a 429 when you hit a rate limit, a dropped connection, an Azure SQL failover. The first rule is classification. I retry 5xx, 408, 429, HttpRequestException and timeouts. I never retry 400, 401, 403, 404 or 409, because the answer won't change, and retrying a 401 is just hammering an auth server. For 429 and 503 I honour the Retry-After header if the server sends one.

The second rule is timing. Immediate retries just add load at the worst moment, so I use exponential backoff, roughly 2, 4, 8 seconds, and jitter, so a thousand clients that failed at the same instant don't all retry at the same instant. Polly v8 does decorrelated jitter when you set BackoffType = Exponential and UseJitter = true. I cap it at about three retries and put a total timeout around the whole thing, so a user never waits 40 seconds for something that was going to fail anyway. In .NET 10 for HTTP I usually start with AddStandardResilienceHandler, which gives three retries with exponential backoff and jitter from a 2-second base, inside a 30-second total timeout, with a 10-second timeout per attempt and a circuit breaker between them. For non-HTTP calls I build a Polly ResiliencePipeline with AddRetry. For EF Core, EnableRetryOnFailure handles transient SQL errors.

The third rule is safety. A retried POST that actually succeeded the first time creates a second order, so I only retry idempotent calls: GETs, PUTs, or POSTs with an idempotency key. The resilience handler has DisableForUnsafeHttpMethods() for exactly this. The mistake I see is retries at every layer: the gateway retries three times, the API retries three times, the SDK retries three times, and one failing call becomes 64 requests against a database that's trying to recover. For example, at [company] [a downstream outage turned into a retry storm because [n] layers each retried], and I [removed retries from all but the outermost client call and added a circuit breaker], which [cut load on the dependency during incidents by about [n]x]. Retry at one layer, only for transient faults, only for idempotent operations, with backoff, jitter and a budget."


What to retry

Failure Retry? Why
500, 502, 503, 504 Yes Often transient (deploys, overload)
408 Request Timeout Yes Transient
429 Too Many Requests Yes, honour Retry-After Back off as asked
HttpRequestException, socket errors Yes Connection-level transient
Attempt timeout (TimeoutRejectedException) Yes, if idempotent Request may or may not have been processed
400, 422 No Request is invalid
401, 403 No Auth won't change by retrying
404 No Resource doesn't exist
409 Conflict No (re-read and decide) Business conflict

Backoff strategies

Strategy Delays (base 1 s) Problem
Immediate 0, 0, 0 Adds load at the worst moment
Constant 1, 1, 1 Clients stay synchronised
Exponential 1, 2, 4 Still synchronised without jitter
Exponential + jitter ~0.8, ~2.3, ~3.6 (random) Recommended

Amplification

Layers each retrying 3 times (4 attempts) Calls to the failing dependency
1 4
2 16
3 64

Production example

After consolidating retries into one Polly pipeline at the HTTP client (3 retries, exponential with jitter, 2 s base) and removing SDK-level and controller-level retries, peak requests to a payment provider during its incidents fell from about 9x normal traffic to 1.6x, and the success rate for transient blips stayed at 99.7%.

🔍 What the interviewer is checking

Checks whether the candidate can apply retries safely: classifying faults, backing off with jitter, ensuring idempotency and avoiding amplification.

Green flags

  • Lists retryable and non-retryable status codes and honours Retry-After.
  • Explains exponential backoff and why jitter matters.
  • Connects retries to idempotency and idempotency keys.
  • Describes amplification across layers.
  • Knows Polly v8 pipelines and the standard handler defaults.

Red flags

  • "Retry 5 times on any exception."
  • Retries POSTs blindly.
  • Retries at every layer.
  • Still describes Polly v7 Policy.Handle().WaitAndRetry as current.

📚 Learn in depth

1. Transient vs permanent faults

Transient faults are self-correcting: network glitches, brief overload, failovers, throttling. Permanent faults won't change on retry: bad input, missing resources, auth failures, bugs. A retry policy is mostly a classifier (ShouldHandle) plus a schedule (backoff) plus a limit.

 Caller --> [Retry: ShouldHandle? attempt < max?] --> call --> dependency
               ^           | transient
               |__ wait(backoff + jitter) __|

2. Backoff and jitter

Exponential backoff: delay = base * 2^attempt, usually capped (MaxDelay). Without jitter, clients that failed together retry together, creating synchronised waves (the "thundering herd"). AWS's analysis of backoff strategies showed that adding jitter greatly reduces total work and contention. Polly v8 uses a decorrelated-jitter formula when BackoffType = Exponential and UseJitter = true, which spreads delays while keeping the exponential trend.

3. Idempotency

A timeout doesn't tell you whether the server processed the request. Retrying a non-idempotent operation can duplicate it. Options:

  • Retry only safe/idempotent HTTP methods (GET, HEAD, PUT, DELETE when designed idempotently).
  • Send an Idempotency-Key header that the server deduplicates (common with payment APIs).
  • options.Retry.DisableForUnsafeHttpMethods() (Microsoft.Extensions.Http.Resilience) disables retries for POST, PATCH, PUT, DELETE and CONNECT; DisableFor(...) targets specific methods.

4. Retry storms and budgets

Retries add load exactly when the dependency is weakest. Mitigations:

  • Retry at one layer.
  • Cap attempts (3 is usually plenty).
  • A circuit breaker stops retries once failures are sustained.
  • A retry budget (e.g. retries may add at most 10% extra load) caps the total; Polly doesn't ship a budget strategy, so it's implemented with a rate limiter or custom ShouldHandle logic, or provided by a service mesh.
  • Honour Retry-After.

5. Polly v8 model

Polly v8 replaced v7's Policy/PolicyWrap with resilience pipelines built by ResiliencePipelineBuilder. Strategies are added outermost first. RetryStrategyOptions has MaxRetryAttempts (default 3), Delay (default 2 s), BackoffType (default Constant), UseJitter (default false), MaxDelay, ShouldHandle, DelayGenerator and OnRetry. Pipelines are thread-safe and should be built once (via DI AddResiliencePipeline or AddResilienceHandler) and reused.

6. Microsoft.Extensions.Http.Resilience

AddStandardResilienceHandler() adds, outer to inner: rate limiter, total timeout (30 s), retry, circuit breaker, attempt timeout (10 s). The retry uses HttpRetryStrategyOptions, whose defaults handle 5xx, 408, 429, HttpRequestException and TimeoutRejectedException, retry 3 times with exponential backoff and jitter from a 2-second base, and respect Retry-After (ShouldRetryAfterHeader = true). AddResilienceHandler("name", builder => ...) builds a custom pipeline. Polly.Core is the engine underneath both.

7. Database retries

EF Core's EnableRetryOnFailure (SQL Server provider) retries a known list of transient error numbers with exponential backoff. User-initiated transactions must run inside CreateExecutionStrategy().ExecuteAsync, and the block may re-run.

8. Telemetry

Polly v8 emits metrics and logs per strategy (resilience events via System.Diagnostics.Metrics), so you can chart retry counts. A rising retry rate is an early warning that a dependency is degrading.

Try it yourself

  1. Build a pipeline with constant delay, then exponential with jitter; log OnRetry delays and compare.
  2. Point an HttpClient at a stub returning 503 with Retry-After: 3 and verify the delay.
  3. Add retries at three layers in a test harness and count calls to a failing stub.
  4. Enable DisableForUnsafeHttpMethods() and confirm a failing POST isn't retried.
  5. Watch Polly's resilience metrics with dotnet-counters monitor --counters Polly.

💻 Code

A standard handler with tuned retry options, a custom HTTP pipeline, and a Polly v8 pipeline for a non-HTTP dependency.

using Microsoft.Extensions.Http.Resilience;
using Polly;
using Polly.Retry;

var builder = WebApplication.CreateBuilder(args);

// 1. Standard pipeline: rate limiter -> total timeout -> retry -> circuit breaker -> attempt timeout
builder.Services.AddHttpClient<CatalogueClient>(c => c.BaseAddress = new Uri("https://catalogue.internal"))
    .AddStandardResilienceHandler(o =>
    {
        o.Retry.MaxRetryAttempts = 3;
        o.Retry.BackoffType = DelayBackoffType.Exponential;
        o.Retry.UseJitter = true;                          // de-synchronise clients
        o.Retry.Delay = TimeSpan.FromMilliseconds(500);
        o.Retry.DisableForUnsafeHttpMethods();             // never retry POST/PATCH/PUT/DELETE automatically
        o.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(10);   // the user's total budget, including retries
        o.AttemptTimeout.Timeout = TimeSpan.FromSeconds(2);
        o.CircuitBreaker.SamplingDuration = TimeSpan.FromSeconds(10); // must be at least 2x the attempt timeout
    });

// 2. Custom HTTP pipeline for a POST that is safe because it carries an idempotency key
builder.Services.AddHttpClient<PaymentsClient>(c => c.BaseAddress = new Uri("https://payments.example.com"))
    .AddResilienceHandler("payments", pipeline =>
    {
        pipeline.AddTimeout(TimeSpan.FromSeconds(15));     // total
        pipeline.AddRetry(new HttpRetryStrategyOptions
        {
            MaxRetryAttempts = 2,
            BackoffType = DelayBackoffType.Exponential,
            UseJitter = true,
            ShouldRetryAfterHeader = true                  // honour 429/503 Retry-After
        });
        pipeline.AddTimeout(TimeSpan.FromSeconds(5));      // per attempt
    });

// 3. Non-HTTP dependency (e.g. a blob or SDK call): plain Polly v8 pipeline, built once and reused
builder.Services.AddResiliencePipeline("blob-retry", pipeline => pipeline.AddRetry(new RetryStrategyOptions
{
    MaxRetryAttempts = 3,
    Delay = TimeSpan.FromMilliseconds(200),
    BackoffType = DelayBackoffType.Exponential,
    UseJitter = true,
    ShouldHandle = new PredicateBuilder().Handle<IOException>().Handle<TimeoutException>()   // transient only
}));

var app = builder.Build();
app.Run();

public sealed class CatalogueClient(HttpClient http)
{
    public Task<string> GetProductAsync(int id, CancellationToken ct) => http.GetStringAsync($"/products/{id}", ct);
}

public sealed record PaymentRequest(Guid OrderId, decimal Amount);

public sealed class PaymentsClient(HttpClient http)
{
    public async Task ChargeAsync(PaymentRequest request, CancellationToken ct)
    {
        using var message = new HttpRequestMessage(HttpMethod.Post, "/charges") { Content = JsonContent.Create(request) };
        message.Headers.Add("Idempotency-Key", request.OrderId.ToString());   // the server dedupes retries
        using var response = await http.SendAsync(message, ct);
        response.EnsureSuccessStatusCode();
    }
}
// Using the named pipeline
using Polly;
using Polly.Registry;

public sealed class ReportStore(ResiliencePipelineProvider<string> pipelines)
{
    private readonly ResiliencePipeline _retry = pipelines.GetPipeline("blob-retry");

    public ValueTask<byte[]> ReadAsync(string path, CancellationToken ct) =>
        _retry.ExecuteAsync(async token => await File.ReadAllBytesAsync(path, token), ct);
}

⚠ Common mistakes

  • Mistake: Retrying every failure, including 400, 401 and 404. Why it is wrong: The result won't change, and it adds load and latency. Instead: Retry only transient faults with a precise ShouldHandle.
  • Mistake: Immediate or constant-delay retries. Why it is wrong: Clients retry in synchronised waves against an overloaded dependency. Instead: Exponential backoff with jitter.
  • Mistake: Retrying non-idempotent POSTs. Why it is wrong: A request that succeeded but timed out is executed twice (duplicate orders or charges). Instead: Use idempotency keys or DisableForUnsafeHttpMethods().
  • Mistake: Retrying at several layers. Why it is wrong: Attempts multiply (64 calls from three layers of 3 retries), creating a retry storm. Instead: Retry at one layer and remove the others.
  • Mistake: No total timeout around retries. Why it is wrong: Users wait for the sum of all attempts and delays. Instead: Put a total timeout outside the retry and a per-attempt timeout inside.
  • Mistake: Ignoring Retry-After on 429/503. Why it is wrong: You retry earlier than the server asked and get throttled harder. Instead: Honour the header (ShouldRetryAfterHeader).
  • Mistake: Building a new Polly pipeline per call. Why it is wrong: It allocates each time and loses circuit-breaker state. Instead: Build once via DI and reuse.
  • Mistake: Hiding retries with no telemetry. Why it is wrong: A dependency can degrade for weeks while retries mask it. Instead: Chart retry counts from Polly's metrics and alert on spikes.

🏛 Senior insight: trade-offs

Retry is the resilience pattern most likely to make an outage worse, so I think about it in terms of load: how many extra calls can my retries add when the dependency is already struggling? One layer of retries, a small attempt count, jitter, a total timeout and a circuit breaker keep that number bounded.

Option When it fits Cost When not to
No retry Non-idempotent calls without keys; user can retry Lower success on blips Background work that must complete
AddStandardResilienceHandler Most outgoing HTTP Defaults may not suit every API Calls needing custom classification
Custom Polly pipeline Non-HTTP, special status codes More configuration When the standard handler fits
Queue + redelivery Background processing Latency Interactive requests
Service mesh retries Platform-wide policy Another layer that can amplify Alongside app-level retries

I measure retry rate per dependency, the ratio of attempts to requests during incidents (amplification), and p99 latency including retries.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions a total timeout around retries Why: Checks combining per-attempt and total timeouts with retries
    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.

  2. When: Candidate talks about the order of retry, circuit breaker and timeout Why: Checks how handler order (retry outside the breaker) causes or prevents retry storms
    How to answer

    All three symptoms come from wrapper order and duplication. The outermost decorator or handler runs first and can short-circuit everything inside it.

    • Cached errors: the cache sits outside a fallback that turns exceptions into "empty" results, so it stores the outage for the full TTL. Put the fallback outermost (Fallback → Cache → real search): exceptions pass through the cache uncached, and the empty answer is never stored.
    • Retry storms: retries in two layers multiply attempts, for example a custom handler on top of AddStandardResilienceHandler. The standard pipeline is already rate limiter → total timeout → retry → circuit breaker → attempt timeout.
    • Duplicate logs: a decorator or handler is registered twice, or a custom logging handler sits on top of the built-in HttpClient logging.

    To diagnose, list the ServiceDescriptors, walk the resolved chain, inspect the handler order, and read span nesting in traces. Then compose the chain in one place and add tests that assert its order and attempt counts.

  3. When: Candidate says retried operations must be idempotent Why: Checks idempotent processing on the receiving side of retried messages
    How to answer

    With at-least-once delivery, duplicates are normal: outbox resends, peek-lock redelivery after a crash or lock expiry, and publisher retries. An idempotent consumer makes processing a message twice have the same effect as once.

    The inbox is an InboxMessages table with a primary key on (MessageId, Consumer). For each message, in one EF Core transaction:

    1. Insert the inbox row first.
    2. Apply the business change.
    3. Commit, then complete the Service Bus message.

    If the insert fails with SQL error 2627/2601, the message was already processed, so complete it. A concurrent duplicate blocks on the key lock until the first commits, then fails the insert. If the first rolls back, the duplicate goes ahead.

    Purge old rows past the redelivery window. The trade-off is an extra write and table per consumer against correct exactly-once processing.

  4. When: Candidate says retries should be paired with a circuit breaker Why: Checks the circuit breaker that stops retries hammering a failing dependency
    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.

🛠 Real-world problems: how you handle them

Three layers of retries turned a database blip into a retry storm
Situation
Order API at [company] calling an inventory service, which called Azure SQL. The gateway, the order API's HttpClient and the inventory service's data layer each retried 3 times with no jitter. Peak traffic [~600] requests a second.
Signals
During a [40-second] Azure SQL failover, inventory requests jumped to [~10x] normal; the inventory service's CPU hit 100% and stayed there for [8 minutes] after the database recovered; Application Insights showed bursts of identical calls at fixed intervals.
Investigation
Application Insights dependency telemetry showed each user request producing up to [64] inventory database calls. Reviewed resilience configuration across layers: APIM retry policy, a Polly v7 `WaitAndRetry` without jitter in the order API, and EF Core retries plus a hand-written retry loop in inventory. Fixed-interval spikes in the dependency chart confirmed synchronised retries.
Resolution
Immediate: removed the gateway retry and the hand-written loop via config and redeploy. Real fix: one retry layer at the order API using `AddStandardResilienceHandler` (exponential, jitter, 3 retries, circuit breaker), EF Core `EnableRetryOnFailure` only for the database call inside inventory, and retries disabled for unsafe methods.
Prevention
An ADR stating which layer retries for each dependency; a dashboard of attempts-per-request during incidents; chaos tests (fault injection with Polly's chaos strategies) in staging to verify amplification stays under [2x]; code review checklist item for new retry logic.

How to tell it (STAR)

**S:** At [company], a [40-second] database failover turned into [8 minutes] of inventory outage. **T:** I led the incident review and had to stop small blips from becoming outages. **A:** Telemetry showed each request causing up to [64] database calls because the gateway, the order API and the inventory service all retried, without jitter. I consolidated to one retry layer using the standard resilience handler with jittered exponential backoff and a circuit breaker, kept EF Core retries only at the database, and added chaos tests for amplification. **R:** In the next failover, load on inventory peaked at [1.6x] instead of [10x], and recovery took [under a minute] instead of [8].

↩ Usually asked after

More in Enterprise Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me