---
title: "LLM API Retry with Exponential Backoff and Jitter: What Not to Retry"
description: "How to retry LLM API calls: full jitter backoff, total time caps, retry budgets and SDK double-retry amplification, with Python and TypeScript code."
url: https://cdnping.org/en/blog/llm-api-retry-exponential-backoff-jitter
language: en
published: 2026-10-27
category: "Developer tools"
tags: ["retry strategy","exponential backoff","LLM API","error handling","Python","TypeScript"]
source: cdnping.org
license: Free to quote and summarize with a link to the url above.
---
# LLM API Retry with Exponential Backoff and Jitter: What Not to Retry

The right way to retry an LLM API call: retry only on 408, 409, 429, 5xx and connection errors. Wait a random time between `0` and `min(cap, base × 2^n)` before each retry (full jitter). Set a total time limit and a global retry budget. Turn off either the SDK's built-in retry or your application-level retry, so only one layer is active. Errors like 400, 401, 403 and exhausted quota will not succeed no matter how many times you retry. You only waste time and money.

Most general backoff guides use object storage or database requests as examples: tens of milliseconds per call, almost free. LLM requests are different. One call can run for tens of seconds, it is billed by token, and after a timeout the server may already have finished the computation and charged you. Below we rework retry for the LLM case and finish with two implementations you can use directly.

## Why does retry for LLM APIs need separate treatment?

Three things differ from an ordinary HTTP API:

- Each call is expensive. A long-context request can carry a lot of input tokens, and every retry pays for that input again. Be especially careful with timeouts: the client giving up does not mean the server stopped. For billing details, see [How token billing works: an itemized breakdown of one API call](/en/blog/llm-token-billing-explained).
- Each call is slow. Three retries on a normal API cost an extra second or two. If an LLM call has a 60-second timeout and the first attempt plus three retries all time out, the user waits more than 4 minutes. You need a total time limit, not just an attempt limit.
- Failures come in clusters. When an upstream is overloaded, failures are not evenly distributed random events. They concentrate in a window. If every client retries on the same schedule, they all hit the upstream at the moment it recovers.

## Do failures really cluster? A look at public data

AGI Plan publishes real hourly request success and failure counts at `https://agiplan.dev/api/status/requests?month=YYYY-MM` (no login required). AGI Plan is a commercial partner of cdnping, and cdnping's [/en/status/agiplan](/en/status/agiplan) page mirrors this data. By the API's definition, only 5xx responses count as platform failures.

Take the 48 hourly buckets from 2026-10-15 19:00 to 2026-10-17 19:00 (Beijing time, UTC+8), summed across all capability groups:

| Metric | Value |
|---|---|
| Total successful requests | 13,963 |
| Total failed requests | 2,177 |
| Hour of Oct 16, 14:00 | 664 successes, 722 failures |
| Hour of Oct 16, 15:00 | 455 successes, 877 failures |
| Share of all 48-hour failures in these two hours | about 73% |

Of the 48 hourly buckets, 20 had zero failures, while more than 70% of failures were packed into two hours, with failure rates of about 52% and 66% in those hours. The window is only two days, so treat this as an example. What it shows is the situation a retry policy actually has to handle: a large share of upstream requests failing for a stretch of time. In that situation, the more aggressively you retry, the more load you put on the upstream and the longer your own users wait.

To check this against your own data, count failures per hour using the method in [Measuring AI API uptime yourself: metrics, scripts and definitions](/en/blog/measure-ai-api-uptime-yourself) and see whether they cluster.

## Which errors should you retry, and which must you never retry?

Set the rules first, then write the code. The table below can be used as a configuration. The intervals and caps are suggested starting points, so adjust them for your workload. For what each status code means, see [LLM API error code cheatsheet](/en/blog/ai-api-error-codes-400-to-529-cheatsheet).

