Conceptcore
Retry with backoff
Also called exponential backoff, retry, backoff, jitter, retry policy, retry budget.
A retry calls a failed operation again, in case the failure was temporary. Backoff makes each wait longer, and jitter makes it random, so that retries do not overload the service that failed.
- Applies to
- core-languages
Idea
Some failures go away by themselves. A server restarts, a network link drops a packet, a database lock is released, a rate limit resets. If the program calls the same operation again a little later, the call can succeed. A retry is this second call.
A retry is easy to write and easy to get wrong. If every client retries at once, the retries arrive as one more burst of load on a service that is already in trouble. Marc Brooker calls retries "selfish": a client that retries takes more of the capacity of the server to make its own success more likely.3 Two techniques keep retries safe for the service. Backoff makes each wait longer than the one before. Jitter makes each wait random, so that clients that failed at the same moment do not retry at the same moment.
This Python program prints the limits of a capped exponential backoff, and one random wait below each limit. The wait before attempt n+1 is a random number between 0 and min(cap, base * 2**n).
import random
base, cap = 100, 1000 # milliseconds
rng = random.Random(7)
for attempt in range(6):
limit = min(cap, base * 2**attempt)
print(f"retry {attempt + 1}: limit {limit:4} ms, wait {rng.randint(0, limit):4} ms")
retry 1: limit 100 ms, wait 41 ms
retry 2: limit 200 ms, wait 38 ms
retry 3: limit 400 ms, wait 202 ms
retry 4: limit 800 ms, wait 666 ms
retry 5: limit 1000 ms, wait 49 ms
retry 6: limit 1000 ms, wait 74 ms
A retry policy answers five questions. Which failures are worth a retry? How many attempts are allowed? How long is the wait before each attempt? What is the total time limit? Is the operation safe to do twice? The sections below take these in turn.
How it works
Which failures to retry
A retry helps only when the next attempt can give a different result. The error must say which kind of failure happened, so the caller can decide (Error value, Exception).
| Worth a retry | Not worth a retry |
|---|---|
| a timeout, or a connection reset before the response | a request that is not valid, such as HTTP 400 |
| HTTP 503 Service Unavailable, HTTP 429 Too Many Requests | a missing resource, HTTP 404 |
EAGAIN and EINTR from a system call |
EINVAL, wrong arguments |
exit status 75, EX_TEMPFAIL |
exit status 64, EX_USAGE |
| a serialization failure of a database transaction, SQLSTATE 40001 | a constraint violation |
The C example retries on EAGAIN ("Resource unavailable, try again") and EINTR ("Interrupted function"), and stops on EINVAL ("Invalid argument").12 The Bash example uses the exit codes of sysexits.h, where EX_TEMPFAIL marks a temporary failure and EX_USAGE marks a command that was called wrongly.11 The TypeScript example puts the kinds of outcome in a union type, so the compiler checks that the policy handles each one (Sum types).
A database also gives errors that are worth a retry. PostgreSQL says that applications at the Repeatable Read and Serializable isolation levels "must be prepared to retry transactions due to serialization failures", and that such failures always return the SQLSTATE 40001.16
How long to wait
Let base be the first wait, cap the longest wait, and n the number of attempts that have failed. Brooker's article compares four schedules.2
- Exponential backoff. Wait
min(cap, base * 2**n). The waits double until they reach the cap. All clients that failed at the same moment wait the same time, so they collide again. - Full jitter. Wait a random time between 0 and
min(cap, base * 2**n). The Python, Go, Rust and Bash examples use this schedule. - Equal jitter. Let
v = min(cap, base * 2**n). Waitv/2plus a random time between 0 andv/2. No wait is very short. The C example uses this schedule. - Decorrelated jitter. Wait
min(cap, random(base, 3 * previous_wait)). Each wait depends on the one before it, not on the attempt number. The C++ example uses this schedule.
In Brooker's simulation of 100 clients that contend for one resource, jitter "reduced our call count by more than half". Of the jittered schedules, Brooker calls equal jitter "the loser": it does slightly more work than full jitter and takes much longer. Decorrelated jitter makes more calls than full jitter, and full jitter takes a little more time.2 Brooker recommends jittered backoff as "a standard approach for remote clients".2
The cap keeps the waits finite. Without a cap, the waits grow without limit. The Rust example shows that after 20 failed attempts, a base of 100 ms gives a wait of more than 29 hours.
A server can say how long to wait. The HTTP header Retry-After carries either a date or a number of seconds. With a 503 response, it says how long the service is expected to be unavailable.5 A 429 response can include it too.14 The JavaScript example waits for the longer of the hint and its own backoff.
How long to try
A retry loop needs two limits: a number of attempts and a total time. The number of attempts stops a loop that fails fast. The total time stops a loop that fails slowly, where each attempt waits for a long timeout.
The total time usually comes from the caller. A user waits a few seconds for a page, and work after that is wasted. The Google SRE book says that servers "should employ deadline propagation": the deadline of the incoming request becomes the limit of each call that the server makes for it.4 In Go, context.WithDeadline gives a child context whose deadline is "no later than" the one asked for. If the parent's deadline is earlier, the child keeps the deadline of the parent.8 The Go example shows a call that asks for an hour and stops after the 20 ms of its request. The Python example stops when the next wait would pass its deadline.
The timeout of each attempt is a separate choice. Brooker suggests that a team picks a rate of false timeouts that it accepts, such as 0.1%, and sets the timeout from the matching latency percentile of the service that it calls, here p99.9.3
Is it safe to do twice
A failed call does not prove that nothing happened. When a connection breaks after the server has done the work but before the response arrives, the client sees a failure. A retry then does the work a second time. The Go example double-charge shows a payment that a retry charges twice.
An operation is idempotent when two identical calls have the same effect as one. HTTP defines PUT, DELETE and the safe methods such as GET as idempotent.5 Brooker writes that "APIs with side effects aren't safe to retry unless they provide idempotency".3
An idempotency key makes an operation safe to retry. The client makes a unique key for each logical operation and sends the same key with every attempt. Stripe saves the status code and the body of the first request with a given key, and it returns the saved response to a retry with that key, even a 500 error. Stripe compares the parameters of the retry with those of the first request and returns an error if they differ. Keys can be removed after they are at least 24 hours old.7 The Java example keeps such a table of keys on the server, and the charge happens once although the server receives it three times.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Standard library | |
| C++ | Standard library | |
| Java | Standard library | |
| C | Absent | |
| C# | Standard library | |
| JavaScript | Standard library | |
| TypeScript | Standard library | |
| Go | Standard library | |
| Rust | Standard library | |
| Kotlin | Idiom | Kotlin on the JVM uses the same loop as Java, or the delay function in a coroutine; no example file in this version. Alternative: A loop with Thread.sleep and java.util.Random, as in the Java example. |
| SQL | Absent | A statement does not retry itself; the client retries a transaction that fails with a serialization failure, SQLSTATE 40001. Alternative: The retry loop of the host language around the whole transaction. |
| Bash | Idiom | |
| PowerShell | Native | Invoke-RestMethod has the parameters MaximumRetryCount and RetryIntervalSec; the interval is fixed, and it retries every status from 400 to 599; no example file because pwsh is not installed on the machine that recorded the examples. Alternative: A loop with try and catch and Start-Sleep for a backoff with jitter. |
| HTML | Does not apply | Markup does not call anything that can fail. |
| CSS | Does not apply | Style rules do not call anything that can fail. |
| Regular expressions | Does not apply | A pattern does not call anything that can fail. |
No tier 1 language has a general retry function in its standard library. The parts come from the standard library: a way to sleep, a random number generator, a clock, and a way to tell the kinds of error apart. The example files build the loop from those parts. Each one keeps time in a counter in place of a real sleep and seeds its generator, so the output is the same on each run.
| Language | Verdict | Form |
|---|---|---|
| Python | stdlib | a loop with random and time.sleep; exception classes say which errors are transient |
| JavaScript | stdlib | a loop around an async call; Retry-After from the response |
| TypeScript | stdlib | as JavaScript; a union type of outcomes with an exhaustive switch |
| Java | stdlib | a loop with java.util.Random; an idempotency key in the example |
| C | absent | a loop that reads errno; equal jitter |
| C++ | stdlib | <random> and <chrono>; decorrelated jitter |
| C# | stdlib | a loop with a token bucket as a retry budget |
| Go | stdlib | a loop with errors.Is; context carries the deadline |
| Rust | stdlib | a loop with match on the error kind; no random generator in std |
| Kotlin | idiom | the same loop as Java, or delay in a coroutine |
| PowerShell | native | Invoke-RestMethod -MaximumRetryCount -RetryIntervalSec, with a fixed interval |
| Bash | idiom | a loop on the exit status $?, with sleep |
| SQL | absent | the client retries a transaction that fails with SQLSTATE 40001 |
| Regex | n/a | a pattern does not call anything that can fail |
| HTML/CSS | n/a | markup and style rules do not call anything that can fail |
Libraries and frameworks supply retry policies on top of these parts. gRPC reads a retry policy from the service config, with the fields maxAttempts, initialBackoff, maxBackoff, backoffMultiplier and retryableStatusCodes. It applies a jitter of plus or minus 20% to each wait.9 PowerShell's Invoke-RestMethod has a retry built in. It retries on "a failure code between 400 and 599, inclusive or 304", at the fixed interval of -RetryIntervalSec. For a 429 response with a Retry-After header, it waits for the time in the header.15 Because the interval is fixed and the range includes the 4xx codes, it also retries requests that cannot succeed, and many clients that fail together retry together.
Some notes on the examples:
- C++. The engine
std::mt19937gives the same sequence on every implementation, but "the algorithms for producing each of the specified distributions are implementation-defined".13 The output ofuniform_int_distributioncan differ between standard libraries. - Rust. The standard library has no random number generator, so the example uses a xorshift generator of a few lines.
- JavaScript.
Math.randomcannot take a seed, so the example uses a small linear congruential generator.
import random
class FakeClock:
def __init__(self):
self.now = 0 # milliseconds
def sleep(self, ms):
self.now += ms
class TransientError(Exception):
pass
class PermanentError(Exception):
pass
def retry(op, clock, rng, attempts=5, base=100, cap=1000, deadline=2000):
for attempt in range(attempts):
try:
return op()
except TransientError as exc:
if attempt == attempts - 1:
raise
delay = rng.randint(0, min(cap, base * 2**attempt))
if clock.now + delay > deadline:
raise TimeoutError(f"the deadline of {deadline} ms would pass") from exc
print(f" t={clock.now:4} ms: attempt {attempt + 1} failed ({exc}); wait {delay} ms")
clock.sleep(delay)
def service(failures, error=TransientError("503 Service Unavailable")):
calls = 0
def call():
nonlocal calls
calls += 1
if calls <= failures:
raise error
return f"200 OK after {calls} calls"
return call
rng = random.Random(42)
for name, op in [
("flaky", service(3)),
("bad request", service(1, PermanentError("400 Bad Request"))),
("down", service(100)),
]:
print(name)
try:
print(" result:", retry(op, FakeClock(), rng))
except (PermanentError, TransientError, TimeoutError) as exc:
print(" gave up:", type(exc).__name__, exc)
flaky
t= 0 ms: attempt 1 failed (503 Service Unavailable); wait 81 ms
t= 81 ms: attempt 2 failed (503 Service Unavailable); wait 28 ms
t= 109 ms: attempt 3 failed (503 Service Unavailable); wait 12 ms
result: 200 OK after 4 calls
bad request
gave up: PermanentError 400 Bad Request
down
t= 0 ms: attempt 1 failed (503 Service Unavailable); wait 94 ms
t= 94 ms: attempt 2 failed (503 Service Unavailable); wait 70 ms
t= 164 ms: attempt 3 failed (503 Service Unavailable); wait 125 ms
t= 289 ms: attempt 4 failed (503 Service Unavailable); wait 228 ms
gave up: TransientError 503 Service Unavailable
- Verdict: stdlib. Python has no retry function in the standard library. The loop above uses only
randomfor the jitter. - The delay before attempt n+1 is a random number between 0 and
min(cap, base * 2**n). This is the "full jitter" of the AWS article. - The loop retries only
TransientError. A400 Bad Requestwill fail again, so the loop raises it at once. - The fake clock records the time that the loop would wait, and the seeded generator gives the same delays on each run.
Without jitter, clients that fail at the same moment retry at the same moments too. Here 100 clients back off from one failure, and each retry round arrives as one burst.
This code runs but gives a wrong answer on purpose.
from collections import Counter
calls = Counter()
for client in range(100):
t = 0
for attempt in range(4):
calls[t] += 1
t += 100 * 2**attempt
for t in sorted(calls):
print(f"t={t:4} ms: {calls[t]} calls")
t= 0 ms: 100 calls
t= 100 ms: 100 calls
t= 300 ms: 100 calls
t= 700 ms: 100 calls
#include <algorithm>
#include <chrono>
#include <iostream>
#include <random>
using std::chrono::milliseconds;
struct FakeClock {
milliseconds now{0};
void sleep(milliseconds d) { now += d; }
};
int main() {
const milliseconds base{100}, cap{2000};
std::mt19937 rng(2024);
FakeClock clock;
milliseconds sleep = base;
for (int attempt = 1; attempt <= 8; ++attempt) {
long long low = base.count(), high = sleep.count() * 3;
sleep = std::min(cap, milliseconds{low + static_cast<long long>(rng() % (high - low + 1))});
std::cout << "t=" << clock.now.count() << " ms: attempt " << attempt
<< " failed; wait " << sleep.count() << " ms\n";
clock.sleep(sleep);
}
std::cout << "gave up at t=" << clock.now.count() << " ms\n";
}
t=0 ms: attempt 1 failed; wait 120 ms
t=120 ms: attempt 2 failed; wait 336 ms
t=456 ms: attempt 3 failed; wait 488 ms
t=944 ms: attempt 4 failed; wait 735 ms
t=1679 ms: attempt 5 failed; wait 727 ms
t=2406 ms: attempt 6 failed; wait 1350 ms
t=3756 ms: attempt 7 failed; wait 1928 ms
t=5684 ms: attempt 8 failed; wait 2000 ms
gave up at t=7684 ms
- Verdict: stdlib. C++ has no retry facility.
<random>gives a seeded generator, and<chrono>gives typed durations, so a delay cannot be mixed up with a count. - This is the "decorrelated jitter" of the AWS article: each sleep is a random value between the base and three times the previous sleep, capped. The delays grow on average but do not follow a fixed curve.
- The output is the same on each run and with each standard library.
std::mt19937is fully specified, but the algorithm ofuniform_int_distributionis left to the implementation, so this code takes the remainder of the raw value. The remainder has a small bias, which does not matter for a delay.
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class Main {
static class ConnectionLost extends RuntimeException {
ConnectionLost(String message) { super(message); }
}
static class Server {
int balance = 500;
int calls = 0;
final Map<String, String> receipts = new HashMap<>();
String charge(String idempotencyKey, int amount) {
calls++;
String earlier = receipts.get(idempotencyKey);
if (earlier != null) return earlier;
balance -= amount;
String receipt = "receipt " + (receipts.size() + 1);
receipts.put(idempotencyKey, receipt);
if (calls == 1) throw new ConnectionLost("connection reset before the response");
return receipt;
}
}
static long now = 0;
static String chargeWithRetry(Server server, String key, int amount, Random rng) {
long base = 100, cap = 1000;
for (int attempt = 0; ; attempt++) {
try {
return server.charge(key, amount);
} catch (ConnectionLost e) {
if (attempt == 4) throw e;
long delay = rng.nextLong(Math.min(cap, base << attempt) + 1);
System.out.printf("t=%d ms: attempt %d failed (%s); wait %d ms%n", now, attempt + 1, e.getMessage(), delay);
now += delay;
}
}
}
public static void main(String[] args) {
Server server = new Server();
Random rng = new Random(42);
String key = "order-7781";
System.out.println("result: " + chargeWithRetry(server, key, 100, rng));
System.out.println("balance: " + server.balance + ", calls: " + server.calls);
System.out.println("again: " + chargeWithRetry(server, key, 100, rng));
System.out.println("balance: " + server.balance + ", calls: " + server.calls);
}
}
t=0 ms: attempt 1 failed (connection reset before the response); wait 2 ms
result: receipt 1
balance: 400, calls: 2
again: receipt 1
balance: 400, calls: 3
- Verdict: stdlib. Java has no retry method in the standard library. The loop uses
java.util.Randomwith a fixed seed for the jitter, and a counter in place of a clock. - The client sends the same idempotency key with each attempt. The server stores the result of the first charge under the key, and it returns that result for a repeated request. The charge happens once, though the server receives it three times.
- A charge is not idempotent by nature. The key makes the operation safe to retry.
#include <errno.h>
#include <stdio.h>
static int calls = 0;
static long now_ms = 0;
static int send_report(int failures, int error) {
calls++;
if (calls <= failures) {
errno = error;
return -1;
}
return 0;
}
static unsigned next_random(unsigned *state) {
*state = *state * 1103515245u + 12345u;
return (*state >> 16) & 0x7fff;
}
static int with_retry(int failures, int error, unsigned *rng) {
long base = 100, cap = 1000;
for (int attempt = 0; attempt < 5; attempt++) {
if (send_report(failures, error) == 0)
return 0;
if (errno != EAGAIN && errno != EINTR)
return -1;
long limit = base << attempt;
if (limit > cap)
limit = cap;
long half = limit / 2;
long delay = half + (long)(next_random(rng) % (unsigned)(half + 1));
printf(" t=%4ld ms: attempt %d failed (%s); wait %ld ms\n", now_ms, attempt + 1,
errno == EAGAIN ? "EAGAIN" : "EINTR", delay);
now_ms += delay;
}
return -1;
}
int main(void) {
unsigned rng = 1;
puts("busy");
calls = 0, now_ms = 0;
int ok = with_retry(2, EAGAIN, &rng);
printf(" result %d after %d calls\n", ok, calls);
puts("bad argument");
calls = 0, now_ms = 0;
int rc = with_retry(1, EINVAL, &rng);
printf(" result %d after %d calls, errno is %s\n", rc, calls, errno == EINVAL ? "EINVAL" : "other");
return 0;
}
busy
t= 0 ms: attempt 1 failed (EAGAIN); wait 58 ms
t= 58 ms: attempt 2 failed (EAGAIN); wait 101 ms
result 0 after 3 calls
bad argument
result -1 after 1 calls, errno is EINVAL
- Verdict: absent. C has no retry facility and no exceptions. A failed call returns
-1and setserrno, and the caller readserrnoto decide. EAGAINandEINTRmean that the same call can succeed later, so the loop retries them.EINVALmeans that the arguments are wrong, so a retry cannot help.- This loop uses "equal jitter": half of the backoff is fixed and the other half is random, so no wait is very short.
Retries at several layers multiply. Here three layers each make up to four attempts, so one request from the user reaches the failing database 64 times.
This code runs but gives a wrong answer on purpose.
#include <stdio.h>
static int database_calls = 0;
static int database(void) {
database_calls++;
return -1;
}
static int with_retries(int (*call)(void)) {
for (int attempt = 0; attempt < 4; attempt++)
if (call() == 0)
return 0;
return -1;
}
static int backend(void) { return with_retries(database); }
static int frontend(void) { return with_retries(backend); }
static int client(void) { return with_retries(frontend); }
int main(void) {
client();
printf("database calls for one user request: %d\n", database_calls);
return 0;
}
database calls for one user request: 64
using System;
var budget = new RetryBudget(capacity: 5, refillEveryMs: 1000);
long now = 0;
int calls = 0;
for (int request = 1; request <= 10; request++)
{
int retries = 0;
for (int attempt = 0; attempt < 4; attempt++)
{
calls++;
bool ok = false;
if (ok || attempt == 3) break;
if (!budget.TryTake(now)) break;
retries++;
}
Console.WriteLine($"t={now,5} ms: request {request,2} failed after {retries} retries");
now += 400;
}
Console.WriteLine($"calls with a budget: {calls}");
Console.WriteLine($"calls without a budget: {10 * 4}");
sealed class RetryBudget(int capacity, long refillEveryMs)
{
private int tokens = capacity;
private long lastRefill = 0;
public bool TryTake(long now)
{
long earned = (now - lastRefill) / refillEveryMs;
if (earned > 0)
{
tokens = (int)Math.Min(capacity, tokens + earned);
lastRefill += earned * refillEveryMs;
}
if (tokens == 0) return false;
tokens--;
return true;
}
}
t= 0 ms: request 1 failed after 3 retries
t= 400 ms: request 2 failed after 2 retries
t= 800 ms: request 3 failed after 0 retries
t= 1200 ms: request 4 failed after 1 retries
t= 1600 ms: request 5 failed after 0 retries
t= 2000 ms: request 6 failed after 1 retries
t= 2400 ms: request 7 failed after 0 retries
t= 2800 ms: request 8 failed after 0 retries
t= 3200 ms: request 9 failed after 1 retries
t= 3600 ms: request 10 failed after 0 retries
calls with a budget: 18
calls without a budget: 40
- Verdict: stdlib. .NET has no retry type in the base class library. The example keeps time in a counter, so it runs at once.
- Each retry costs a token from a shared bucket, and the bucket earns one token each second. While the dependency is down, most requests fail at once, and the load from retries stays near one call each second.
- Without the budget, every request makes four calls, and the failing dependency gets four times the normal load.
function seeded(seed) {
let s = seed >>> 0;
return () => {
s = (Math.imul(s, 1664525) + 1013904223) >>> 0;
return s / 2 ** 32;
};
}
const clock = {
now: 0,
async sleep(ms) {
this.now += ms;
},
};
const responses = [
{ status: 503, retryAfter: 2 },
{ status: 503 },
{ status: 200, body: "report.pdf" },
];
async function fetchReport() {
return responses.shift();
}
async function withRetry(op, { attempts = 5, base = 100, cap = 5000, random }) {
for (let attempt = 0; attempt < attempts; attempt++) {
const res = await op();
if (res.status < 500 && res.status !== 429) return res;
if (attempt === attempts - 1) return res;
const backoff = Math.floor(random() * Math.min(cap, base * 2 ** attempt));
const hint = res.retryAfter === undefined ? 0 : res.retryAfter * 1000;
const delay = Math.max(backoff, hint);
console.log(`t=${clock.now} ms: status ${res.status}; wait ${delay} ms`);
await clock.sleep(delay);
}
}
const res = await withRetry(fetchReport, { random: seeded(7) });
console.log(`t=${clock.now} ms: status ${res.status}, body ${res.body}`);
t=0 ms: status 503; wait 2000 ms
t=2000 ms: status 503; wait 182 ms
t=2182 ms: status 200, body report.pdf
- Verdict: stdlib. JavaScript has no retry function in the language or in Node.js. The loop is ordinary code around an
asynccall. - A server can send the header
Retry-Afterwith a503response to say how long the service is expected to be unavailable. The value is a date or a number of seconds. The client here waits for the longer of the hint and its own backoff. Math.randomcannot take a seed, so the example uses a small linear congruential generator. Its output is the same on each run.
type Outcome =
| { kind: "ok"; value: string }
| { kind: "transient"; reason: string }
| { kind: "throttled"; retryAfterMs: number }
| { kind: "permanent"; reason: string };
type Decision = { retry: false } | { retry: true; delayMs: number };
function decide(outcome: Outcome, attempt: number, random: () => number): Decision {
const backoff = Math.floor(random() * Math.min(1000, 100 * 2 ** attempt));
switch (outcome.kind) {
case "ok":
case "permanent":
return { retry: false };
case "transient":
return { retry: true, delayMs: backoff };
case "throttled":
return { retry: true, delayMs: Math.max(backoff, outcome.retryAfterMs) };
default: {
const unhandled: never = outcome;
return unhandled;
}
}
}
function run(outcomes: Outcome[], random: () => number): void {
let now = 0;
for (let attempt = 0; attempt < outcomes.length; attempt++) {
const outcome = outcomes[attempt];
const d = decide(outcome, attempt, random);
if (!d.retry) {
console.log(` t=${now} ms: ${outcome.kind}, stop`);
return;
}
console.log(` t=${now} ms: ${outcome.kind}, wait ${d.delayMs} ms`);
now += d.delayMs;
}
console.log(` t=${now} ms: out of attempts`);
}
let seed = 11;
const random = () => {
seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
return seed / 2 ** 32;
};
console.log("flaky");
run([{ kind: "transient", reason: "503" }, { kind: "throttled", retryAfterMs: 1500 }, { kind: "ok", value: "done" }], random);
console.log("bad request");
run([{ kind: "permanent", reason: "400" }], random);
flaky
t=0 ms: transient, wait 24 ms
t=24 ms: throttled, wait 1500 ms
t=1524 ms: ok, stop
bad request
t=0 ms: permanent, stop
- Verdict: stdlib. TypeScript adds no retry construct. A union type lists the outcomes of a call, and the checker makes the retry policy handle each one.
- The
neverin thedefaultbranch fails to compile if someone adds a new kind of outcome and forgets to decide whether it is worth a retry. - The policy is a pure function. It takes the attempt number and a source of random numbers, so a test can call it without a clock or a network.
package main
import (
"errors"
"fmt"
"math/rand/v2"
)
var ErrTransient = errors.New("503 Service Unavailable")
var ErrPermanent = errors.New("400 Bad Request")
type fakeClock struct{ now int }
func (c *fakeClock) Sleep(ms int) { c.now += ms }
func retry(op func() (string, error), clock *fakeClock, rng *rand.Rand) (string, error) {
const attempts, base, limit = 5, 100, 1000
var err error
for attempt := 0; attempt < attempts; attempt++ {
var result string
result, err = op()
if err == nil {
return result, nil
}
if !errors.Is(err, ErrTransient) {
return "", fmt.Errorf("attempt %d: %w", attempt+1, err)
}
if attempt == attempts-1 {
break
}
delay := rng.IntN(min(limit, base<<attempt) + 1)
fmt.Printf(" t=%4d ms: attempt %d failed (%v); wait %d ms\n", clock.now, attempt+1, err, delay)
clock.Sleep(delay)
}
return "", fmt.Errorf("gave up after %d attempts: %w", attempts, err)
}
func service(failures int, failure error) func() (string, error) {
calls := 0
return func() (string, error) {
calls++
if calls <= failures {
return "", failure
}
return fmt.Sprintf("200 OK after %d calls", calls), nil
}
}
func main() {
rng := rand.New(rand.NewPCG(1, 2))
cases := []struct {
name string
op func() (string, error)
}{
{"flaky", service(3, ErrTransient)},
{"bad request", service(1, ErrPermanent)},
{"down", service(100, ErrTransient)},
}
for _, c := range cases {
fmt.Println(c.name)
result, err := retry(c.op, &fakeClock{}, rng)
if err != nil {
fmt.Println(" error:", err)
continue
}
fmt.Println(" result:", result)
}
}
flaky
t= 0 ms: attempt 1 failed (503 Service Unavailable); wait 77 ms
t= 77 ms: attempt 2 failed (503 Service Unavailable); wait 123 ms
t= 200 ms: attempt 3 failed (503 Service Unavailable); wait 314 ms
result: 200 OK after 4 calls
bad request
error: attempt 1: 400 Bad Request
down
t= 0 ms: attempt 1 failed (503 Service Unavailable); wait 80 ms
t= 80 ms: attempt 2 failed (503 Service Unavailable); wait 47 ms
t= 127 ms: attempt 3 failed (503 Service Unavailable); wait 16 ms
t= 143 ms: attempt 4 failed (503 Service Unavailable); wait 400 ms
error: gave up after 5 attempts: 503 Service Unavailable
package main
import (
"context"
"errors"
"fmt"
"time"
)
func fetch(ctx context.Context) error {
select {
case <-time.After(time.Second):
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func main() {
request, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
call, cancelCall := context.WithTimeout(request, time.Hour)
defer cancelCall()
rd, _ := request.Deadline()
cd, _ := call.Deadline()
fmt.Println("the call keeps the request deadline:", cd.Equal(rd))
err := fetch(call)
fmt.Println("fetch:", err)
fmt.Println("deadline exceeded:", errors.Is(err, context.DeadlineExceeded))
}
the call keeps the request deadline: true
fetch: context deadline exceeded
deadline exceeded: true
- Verdict: stdlib. Go has no retry function in the standard library. The package
contextcarries deadlines and cancellation from a request to the calls that it makes. errors.Isseparates the error that is worth a retry from the one that is not.- A child context cannot extend the deadline of its parent. The call asks for an hour, but it keeps the 20 ms deadline of the request, so
fetchstops after 20 ms withcontext.DeadlineExceeded.
A retry repeats the request. When the server applied the first request and only the response was lost, the retry applies it a second time. The customer pays twice.
This code runs but gives a wrong answer on purpose.
package main
import (
"errors"
"fmt"
)
type bank struct {
balance int
calls int
}
func (b *bank) Charge(amount int) error {
b.calls++
b.balance -= amount
if b.calls == 1 {
return errors.New("timeout: no response")
}
return nil
}
func main() {
b := &bank{balance: 500}
for attempt := 1; attempt <= 3; attempt++ {
err := b.Charge(100)
if err == nil {
break
}
fmt.Println("attempt", attempt, "failed:", err)
}
fmt.Println("balance after one charge of 100:", b.balance)
}
attempt 1 failed: timeout: no response
balance after one charge of 100: 300
use std::fmt;
#[derive(Debug)]
enum CallError {
Unavailable,
BadRequest,
}
impl CallError {
fn is_transient(&self) -> bool {
matches!(self, CallError::Unavailable)
}
}
impl fmt::Display for CallError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
CallError::Unavailable => write!(f, "503 Service Unavailable"),
CallError::BadRequest => write!(f, "400 Bad Request"),
}
}
}
struct XorShift(u64);
impl XorShift {
fn below(&mut self, bound: u64) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0 % bound
}
}
fn retry<T>(
mut op: impl FnMut() -> Result<T, CallError>,
rng: &mut XorShift,
) -> Result<T, CallError> {
let (attempts, base, cap) = (5u32, 100u64, 1000u64);
let mut now = 0u64;
let mut attempt = 0;
loop {
match op() {
Ok(value) => return Ok(value),
Err(e) if !e.is_transient() || attempt + 1 == attempts => return Err(e),
Err(e) => {
let delay = rng.below(cap.min(base << attempt) + 1);
println!(" t={now:4} ms: attempt {} failed ({e}); wait {delay} ms", attempt + 1);
now += delay;
attempt += 1;
}
}
}
}
fn service(failures: u32, error: fn() -> CallError) -> impl FnMut() -> Result<String, CallError> {
let mut calls = 0;
move || {
calls += 1;
if calls <= failures {
Err(error())
} else {
Ok(format!("200 OK after {calls} calls"))
}
}
}
fn main() {
let mut rng = XorShift(0x2545_F491_4F6C_DD1D);
for (name, failures, error) in [
("flaky", 3, (|| CallError::Unavailable) as fn() -> CallError),
("bad request", 1, || CallError::BadRequest),
("down", 100, || CallError::Unavailable),
] {
println!("{name}");
match retry(service(failures, error), &mut rng) {
Ok(v) => println!(" result: {v}"),
Err(e) => println!(" gave up: {e}"),
}
}
}
flaky
t= 0 ms: attempt 1 failed (503 Service Unavailable); wait 54 ms
t= 54 ms: attempt 2 failed (503 Service Unavailable); wait 81 ms
t= 135 ms: attempt 3 failed (503 Service Unavailable); wait 211 ms
result: 200 OK after 4 calls
bad request
gave up: 400 Bad Request
down
t= 0 ms: attempt 1 failed (503 Service Unavailable); wait 75 ms
t= 75 ms: attempt 2 failed (503 Service Unavailable); wait 144 ms
t= 219 ms: attempt 3 failed (503 Service Unavailable); wait 103 ms
t= 322 ms: attempt 4 failed (503 Service Unavailable); wait 380 ms
gave up: 503 Service Unavailable
- Verdict: stdlib. Rust's standard library has no retry function and no random number generator. The example uses a xorshift generator of a few lines, with a fixed seed.
- The error type says which errors are transient. The match arm with a guard returns a permanent error at once, and it returns a transient one when the attempts run out.
- The closure that
servicereturns keeps its own count of calls, so each case starts from zero.
Exponential growth without a cap gives absurd delays after a few attempts. After 20 failed attempts, a base of 100 ms has grown to more than a day.
This code runs but gives a wrong answer on purpose.
fn main() {
let base: u64 = 100;
for attempt in [0u32, 5, 10, 15, 20] {
let delay = base * 2u64.pow(attempt);
let seconds = delay as f64 / 1000.0;
println!("attempt {attempt:2}: wait {seconds:>9.1} s = {:>4.1} hours", seconds / 3600.0);
}
}
attempt 0: wait 0.1 s = 0.0 hours
attempt 5: wait 3.2 s = 0.0 hours
attempt 10: wait 102.4 s = 0.0 hours
attempt 15: wait 3276.8 s = 0.9 hours
attempt 20: wait 104857.6 s = 29.1 hours
#!/usr/bin/env bash
# Retry a command with capped exponential backoff and full jitter.
# The script keeps time in a counter and does not sleep, so it runs at once.
seed=12345
next_random() {
# A linear congruential generator with a fixed seed, so each run gives the same delays.
seed=$(( (seed * 1103515245 + 12345) % 2147483648 ))
rnd=$(( seed / 65536 ))
}
calls=0
flaky() {
# Exit code 75 is EX_TEMPFAIL: a temporary failure that is worth a retry.
calls=$(( calls + 1 ))
if (( calls <= $1 )); then return 75; fi
echo " ok after $calls calls"
}
usage_error() {
# Exit code 64 is EX_USAGE: the command was called wrongly, and a retry cannot help.
calls=$(( calls + 1 ))
return 64
}
retry() {
local attempts=5 base=100 cap=1000 now=0 attempt status limit delay
for (( attempt = 0; attempt < attempts; attempt++ )); do
"$@" && return 0
status=$?
if (( status != 75 )); then
echo " exit $status: not a temporary failure, stop"
return "$status"
fi
if (( attempt == attempts - 1 )); then break; fi
limit=$(( base << attempt ))
(( limit > cap )) && limit=$cap
next_random
delay=$(( rnd % (limit + 1) ))
printf ' t=%4d ms: attempt %d failed (exit %d); wait %d ms\n' "$now" $(( attempt + 1 )) "$status" "$delay"
now=$(( now + delay ))
done
echo " gave up after $attempts attempts"
return "$status"
}
echo "flaky"; calls=0; retry flaky 2
echo "usage error"; calls=0; retry usage_error
echo "down"; calls=0; retry flaky 100
echo "exit status of the last retry: $?"
flaky
t= 0 ms: attempt 1 failed (exit 75); wait 56 ms
t= 56 ms: attempt 2 failed (exit 75); wait 139 ms
ok after 3 calls
usage error
exit 64: not a temporary failure, stop
down
t= 0 ms: attempt 1 failed (exit 75); wait 99 ms
t= 99 ms: attempt 2 failed (exit 75); wait 81 ms
t= 180 ms: attempt 3 failed (exit 75); wait 85 ms
t= 265 ms: attempt 4 failed (exit 75); wait 25 ms
gave up after 5 attempts
exit status of the last retry: 75
- Verdict: idiom. Bash has no retry builtin. A loop around the command, with
$?for the exit status, is the usual form. - The exit status says whether a retry can help. The codes 64 and 75 come from
sysexits.h:EX_USAGEis a wrong call, andEX_TEMPFAILis a temporary failure where the user is invited to retry. - A real script calls
sleepwith the delay. The loop here adds the delay to a counter, so the output does not depend on the clock. - The script uses its own generator and not
$RANDOM, because the sequence of$RANDOMfor a given seed is not part of any standard.
Variations and related ideas
- Retry budgets. A budget limits the retries of a whole process, not of one request. The SRE book suggests a server-wide budget, "for example, only allow 60 retries per minute in a process".4 Brooker describes "limiting retries locally using a token bucket", which AWS added to the AWS SDK in 2016.3 gRPC throttles retries per server with a token count that starts at
maxTokens. Each failure takes away 1, each success addstokenRatio, and retries stop while the count is below half ofmaxTokens.9 The C# example shows a budget that cuts the calls to a failing dependency from 40 to 18. - Circuit breakers. A circuit breaker stops the calls for a while after many failures. Martin Fowler credits Michael Nygard's book Release It! with making the pattern popular. When the breaker trips, "all further calls to the circuit breaker return with an error, without the protected call being made at all".10 A retry policy reacts to one failure, and a circuit breaker reacts to a pattern of failures.
- Hedged requests. A client sends a second copy of a slow request before the first one fails, and uses the first response that arrives. This trades extra load for lower tail latency, and it needs an idempotent operation as a retry does.
- TCP retransmission. TCP backs off its retransmission timer. When the timer expires, "The host MUST set RTO <- RTO * 2". A maximum may be placed on the timer "provided it is at least 60 seconds".6
- Jitter for timers. Brooker suggests adding jitter to "all timers, periodic jobs, and other delayed work", for example a job that many servers run from cron at the same minute.3
- Polling. A loop that polls for a result, such as the status of a job, uses the same schedule: start often and slow down while nothing changes.
- Retries in tests. A test that retries until it passes hides a flaky test. A Test double that fails a set number of times, such as the
servicefunction of the Go and Python examples, tests the retry loop without a network.
Pitfalls
No jitter
Clients that fail together retry together. The Python example no-jitter shows 100 clients with a plain exponential backoff. Every retry round arrives as one burst of 100 calls, at 0, 100, 300 and 700 ms. Full jitter spreads each round over the whole interval.
No cap
The waits double without limit. The Rust example no-cap gives a wait of 29.1 hours after 20 attempts. A cap, and a total deadline, keep the loop in the range that a user waits for.
Retries at every layer
When each layer of a system retries, the retries multiply. The SRE book gives an example where three layers each make four attempts, so "a single user action may create 64 attempts (4^3) on the database".4 Brooker gives a stack five layers deep and says that "the load on the database will increase 243x".3 The C example layers counts the 64 calls. Retry at one layer, usually the one nearest to the user, and let the other layers fail fast.
Retrying an operation that is not idempotent
A timeout does not say whether the server did the work. A retry of a payment, an email or an insert can do it twice. Use an idempotency key, or make the operation idempotent, before it gets a retry policy.
Retrying errors that cannot succeed
A 400 Bad Request fails the same way on every attempt. Each retry adds load and delay and gives the same answer. The examples stop at once on a permanent error and return it to the caller.
Retrying without a deadline
Each attempt can wait for its full timeout. Five attempts with a 10 second timeout and the waits between them take more than 50 seconds, long after the user has gone. Pass the deadline of the request down to the retry loop.
Hiding the failure
A retry that succeeds hides the failure that came before it. Record each failed attempt, for example with Structured logging, and count the retries. A rise in the retry rate is often the first sign that a dependency is in trouble.
Retrying in a hot loop
A loop that retries at once, with no wait, sends calls as fast as the CPU allows. When the dependency is down, the loop uses a whole core and floods the dependency (Uncontrolled resource consumption).
Cost
- Latency. Each retry adds its wait and the time of the next attempt. With full jitter, the mean wait before retry n+1 is half of
min(cap, base * 2**n). - Load. In the worst case, every request makes the maximum number of attempts. A retry policy with four attempts can multiply the load on a failing dependency by four, and nested retries multiply further. Budgets and circuit breakers put a limit on this.
- State. An idempotency key needs storage on the server for as long as a retry can arrive. Stripe allows keys to be removed after 24 hours.7
- Testing. The retry loop is code that runs only on failure. The examples inject the clock and the random generator, so a test can check the waits without sleeping.
History
- 1976. Robert Metcalfe and David Boggs described Ethernet. After each collision, a controller "delays for an interval of random length with a mean twice that of the previous interval". The authors called this Binary Exponential Backoff.1
- 2011. RFC 6298 specified the TCP retransmission timer, with the timer doubled after each timeout.6
- 2014. Martin Fowler described the circuit breaker, after Michael Nygard's Release It!.10
- 2015. Marc Brooker's article "Exponential Backoff And Jitter" compared full, equal and decorrelated jitter in a simulation.2
- 2016. The Google SRE book described retry budgets and deadline propagation.4 AWS added a token bucket for retries to the AWS SDK.3
- 2019. The Amazon Builders' Library article "Timeouts, retries, and backoff with jitter" described the multiplication of retries across layers, and idempotency as the condition for a safe retry.3
References
- Robert M. Metcalfe and David R. Boggs, Ethernet, Distributed Packet Switching for Local Computer Networks, Communications of the ACM 19(7), July 1976, pages 395 to 404, page 400, the section on the controller (Binary Exponential Backoff)
- Marc Brooker, Exponential Backoff And Jitter, AWS Architecture Blog, 4 March 2015, the sections on Full Jitter, Equal Jitter and Decorrelated Jitter, and the closing paragraphs
- Marc Brooker, Timeouts, retries, and backoff with jitter, Amazon Builders' Library, 2019, the sections Timeouts, Retries and backoff, and Jitter
- Mike Ulrich, Addressing Cascading Failures, chapter 22 of Site Reliability Engineering, O'Reilly, 2016, the sections Retries, and Latency and Deadlines (Picking a deadline, Deadline propagation)
- RFC 9110, HTTP Semantics, June 2022, section 9.2.2 Idempotent Methods; section 10.2.3 Retry-After
- RFC 6298, Computing TCP's Retransmission Timer, June 2011, section 2.5 (the maximum value of RTO); section 5, step 5.5 (back off the timer)
- Stripe API Reference, Idempotent requests, the whole page
- Go standard library, package context, func WithDeadline
- gRPC documentation, Retry, the sections on the retry policy and on throttling
- Martin Fowler, CircuitBreaker, 6 March 2014, the first paragraphs
- FreeBSD Library Functions Manual, sysexits(3), EX_USAGE and EX_TEMPFAIL
- The Open Group Base Specifications Issue 8, errno.h, the list of symbolic names (EAGAIN, EINTR, EINVAL)
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [rand.dist.general], paragraph 3
- RFC 6585, Additional HTTP Status Codes, April 2012, section 4, 429 Too Many Requests
- PowerShell documentation, Invoke-RestMethod, the parameters MaximumRetryCount and RetryIntervalSec
- PostgreSQL documentation, Transaction Isolation, 13.2.2 Repeatable Read Isolation Level; 13.2.3 Serializable Isolation Level
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag Z242S4 Edit this page History Report an error Markdown