Retries, backoff & circuit breakers
Retry only transient errors, with exponential backoff plus jitter, within a deadline and a retry budget; when a dependency is clearly down, a circuit breaker fails fast or falls back instead of piling on.
Analogy: Calling a busy restaurant: you don't redial every second (backoff), you don't all call at 7:00 sharp (jitter), and after five busy signals you eat somewhere else tonight (circuit breaker).
How it works
- Retry transient errors like timeouts, 429 and 503; permanent ones (400, 401, 403) fail the same every time.
- Full jitter waits a random time from 0 to
base × 2^attempt, so failed clients don't retry in waves. - Retry at one layer only: 3 layers × 4 attempts put 64 calls on the bottom service.
- For streaming LLM calls, time out on the first token and idle gaps, not total duration.
- A circuit breaker opens after N failures, fails fast or falls back, then half-opens to probe recovery.
Check yourself
Answer to mark it learned; your answers aren't scored.
Logs show an LLM call failing with 400 because the prompt exceeds the context window. Your client retries it 3 times with exponential backoff, adding seconds before the user sees an error. Best change?
Go deeper
Full explanation
A retry turns a transient failure into a success; a bad retry policy turns a small outage into a big one.
Classify first. Retry transient errors: timeouts, connection resets, 429, 500/502/503/504 and the LLM-specific 529 overloaded. Never retry permanent ones (400, 401, 403, context too long): they fail the same way every time. Retry writes only if they are idempotent (Idempotency).
Back off with jitter. Wait base × 2^attempt, capped, and randomize it (full jitter: a uniform draw between 0 and that value). Without jitter, clients that failed together retry together, in waves. If the server sends Retry-After, obey it.
Bound everything.
- A timeout on every network call and a total deadline per request. For streaming LLM calls, time out on the first token and on idle gaps, not on total duration.
- A retry budget: ~3 attempts per request, retries ≤ 10% of traffic. Retry at one layer: 3 layers × 4 attempts = 64 calls on the bottom service.
Stop calling a dead dependency. A circuit breaker is closed (normal), trips open after N failures (fail fast, or Model routing & cascades to a fallback model, for e.g. 30 s), then goes half-open and lets a few probes test recovery. Bulkheads give each dependency its own concurrency pool, so one slow LLM provider cannot exhaust every worker.
Code Full-jitter retries, Retry-After and a fallback model
import random, time
import anthropic
client = anthropic.Anthropic(max_retries=0) # exactly one layer owns retries: this one
PRIMARY = "claude-sonnet-4-5" # example ids: any two models
FALLBACK = "claude-haiku-4-5"
TRANSIENT = {408, 429, 500, 502, 503, 504, 529}
def full_jitter(attempt: int, base: float = 0.5, cap: float = 20.0) -> float:
# Uniform in [0, base*2^n]: de-synchronizes clients that failed together
return random.uniform(0, min(cap, base * 2 ** attempt))
def ask(messages, model=PRIMARY, attempts=3, deadline_s=45.0):
start = time.monotonic()
for n in range(attempts):
try:
return client.messages.create(model=model, max_tokens=1024,
messages=messages, timeout=30.0)
except anthropic.APIStatusError as e:
if e.status_code not in TRANSIENT:
raise # 400/401/403: permanent
hint = e.response.headers.get("retry-after")
wait = float(hint) if hint else full_jitter(n) # server knows best
except anthropic.APIConnectionError: # also covers timeouts
wait = full_jitter(n)
if n + 1 == attempts or time.monotonic() - start + wait > deadline_s:
break # out of attempts or time
time.sleep(wait)
if model != FALLBACK: # degrade instead of failing
return ask(messages, FALLBACK, attempts=2, deadline_s=15.0)
raise RuntimeError("primary and fallback both unavailable")Real example
Monday 9:00: your LLM provider returns 529 overloaded on ~30% of calls. With no policy, each of 3 layers retries 3 times immediately: one failed call becomes up to 64 calls and the overload deepens. With a policy, only the gateway retries, at most twice, with full jitter and Retry-After; after 20 failures in 10 s the breaker opens and sends traffic to a fallback model for 30 s. Users see ~1.5 s extra latency on some answers, slightly lower quality on others, and almost no errors.
Trade-offs +3 · −4
+ You gain
- Absorbs the transient failures that are normal at scale: network blips, deploys, brief throttling.
- Circuit breakers turn slow timeouts into instant failures or fallbacks, freeing workers and giving the dependency room to recover.
- Fallback models keep the product up when one provider is degraded.
− You pay
- Every retry adds latency; without a deadline, tail latency is unbounded.
- Misconfigured, retries amplify load exactly when the dependency is weakest.
- Breakers need tuning: too sensitive and they flap on noise, too lax and they never trip.
- A fallback model changes quality and cost; it needs its own evals.
Use it when
Every call that crosses a network: LLM APIs, vector databases, internal services. Add breakers and bulkheads wherever one slow dependency could stall many callers.
Avoid it when
Permanent errors, non-idempotent writes without an idempotency key, or a layer whose callee already retries. Don't retry when the user's deadline has no room left.
Numbers to know 5
- Full jitter: sleep = random(0, min(cap, base × 2^attempt)) — AWS Architecture Blog.
- Google SRE: at most 3 attempts per request, and a per-client budget keeping retries under 10% of requests.
- Retries multiply across layers: 3 layers × 4 attempts each = 4³ = 64 calls on the bottom service.
- OpenAI and Anthropic Python SDKs retry 2 times by default with exponential backoff (429, 5xx, connection errors).
- Anthropic returns 429 for rate limits (with a retry-after header) and 529 when the API is overloaded.
Common pitfalls 4
- Retrying at every layer (SDK, gateway, service): attempts multiply and the storm lands on the weakest service.
- No jitter: thousands of clients retry in synchronized waves that look like a DDoS.
- Retrying an agent's tool call or a payment without an idempotency key: double charges, duplicate emails.
- One total timeout on a streaming LLM call: it either kills long valid answers or waits minutes on a hung one.
Interview questions 3
Answer out loud first, then reveal.
Your LLM provider starts returning 529 overloaded at peak. What does your system do?Show answer
I treat 429 and 529 as transient, but as a signal to back off, not push harder. The gateway, and only the gateway, retries up to twice with full jitter, honoring Retry-After. If failures cross a threshold, a circuit breaker opens and routes to a fallback: a second provider or a smaller model whose quality we've already evaluated. Meanwhile I shed or queue low-priority work like batch jobs so interactive users keep the capacity. The trade-off is lower quality or higher cost on the fallback path versus an outright error.
How can retries make an outage worse, and how do you prevent it?Show answer
Retries add load exactly when the dependency is saturated. If three layers each make four attempts, one user action becomes 64 calls at the bottom, and clients that failed together retry together. I prevent it with four rules: retry at one layer only, exponential backoff with jitter, a retry budget such as retries under 10% of traffic, and circuit breakers that fail fast once the error rate is clearly high. I also make deadlines shrink down the stack, so nobody keeps working on a request the caller already abandoned.
Retries and circuit breakers seem contradictory. Why use both?Show answer
They cover different time scales. Retries handle short, independent blips: one call failed, the next will likely succeed. A breaker handles sustained failure: if half of the last 100 calls failed, the next one probably will too, so retrying only adds latency and load. The breaker opens, callers get an instant error or fallback, and after a cooldown it half-opens to probe. I put the retry loop inside the breaker, so a tripped breaker stops the retries too.