| Error type | Retry? | Initial interval (base) | Per-wait cap | Notes |
|---|---|---|---|---|
| Connection failure, DNS failure, TLS handshake failure | Retry | 0.5 s | 10 s | The request never went out, so retrying is safe |
| Read timeout / 408 | Conditional | 1 s | 30 s | The server may have finished and billed you; limit attempts on long non-streaming requests |
| 409 | Retry | 1 s | 10 s | Usually a server-side lock conflict; retry a few times |
| 429 rate limit (RPM/TPM) | Retry | Prefer Retry-After; otherwise 2 s | 60 s | Wait the larger of Retry-After and the backoff value |
| 429 quota exhausted (e.g. `insufficient_quota`) | Do not retry | — | — | Will not recover until you top up or switch keys |
| 500, 502, 503, 504 | Retry | 1 s | 30 s | Upstream or gateway failure, the type most likely to cluster |
| 529 / overloaded | Retry | 2 s | 60 s | Overload; wait longer and keep the budget tighter |
| 400 bad parameters, context too long | Do not retry | — | — | Change the request, not the timing |
| 401, 403 | Do not retry | — | — | Authentication or permission problem; a 403 can also be a region restriction, which you should handle according to the provider's terms of service |
| 404 model not found | Do not retry | — | — | Check the model name and endpoint URL |
| 422, content moderation rejection | Do not retry | — | — | The same input gives the same result |
| Stream drops midway | Depends | 1 s | 30 s | If content was already output, do not silently restart; see below |

Always separate the two kinds of 429. A rate limit means "wait a bit and it clears." Exhausted quota means "no amount of waiting helps." Retry code that looks only at the status code will make every request wait out its full backoff before failing once the quota runs out. For more on 429, see [What to do when the API returns 429 Too Many Requests](/en/blog/llm-api-429-too-many-requests-fix).

## Which backoff formula: why full jitter?

Three common approaches:

- Fixed interval: wait 2 seconds every time. All clients stay in sync and surge in together when the service recovers.
- Plain exponential backoff: wait `base × 2^n`. The intervals grow, but all clients still retry at the same moments.
- Exponential backoff with full jitter: wait `random(0, min(cap, base × 2^n))`. Each client's retry time is scattered.

The expected wait under full jitter is half that of plain exponential backoff for the same round, but retries are spread more evenly over time, which is gentler on the upstream. In the formula, `cap` keeps the wait from growing without bound, and `n` starts at 0.

For a 429 whose response carries a `Retry-After` header, wait `max(backoff, Retry-After)`. The server has told you when to come back, which is more accurate than guessing. If Retry-After is longer than your total time limit, fail immediately and let the caller degrade gracefully.

## The SDK already retries, so why is there still a problem?

The official OpenAI Python and TypeScript SDKs both have automatic retry built in, controlled by `max_retries` and `maxRetries` respectively. Check each one's official docs for defaults and retry conditions. The problem is that many projects wrap another layer of tenacity or hand-written retry around the SDK, and there may be a retrying gateway in between.

Retry counts multiply. Suppose each layer makes "at most 3 attempts":

| Layer | Max attempts per layer | Cumulative max requests |
|---|---|---|
| SDK | 3 | 3 |
| SDK + application layer | 3 × 3 | 9 |
| SDK + application layer + gateway | 3 × 3 × 3 | 27 |

During an upstream outage, a single user request can turn into 27 upstream requests, and the backoff schedules of the layers stack on each other, making total latency hard to predict.

The fix is to keep exactly one layer of retry, in the layer that knows the most about your business logic. If you want to control backoff, budget and fallback yourself, turn off the SDK's retry (`max_retries=0` / `maxRetries: 0`). If you only want the SDK's default behavior, do not wrap another layer around it. If you use a gateway, first check whether the gateway itself retries.

## What is a retry budget, and do you need one?

The attempt limit and total time limit are per-request constraints. A retry budget is a per-process constraint: the number of retry requests cannot exceed a certain fraction of normal requests, for example 10%.

It addresses clustered failures. When the upstream fails broadly, every request wants to retry 3 times, the budget runs out quickly, and later requests fail immediately and go to fallback logic instead of adding load to the upstream. When the upstream is healthy, occasional failures are retried as usual and are not affected.

A token bucket is enough to implement it: each original request adds 0.1 token to the bucket, each retry consumes 1 token, and the bucket has a maximum. Both code samples below include this structure.

## Python implementation (tenacity + OpenAI SDK)

