Retry with Backoff and Jitter
Repeat a failed call that is likely to succeed next time, waiting longer and randomly between attempts so retries do not overload the system.
On this page
Problem
Distributed systems fail transiently all the time: a connection is reset during a deploy, a leader election takes a second, a pod is rescheduled, a request lands on a node that just ran out of memory. Without retries, each of these blips becomes a user-visible error even though the same call would succeed a moment later.
Naive retries create the opposite problem. Retrying immediately, many times, from every layer of the stack multiplies load exactly when a dependency is weakest. If three layers each retry three times, one user request can turn into 27 calls to the bottom service, and thousands of clients retrying in lockstep produce synchronised waves of traffic.
Context
Use this pattern when:
- The failure is plausibly transient: timeouts, connection errors, 503 Service Unavailable, 429 Too Many Requests, or explicit "try again" error codes.
- The operation is idempotent, or can be made idempotent with an idempotency key, so a duplicate attempt is harmless.
- The caller has time budget left: retrying is useless if the user's overall deadline has already passed.
- Many clients may fail at the same moment, so their retries must not stay synchronised.
Solution
Classify the failure first. Retry only errors that can succeed on a second attempt; fail immediately on validation errors, authentication failures and 4xx responses other than 408 and 429.
Wait before each attempt, doubling the delay each time (exponential backoff) up to a cap, and randomise it (jitter). Full jitter picks a uniform random delay between zero and the exponential value, which spreads simultaneous clients across the whole window and empties the queue fastest. Honour a server-provided Retry-After header when present.
Bound the total effort: a maximum attempt count, an overall deadline, and ideally a retry budget that limits retries to a small fraction (for example 10%) of total traffic so retries can never multiply load during an outage. Retry at one layer only, usually the one closest to the failing call.
How it works, step by step
- 1Execute the call; on success return the result.
- 2On failure, decide whether the error is transient and the operation safe to repeat. If not, rethrow.
- 3If attempts are exhausted, the deadline would be exceeded, or the retry budget is empty, rethrow.
- 4Compute delay = random(0, min(cap, base × 2^attempt)), or use Retry-After if provided.
- 5Sleep for the delay (respecting cancellation) and try again.
Implementation
Polly v8 handles backoff, jitter and attempt limits declaratively in .NET. The TypeScript helper shows the mechanics explicitly, including error classification and a deadline.
using System.Net;
using Polly;
using Polly.Retry;
var retryOptions = new RetryStrategyOptions<HttpResponseMessage>
{
MaxRetryAttempts = 3,
BackoffType = DelayBackoffType.Exponential,
Delay = TimeSpan.FromMilliseconds(200),
MaxDelay = TimeSpan.FromSeconds(5),
UseJitter = true,
// Retry only failures that can succeed next time.
ShouldHandle = new PredicateBuilder<HttpResponseMessage>()
.Handle<HttpRequestException>()
.Handle<TimeoutException>()
.HandleResult(r => r.StatusCode is HttpStatusCode.TooManyRequests
or HttpStatusCode.ServiceUnavailable
or HttpStatusCode.BadGateway
or HttpStatusCode.GatewayTimeout),
// Prefer the server's own hint when it sends one.
DelayGenerator = args =>
{
var retryAfter = args.Outcome.Result?.Headers.RetryAfter?.Delta;
return ValueTask.FromResult(retryAfter);
},
OnRetry = args =>
{
Console.WriteLine($"Retry {args.AttemptNumber + 1} after {args.RetryDelay}");
return ValueTask.CompletedTask;
},
};
ResiliencePipeline<HttpResponseMessage> pipeline = new ResiliencePipelineBuilder<HttpResponseMessage>()
.AddRetry(retryOptions)
.AddTimeout(TimeSpan.FromSeconds(2)) // per attempt
.Build();
using var http = new HttpClient { BaseAddress = new Uri("https://payments.internal") };
using var response = await pipeline.ExecuteAsync(
async ct => await http.GetAsync("/v1/charges/ch_123", ct),
CancellationToken.None);When DelayGenerator returns null, Polly falls back to the configured exponential backoff with jitter. Placing the timeout after the retry makes it apply to each attempt.
type RetryOptions = {
attempts?: number;
baseMs?: number;
capMs?: number;
deadlineMs?: number;
};
export class HttpError extends Error {
constructor(readonly status: number, readonly retryAfterMs?: number) {
super('HTTP ' + status);
}
}
const RETRYABLE_STATUS = new Set([408, 429, 502, 503, 504]);
function isRetryable(error: unknown): boolean {
if (error instanceof HttpError) return RETRYABLE_STATUS.has(error.status);
// Network failures and per-attempt timeouts from fetch.
return error instanceof TypeError || (error instanceof DOMException && error.name === 'TimeoutError');
}
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
export async function withRetry<T>(fn: () => Promise<T>, options: RetryOptions = {}): Promise<T> {
const { attempts = 4, baseMs = 200, capMs = 5_000, deadlineMs = 10_000 } = options;
const deadline = Date.now() + deadlineMs;
for (let attempt = 0; ; attempt++) {
try {
return await fn();
} catch (error) {
const last = attempt + 1 >= attempts;
if (last || !isRetryable(error)) throw error;
const backoff = Math.random() * Math.min(capMs, baseMs * 2 ** attempt);
const delay = error instanceof HttpError && error.retryAfterMs !== undefined ? error.retryAfterMs : backoff;
if (Date.now() + delay >= deadline) throw error;
await sleep(delay);
}
}
}Wrap each attempt in its own timeout, for example fetch(url, { signal: AbortSignal.timeout(2000) }), and convert non-2xx responses into HttpError inside fn.
In production
- Only retry idempotent operations, or send an idempotency key so the server can deduplicate a repeated POST.
- Retry at a single layer. If the API gateway, the service and the client library all retry, attempts multiply.
- Track a retry budget (retries as a share of requests); when it is exhausted, fail fast instead of retrying.
- Log the final failure with the attempt count, not every intermediate attempt, to avoid drowning the logs during an outage.
- Combine with a circuit breaker so retries stop entirely once a dependency is known to be down.
Trade-offs
Benefits
- Hides transient faults from users at almost no cost when the system is healthy.
- Backoff with jitter spreads retry traffic over time instead of creating synchronised spikes.
- Easy to adopt incrementally with standard libraries.
Costs
- Adds latency: a request that eventually fails takes longer to fail.
- Amplifies load during real outages unless capped by attempts, deadlines and a budget.
- Unsafe for non-idempotent operations, where a retry after an ambiguous timeout can charge a customer twice.
- Can mask a degrading dependency; error rates look fine while latency and load creep up.
Alternatives
- Fail fast and let the user retry
- Appropriate for interactive operations where the user can decide, or when the latency budget is already spent.
- Asynchronous retry through a queue
- Put the work on a queue and let a consumer retry with long delays and a dead letter queue at the end; better for background work than blocking a request.
- Hedged requests
- Send a second request to another replica if the first is slow, trading extra load for lower tail latency on read-only calls.
Anti-patterns
- Immediate retries in a tight loop
- Retrying without delay hammers a dependency that just failed and almost always fails again for the same reason.
- Retrying at every layer
- Nested retries multiply: three layers with three attempts each can turn one request into 27 downstream calls.
- Retrying non-transient errors
- Retrying 400, 401 or 404 wastes time and resources because the answer will not change.
- Backoff without jitter
- Clients that failed together retry together, producing waves of traffic at 1 s, 2 s, 4 s that keep knocking the dependency over.
Related lessons
Interview questions
Which failures should be retried and which should not?
Retry transient failures: connection errors, timeouts, 502, 503, 504, 429 and 408. Do not retry client errors such as 400, 401, 403 or 404, or business rule violations, because repeating the same request produces the same answer.
Why add jitter to exponential backoff?
Without jitter, every client that failed at the same moment retries at the same moments, so the dependency sees synchronised spikes. Randomising the delay spreads retries uniformly across the window, which smooths load and lets the dependency recover.
How do you make retrying a payment request safe?
Send a client-generated idempotency key with the request and have the server store the result keyed by it. A retried request with the same key returns the stored result instead of charging again, which makes ambiguous timeouts safe to retry.
What is a retry budget and why use one?
A retry budget caps retries at a fraction of normal traffic, for example 10%. During a broad outage most calls fail, and per-request attempt limits still allow retries to double or triple load; a budget keeps total load close to normal and turns the extra failures into fast errors.