Retry Pattern
Retrying transient failures safely: exponential backoff, jitter, idempotency, and knowing when to stop.
Networks drop packets, pods restart and databases fail over. Many failures are transient — the same request would succeed a moment later. The retry pattern re-sends those requests automatically, but done carelessly it turns a small blip into a self-inflicted outage.
Only retry what is retryable
Retry: timeouts, connection resets, HTTP 502/503/504, 429 (after
Retry-After).Don’t retry: 400 Bad Request, 401/403, 404, validation errors — they will fail again.
Exponential backoff with jitter
Wait longer after each attempt — 100 ms, 200 ms, 400 ms, 800 ms — so a struggling dependency gets room to recover. Then add jitter (randomness) so thousands of clients that failed together don’t all retry at the same instant.
async function withRetry(fn, { attempts = 4, baseMs = 100, maxMs = 2000 } = {}) {
for (let attempt = 1; ; attempt += 1) {
try {
return await fn();
} catch (error) {
if (attempt >= attempts || !isTransient(error)) throw error;
// "Full jitter": sleep a random time up to the exponential cap.
const cap = Math.min(maxMs, baseMs * 2 ** (attempt - 1));
await sleep(Math.random() * cap);
}
}
}Idempotency makes retries safe
If a payment request times out, did the charge happen? A retry might charge twice. Send an idempotency key with the request; the server stores the result for that key and returns it again instead of repeating the side effect.
Know when to stop
Cap the number of attempts and the total time budget (respect the caller’s deadline).
Retry at one layer only — retries at every layer multiply: 3 × 3 × 3 = 27 calls.
Pair retries with a circuit breaker so a dependency that is truly down stops receiving traffic.
Use a retry budget (e.g. retries ≤ 10% of requests) to avoid retry storms.
Rule of thumb: retries handle blips, circuit breakers handle outages, and idempotency keeps both safe.