Turn off the SDK's retry, use tenacity for backoff, attempt count and total time, and use a token bucket for the budget. The model name is read from an environment variable.

```python
import os
import random
import threading

import openai
from openai import OpenAI
from tenacity import (
    RetryCallState,
    retry,
    stop_after_attempt,
    stop_after_delay,
)

client = OpenAI(max_retries=0, timeout=60)  # keep only one layer of retry
MODEL = os.environ["LLM_MODEL"]

RETRYABLE_STATUS = {408, 409, 429, 500, 502, 503, 504, 529}
MAX_ATTEMPTS = 4
BASE, CAP = 1.0, 30.0          # seconds
MAX_RETRY_AFTER = 60.0          # do not wait if Retry-After exceeds this


class RetryBudget:
    """Process-level retry budget: retries are about ratio times the original requests."""

    def __init__(self, ratio: float = 0.1, cap: float = 20.0):
        self.ratio, self.cap, self.tokens = ratio, cap, cap
        self._lock = threading.Lock()

    def on_request(self) -> None:
        with self._lock:
            self.tokens = min(self.cap, self.tokens + self.ratio)

    def try_spend(self) -> bool:
        with self._lock:
            if self.tokens >= 1:
                self.tokens -= 1
                return True
            return False


budget = RetryBudget()


def _retry_after(exc: BaseException) -> float | None:
    resp = getattr(exc, "response", None)
    if resp is None:
        return None
    value = resp.headers.get("retry-after")
    try:
        return float(value) if value is not None else None
    except ValueError:  # HTTP-date format; for simplicity, leave it to backoff
        return None


def _is_retryable(exc: BaseException) -> bool:
    if isinstance(exc, openai.APIConnectionError):  # includes timeouts
        return True
    if isinstance(exc, openai.APIStatusError):
        if exc.status_code == 429 and getattr(exc, "code", None) == "insufficient_quota":
            return False
        ra = _retry_after(exc)
        if ra is not None and ra > MAX_RETRY_AFTER:
            return False
        return exc.status_code in RETRYABLE_STATUS
    return False


def should_retry(state: RetryCallState) -> bool:
    exc = state.outcome.exception()
    if exc is None or state.attempt_number >= MAX_ATTEMPTS:
        return False  # the last failure does not consume budget
    return _is_retryable(exc) and budget.try_spend()


def full_jitter_wait(state: RetryCallState) -> float:
    n = state.attempt_number - 1
    backoff = random.uniform(0, min(CAP, BASE * 2 ** n))
    ra = _retry_after(state.outcome.exception())
    return max(backoff, ra) if ra is not None else backoff


@retry(
    retry=should_retry,
    wait=full_jitter_wait,
    stop=stop_after_attempt(MAX_ATTEMPTS) | stop_after_delay(120),
    reraise=True,
)
def _chat_once(messages):
    return client.chat.completions.create(model=MODEL, messages=messages)


def chat(messages):
    budget.on_request()  # count each original request only once
    return _chat_once(messages)
```

Two notes. `stop_after_delay` is checked between attempts and does not interrupt a single request's own 60-second timeout, so the actual worst-case duration is roughly "total time limit + one request timeout." tenacity's built-in `wait_random_exponential` also follows the full jitter idea, but it does not read Retry-After, which is why the wait function is written by hand here.

## TypeScript implementation (openai Node SDK)

