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

📚 Interview question

From the API designer's side, how do you make retries safe and predictable for clients? Which requests and status codes should clients retry, how do you use Retry-After, why do clients need backoff with jitter, and how does retry amplification across layers turn a small outage into a big one?

The retry contract of an HTTP API: retryable methods and status codes, Retry-After, exponential backoff with jitter, retry amplification across layers, retry budgets, and documenting retry guidance.

Mid-Level Theory Intermediate idempotency jitter resilience retries retry-after web-api

🎯 Key points

  • Retry only transient failures: network errors, 408, 429, 502, 503, 504 (500 only for idempotent calls, with care)
  • Never retry 400, 401, 403, 404, 409, 422: the same request fails the same way
  • Safe and idempotent methods (GET, PUT, DELETE) retry freely; POST/PATCH need an Idempotency-Key
  • Retry-After (RFC 9110, also valid on 3xx) on 429 and 503; Polly's HTTP retry honours it by default
  • Exponential backoff with jitter spreads retries and avoids synchronised thundering herds
  • Amplification: 3 layers x (1 + 3 retries) = 64 attempts at the bottom
  • Retry at one layer only, within a retry budget, with a circuit breaker to stop retrying a dead dependency
  • Log and meter every retry (Polly resilience events, OnRetry logging) and document retryable errors

⏱ 30-second answer

A retry is only safe if the request is idempotent and the failure is transient. As the API owner I make both explicit: GET, PUT and DELETE are idempotent by design, POST takes an Idempotency-Key, and I document which statuses are retryable: network failures, 408, 429, 502, 503, 504, never 4xx validation or auth errors. When I shed load I return 429 or 503 with Retry-After, and clients should honour it. Clients must use exponential backoff with jitter so thousands of them don't retry in lockstep. The big risk is retry amplification: if three layers each try four times, one user click becomes 64 calls to the struggling service. Retry at one layer, cap it with a budget, and let a circuit breaker stop it.

🗣 Full answer (senior)

How I would answer this in an interview

"Retries are part of the API contract even if the client writes the retry code. Clients can only retry safely if I tell them two things: which operations are idempotent, and which failures are transient. GET, PUT and DELETE are idempotent by HTTP semantics, so I make sure my implementations really are. For POST, I accept an Idempotency-Key header so a retried payment doesn't charge twice. Then I document the retryable statuses: connection failures, 408, 429, 502, 503 and 504. A 400, 401, 403, 404, 409 or 422 will fail the same way every time, so retrying only adds load.

When my service is overloaded or rate limiting, I return 429 or 503 with Retry-After, because that is the only way the server can say how long to wait. Polly's HTTP retry strategy in Microsoft.Extensions.Http.Resilience honours Retry-After by default. Without it, clients guess, and they usually guess too short. Clients should also back off exponentially with jitter: if 5,000 phones all failed at the same second and all retry after exactly 2, 4 and 8 seconds, they hit me in synchronised waves. Random jitter spreads them out.

The mistake I see is retries at every layer. The SPA retries three times, the BFF retries three times, the order service retries three times against the payment service: that's four times four times four, 64 calls to a service that was already struggling. I want retries in one place, normally closest to the failing dependency, with a retry budget and a circuit breaker so that when it's really down, we stop knocking."


What clients may retry

Failure Retry? Why
Connection refused / reset, DNS failure Yes (idempotent requests) Transient network fault
Timeout Yes, if idempotent or keyed Operation may have completed
408 Request Timeout Yes Server closed an idle connection
429 Too Many Requests Yes, after Retry-After Rate limit
500 Internal Server Error Rarely, idempotent only Often a bug, so retries repeat it
502 / 503 / 504 Yes, with backoff Upstream or overload
400, 401, 403, 404, 409, 412, 422 No Same request, same result (refresh token first for 401)

Backoff with jitter

Strategy Delays (base 1 s) Problem
Immediate 0, 0, 0 Hammers the failing service
Constant 1, 1, 1 Synchronised waves
Exponential 1, 2, 4 Still synchronised if all clients failed together
Exponential + jitter random(0..1), random(0..2), random(0..4) Spreads load; the recommended default

Production example

During a [payments provider] brownout, our checkout path had retries in the SPA, the BFF and the order service: one click became up to 64 provider calls and the provider's error rate went from 5% to 60%. Removing retries from the SPA and BFF, keeping one jittered retry layer with a circuit breaker next to the provider, cut calls during the next brownout by about 90% and the provider recovered in minutes instead of [an hour].

🔍 What the interviewer is checking

Checks whether the candidate sees retries as a contract between server and client and understands their systemic risks.

Green flags

  • Separates retryable and non-retryable statuses correctly
  • Links POST retries to idempotency keys
  • Explains jitter and Retry-After
  • Quantifies amplification across layers and limits retries to one layer
  • Mentions circuit breakers or retry budgets

Red flags

  • "Retry three times on any error"
  • Retries POST payments blindly
  • Has never heard of jitter or retry storms

📚 Learn in depth

