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.
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.
"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,
HttpRequestExceptionand 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 theRetry-Afterheader 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 = ExponentialandUseJitter = 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 withAddStandardResilienceHandler, 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 PollyResiliencePipelinewithAddRetry. For EF Core,EnableRetryOnFailurehandles 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."
| 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 |
| 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 |
| Layers each retrying 3 times (4 attempts) | Calls to the failing dependency |
|---|---|
| 1 | 4 |
| 2 | 16 |
| 3 | 64 |
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%.
Checks whether the candidate can apply retries safely: classifying faults, backing off with jitter, ensuring idempotency and avoiding amplification.
Green flags
Retry-After.Red flags
Policy.Handle().WaitAndRetry as current.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) __|
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.
A timeout doesn't tell you whether the server processed the request. Retrying a non-idempotent operation can duplicate it. Options:
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.Retries add load exactly when the dependency is weakest. Mitigations:
ShouldHandle logic, or provided by a service mesh.Retry-After.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.
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.
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.
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.
OnRetry delays and compare.HttpClient at a stub returning 503 with Retry-After: 3 and verify the delay.DisableForUnsafeHttpMethods() and confirm a failing POST isn't retried.dotnet-counters monitor --counters Polly.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);
}
ShouldHandle.DisableForUnsafeHttpMethods().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).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.
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.
All three symptoms come from wrapper order and duplication. The outermost decorator or handler runs first and can short-circuit everything inside it.
AddStandardResilienceHandler. The standard pipeline is already rate limiter → total timeout → retry → circuit breaker → attempt timeout.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.
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:
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.
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.
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].
Last updated 18 Nov 2026.