```ts
import OpenAI from "openai";

const client = new OpenAI({ maxRetries: 0, timeout: 60_000 });
const RETRYABLE = new Set([408, 409, 429, 500, 502, 503, 504, 529]);

class RetryBudget {
  private tokens: number;
  constructor(private ratio = 0.1, private cap = 20) {
    this.tokens = cap;
  }
  onRequest() {
    this.tokens = Math.min(this.cap, this.tokens + this.ratio);
  }
  trySpend() {
    if (this.tokens >= 1) {
      this.tokens -= 1;
      return true;
    }
    return false;
  }
}
const budget = new RetryBudget();

function retryAfterMs(err: unknown): number | undefined {
  if (!(err instanceof OpenAI.APIError) || !err.headers) return;
  const h: any = err.headers; // depending on SDK version this may be Headers or a plain object
  const v = typeof h.get === "function" ? h.get("retry-after") : h["retry-after"];
  const s = Number(v);
  return Number.isFinite(s) && v != null ? s * 1000 : undefined;
}

function isRetryable(err: unknown): boolean {
  if (err instanceof OpenAI.APIConnectionError) return true; // includes timeouts
  if (err instanceof OpenAI.APIError) {
    if (err.status === 429 && err.code === "insufficient_quota") return false;
    return err.status !== undefined && RETRYABLE.has(err.status);
  }
  return false;
}

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

export async function withRetry<T>(
  fn: () => Promise<T>,
  { maxAttempts = 4, baseMs = 1_000, capMs = 30_000, deadlineMs = 120_000 } = {},
): Promise<T> {
  const start = Date.now();
  budget.onRequest();
  for (let attempt = 1; ; attempt++) {
    try {
      return await fn();
    } catch (err) {
      if (attempt >= maxAttempts || !isRetryable(err)) throw err;
      const backoff = Math.random() * Math.min(capMs, baseMs * 2 ** (attempt - 1));
      const wait = Math.max(backoff, retryAfterMs(err) ?? 0);
      if (Date.now() - start + wait > deadlineMs) throw err; // total time limit exceeded
      if (!budget.trySpend()) throw err;                      // budget exhausted
      await sleep(wait);
    }
  }
}

// Usage
const res = await withRetry(() =>
  client.chat.completions.create({
    model: process.env.LLM_MODEL!,
    messages: [{ role: "user", content: "ping" }],
  }),
);
```

If you use the Anthropic SDK or another compatible API, the structure stays the same. Only the error-type checks need to change.

## What if a stream breaks halfway?

Retrying a streaming request splits into two cases:

1. It fails before any content arrives (connection failure, timeout before the first chunk, an immediate 5xx): retry with the same rules as non-streaming.
2. It disconnects after some output: do not silently re-send the request in the background and start output over. The user has already seen the first part, the new response may differ, and you pay for it again. A safer approach is to mark the received content as incomplete and let the user decide whether to regenerate. In an agent setting, you can feed the existing output back as context and have the model continue.

It is best to set the time-to-first-token timeout separately from the overall timeout, and the former can be shorter. For how latency breaks down by stage, see [AI API latency breakdown: connection setup, gateway round trip and time to first token](/en/blog/api-latency-connect-rtt-ttft). If you hit a stream interruption error in a tool like Codex, check your network first; see [Codex: "stream disconnected before completion"](/en/blog/codex-stream-disconnected-before-completion).

## Pre-launch checklist

- [ ] Only one layer of retry: enable it in just one of the SDK, application layer or gateway, and set the others to 0.
- [ ] The retry condition is an allowlist (408, 409, 429, 5xx, connection errors), not "retry everything except 400."
- [ ] 429 separates rate limiting from exhausted quota, and exhausted quota fails immediately.
- [ ] Waits use full jitter with a per-wait `cap`.
- [ ] Retry-After is read, and an overly long value fails immediately.
- [ ] Both attempt count and total time are limited, with the total time set by "how long can the user wait."
- [ ] There is a process-level retry budget, and when it runs out you degrade (switch to a backup endpoint, queue, or ask the user to try later).
- [ ] Streaming requests that have already output content are not silently retried.
- [ ] Every retry is logged: status code, attempt number, wait time, and whether it gave up because of the budget. Without these logs you cannot tell afterward whether retries helped or made things worse.

## Before retrying, check whether the upstream is down

Retry is only suited to brief, scattered failures. If failures last several minutes, the upstream is more likely having an outage, and the right move is to degrade rather than keep retrying. First look at cdnping's [API status](/en/status), which probes each vendor's official API endpoint from the Cloudflare edge every 5 minutes and also syncs some official status pages. You can also check [Is it down](/en/down) to see whether other users are reporting the same problem. If the slowness is on your side of the network, use the [homepage speed test](/en) to measure first-connection and round-trip time to each API, then decide how long your timeouts should be. For how probing is defined, see [Methodology](/en/methodology).