1. Why retries are dangerous

A retry is extra load sent exactly when a system is least able to handle it. Under normal conditions retries are rare and harmless. During an incident, every failing request multiplies. If a service is at 100% capacity and 50% of requests fail and each is retried three times, offered load can approach 2.5x, which guarantees it stays down: a retry storm, a form of metastable failure.

2. Amplification

user click
  SPA          1 + 3 retries = 4
   BFF         4 x 4         = 16
    Orders     16 x 4        = 64 calls to Payments

The fix is structural: retry at one layer. Inner layers should fail fast and return a clear status (503 with Retry-After) so the outer layer can decide.

3. Jitter

AWS's well-known analysis compares "full jitter" (delay = random(0, base * 2^attempt)) and "decorrelated jitter"; both reduce total work and completion time compared with plain exponential backoff. Polly v8 uses a decorrelated-jitter formula when UseJitter = true, and the standard resilience handler enables it by default.

4. Retry-After

RFC 9110 defines Retry-After as delay-seconds or an HTTP-date. It is meaningful on 503 (overload, maintenance), 429 (rate limit) and 3xx. Clients should treat it as a minimum and cap it (a misconfigured server sending 86,400 shouldn't stall a job for a day silently). HttpRetryStrategyOptions.ShouldRetryAfterHeader is true by default in Microsoft.Extensions.Http.Resilience.

5. Retry budgets

A budget limits retries to a fraction of normal traffic (for example retries may add at most 10% extra load per client). gRPC has built-in retry throttling (token-based); in .NET HTTP you approximate it with a circuit breaker (stop entirely after a failure ratio) and a client-side rate limiter on retries.

6. The server's role

  • Fail fast and cheaply under overload (load shedding returning 503 + Retry-After before doing work).
  • Make idempotency real: PUT/DELETE implementations without side effects on repeat, Idempotency-Key for POST.
  • Signal retryability: status codes chosen correctly, plus optionally a ProblemDetails extension member such as "retryable": true.
  • Publish retry guidance in the developer portal and SDKs.

Try it yourself

  1. Build a fake dependency that returns 503 for 50% of calls; put three HttpClient layers with retries in front and count calls at the bottom per top-level request.
  2. Add Retry-After: 5 to the 503 and confirm Polly waits at least 5 s.
  3. Plot delays from 1,000 simulated clients with and without jitter (a quick console app writing a CSV).
  4. Add a circuit breaker and watch calls drop to zero during the open state.

💻 Code

Server side: shed load with 503 and Retry-After, and mark errors as retryable or not. Client side: one retry layer that honours Retry-After.

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

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();

// The single retry layer, closest to the dependency.
builder.Services.AddHttpClient("payments", c => c.BaseAddress = new Uri("https://payments.internal"))
    .AddResilienceHandler("payments", pipeline =>
    {
        pipeline.AddRetry(new HttpRetryStrategyOptions
        {
            MaxRetryAttempts = 2,
            BackoffType = DelayBackoffType.Exponential,
            UseJitter = true,             // spread retries from many callers
            Delay = TimeSpan.FromMilliseconds(500),
            ShouldRetryAfterHeader = true // honour the server's Retry-After (the default)
            // ShouldHandle default: network errors, 408, 429 and 5xx.
        });
        pipeline.AddCircuitBreaker(new HttpCircuitBreakerStrategyOptions());
        pipeline.AddTimeout(TimeSpan.FromSeconds(3));
    });

var app = builder.Build();

var inFlight = 0;
const int MaxInFlight = 200;

// Load shedding before doing any work: cheap rejection with a retry hint.
app.Use(async (context, next) =>
{
    if (Interlocked.Increment(ref inFlight) > MaxInFlight)
    {
        Interlocked.Decrement(ref inFlight);
        context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
        context.Response.Headers.RetryAfter = "5";
        await Results.Problem(title: "Service busy", statusCode: 503,
            extensions: new Dictionary<string, object?> { ["retryable"] = true }).ExecuteAsync(context);
        return;
    }
    try { await next(context); }
    finally { Interlocked.Decrement(ref inFlight); }
});

app.MapPost("/orders", (CreateOrder order) =>
    order.Quantity <= 0
        // Validation failures are never retryable: say so.
        ? Results.Problem(title: "Invalid quantity", statusCode: 422,
            extensions: new Dictionary<string, object?> { ["retryable"] = false })
        : Results.Created($"/orders/{Guid.CreateVersion7()}", order));

app.Run();

public sealed record CreateOrder(string Sku, int Quantity);

⚠ Common mistakes

  • Mistake: Retrying every failure, including 400 and 422. Why it is wrong: the same request fails the same way and only adds load. Instead: retry network errors, 408, 429, 502, 503 and 504.
  • Mistake: Retrying POST without an idempotency key. Why it is wrong: a timeout may hide a success, so the retry creates a duplicate order or payment. Instead: accept and require Idempotency-Key on non-idempotent operations.
  • Mistake: Backoff without jitter. Why it is wrong: clients that failed together retry together, in waves. Instead: exponential backoff with jitter.
  • Mistake: Retries at every layer. Why it is wrong: attempts multiply (4 x 4 x 4 = 64). Instead: retry at one layer and have inner layers fail fast.
  • Mistake: No retry budget. Why it is wrong: per-request limits ("3 retries") still let retries add up to 3x the normal load during an outage, which keeps a recovering service down. Instead: cap retries as a share of traffic (for example at most 10% extra calls) with a circuit breaker or a rate limiter on retries.
  • Mistake: Ignoring Retry-After. Why it is wrong: the server knows when it will recover; the client is guessing. Instead: honour it as a minimum delay, with a sensible cap.
  • Mistake: Returning 500 for overload or rate limits. Why it is wrong: clients can't tell "bug" from "busy". Instead: 503 or 429 with Retry-After.
  • Mistake: Retrying silently. Why it is wrong: retries hide a degrading dependency until they stop working; nobody sees that 30% of calls needed a second attempt. Instead: log each retry with the attempt number and outcome (OnRetry), chart Polly's resilience events from the Polly meter, and alert when the retry rate rises.
  • Mistake: Unlimited retries in background jobs. Why it is wrong: poison requests retry forever and hide the real failure. Instead: cap attempts and dead-letter.

🏛 Senior insight: trade-offs

I think of retry policy as a system property, not a per-client setting. The worst outages I know of weren't caused by the first failure but by the retries: synchronised clients, retries at every layer, and nothing to stop them. So I decide in one design review where retries live (usually the hop closest to the dependency), make every other layer fail fast, and make the server's signals unambiguous: correct status codes, Retry-After, idempotency keys.

Measure retry rate as its own metric (Polly emits resilience events through the Polly meter; Application Insights shows dependency calls per request). If retries exceed a few percent of calls in normal operation, something is wrong and retries are hiding it.

Option When it fits Cost When not to
Client retries with jitter + Retry-After Public clients, SDKs Client discipline you don't control Non-idempotent calls without keys
Single server-side retry layer Internal service calls Latency on failure Deep chains where an outer layer already retries
No retry, fail fast Inner layers, user-facing calls with tight budgets User sees errors sooner Known-transient faults like 429 with short Retry-After

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions Polly or exponential backoff Why: Checks depth on the Retry pattern and Polly v8 implementation
    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.

  2. When: Candidate says only idempotent requests can be retried Why: Checks what safety and idempotency guarantee and how to test them
    How to answer

    A safe method (GET, HEAD, OPTIONS) asks for no state change; an idempotent one has the same effect on server state however many times it's repeated (safe methods plus PUT and DELETE). They matter because a timeout is ambiguous: the server may have done the work. Resilience handlers, gateways, service meshes and browsers retry on that basis, so only idempotent requests can be retried blindly.

    When a write must be retryable but isn't naturally idempotent (creating an order, taking a payment), you design idempotency in: PUT to a client-generated id, conditional requests with If-Match, an Idempotency-Key header that replays the stored result, or a unique constraint on a natural key. The trade-off is extra storage and complexity versus duplicate orders and double charges.

  3. When: Candidate says retries should stop when a dependency is down Why: Checks circuit breaker states and thresholds
    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

Retries at three layers turn a payment provider brownout into an outage
Situation
A [checkout] flow: [React SPA] -> [BFF] -> [order service] -> external [payments provider], each layer with its own 3-retry policy. Peak traffic [300] checkouts a minute.
Signals
Provider error rate rising from [5%] to [60%], our outbound calls to the provider up [10x] while checkouts were flat, provider returning 429s, customers seeing spinners for [40 s] before failing.
Investigation
Used the Application Insights end-to-end transaction view for one failed checkout and counted dependency calls per request (dozens), checked each HttpClient registration and the SPA's fetch wrapper for retry policies, and correlated with the provider's status page and 429 rate.
Resolution
Immediately disabled retries in the SPA and BFF via configuration. Then kept one retry layer in the order service (2 retries, jitter, Retry-After honoured) with a circuit breaker and an Idempotency-Key on every payment call, and returned 503 with Retry-After to the SPA when the breaker was open.
Prevention
An ADR stating retries live only at the hop closest to the dependency; a test counting provider calls per checkout under injected failures; dashboards for retry rate and breaker state; API docs listing retryable statuses.

How to tell it (STAR)

**S:** At [company], our payments provider had a partial outage and our checkout made it much worse. **T:** I had to work out why our calls to the provider went up [ten times] while orders stayed flat. **A:** Tracing one checkout in Application Insights, I found retries in the SPA, the BFF and the order service: up to 64 calls per click. I switched off the outer retries straight away, then left a single jittered retry layer with a circuit breaker and idempotency keys next to the provider, and had the API return 503 with Retry-After when the breaker was open. **R:** In the next brownout our provider traffic stayed within [10%] of normal, and checkouts recovered as soon as the provider did, instead of [an hour] later.

↩ Usually asked after

More in API Reliability

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me