Models → Pricing → Docs → Blog → Changelog → Contact → Status →
Get started freeLog in

Retries and Backoff for LLM APIs: What to Retry

Which LLM API errors to retry and which to stop on: 429 and 503 yes, 402, 403 and 404 no. Backoff with jitter and Retry-After in Python and Node.

Every LLM API fails now and then. A per-minute limit fills up, a model is briefly unavailable, a network hop drops a connection. Retrying is the right answer to some of these and the wrong answer to others.

The common mistake is a retry loop that treats every error the same. It hammers the API when the account is out of tokens, or it gives up on a rate limit that would have cleared in two seconds. This post sorts the errors into two groups, explains why, and gives you a retry helper for Python and Node that you can drop into a project.

The short answer

These are the status codes FreeModel returns and what a client should do with each one.

StatusExample codeRetry?Why
429rate_limit_exceeded, account_rate_limit_exceededYes, after Retry-AfterThe per-minute window resets
503model temporarily unavailableYes, with backoffTemporary; often clears in seconds
502, timeouts, dropped connections—Yes, a few timesTransient network or upstream failure
402tokens_exhaustedNoNothing changes until you renew, upgrade or wait for the daily reset
403upgrade_required, insufficient_scopeNoA permission problem, not a timing problem
404model_not_foundNoThe model id is wrong
401invalid_api_keyNoThe key is missing, revoked or expired
400, 413, 422validation_error, context_length_exceededNoThe request itself must change

The rule behind the table: retry when time alone can fix the problem; stop when a person or a code change has to fix it.

Why 429 and 503 are worth retrying

A 429 means you sent more requests per minute than your plan allows. On FreeModel the plan limit applies to the whole account, across all its keys; Starter allows 120 requests per minute and Ultra 1,500. The response carries a Retry-After header with the seconds until the window has room again. Wait that long and the same request goes through.

A 503 means the model could not take the request right now. These are usually short. Some 503 responses also carry Retry-After; a few, such as planned maintenance, carry a long one measured in minutes. Respect it, and if it is longer than your users can wait, show a message instead of sleeping.

A request that fails is not charged, so retrying a 429 or 503 costs you time, not tokens.

Why 402, 403 and 404 are not

402 means the tokens are used up: the plan allowance (tokens_exhausted), a single prompt larger than what is left (prompt_exceeds_quota), or a spend or token limit you set on the key. We answer with 402 rather than 429 on purpose: a 429 tells clients to try again, and a coding agent that retries "tokens used up" every few seconds will do so for ever. A 402 tells the client to stop and show the message.

403 is about permission. upgrade_required means a free account asked for a paid model such as Claude Sonnet (Claude Haiku 5.5 is free); the free tokens work only on the free models. insufficient_scope means the key lacks a scope. Neither changes with time.

404 model_not_found means the id is not one we serve. We do not map unknown names like gpt-4o to some other model, so the same id will fail every time. Fix it from GET /v1/models or the models page.

Backoff with jitter

When there is no Retry-After, wait longer after each failure and add randomness so that many clients do not retry in lockstep. "Full jitter" is simple and works well:

delay = random(0, min(cap, base * 2 ** (attempt - 1)))

With base = 1 second and cap = 30 seconds, attempt 1 waits up to 1 s, attempt 2 up to 2 s, attempt 3 up to 4 s, and so on. Stop after a fixed number of attempts — five is plenty for interactive use.

Python retry helper

This uses the official openai package pointed at FreeModel. Built-in retries are turned off so the policy lives in one place.

import os
import random
import time

import openai
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["FREEMODEL_API_KEY"],
    base_url="https://freemodel.in/v1",
    max_retries=0,   # our loop below decides
    timeout=120,
)

RETRY_STATUS = {429, 502, 503, 504}
MAX_ATTEMPTS = 5
BASE, CAP = 1.0, 30.0


def backoff(attempt):
    return random.uniform(0, min(CAP, BASE * 2 ** (attempt - 1)))


def retry_after(err):
    value = err.response.headers.get("retry-after")
    return int(value) if value and value.isdigit() else None


def chat_with_retries(**kwargs):
    for attempt in range(1, MAX_ATTEMPTS + 1):
        try:
            return client.chat.completions.create(**kwargs)
        except openai.APIConnectionError:          # includes timeouts
            if attempt == MAX_ATTEMPTS:
                raise
            delay = backoff(attempt)
        except openai.APIStatusError as err:
            if err.status_code not in RETRY_STATUS or attempt == MAX_ATTEMPTS:
                raise                               # 401/402/403/404/4xx: stop
            wait = retry_after(err)
            if wait is not None and wait > CAP:
                raise                               # e.g. maintenance: tell the user
            delay = wait if wait is not None else backoff(attempt)
        time.sleep(delay)


reply = chat_with_retries(
    model="gpt-6-luna",
    messages=[{"role": "user", "content": "Say hello in one word."}],
)
print(reply.choices[0].message.content)

Node retry helper

import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.FREEMODEL_API_KEY,
  baseURL: "https://freemodel.in/v1",
  maxRetries: 0,
  timeout: 120_000,
});

const RETRY_STATUS = new Set([429, 502, 503, 504]);
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

function retryAfterSeconds(err) {
  const h = err.headers;
  const v = typeof h?.get === "function" ? h.get("retry-after") : h?.["retry-after"];
  const n = Number(v);
  return v != null && Number.isFinite(n) ? n : null;
}

export async function chatWithRetries(params, maxAttempts = 5) {
  for (let attempt = 1; ; attempt++) {
    try {
      return await client.chat.completions.create(params);
    } catch (err) {
      const isConnection = err instanceof OpenAI.APIConnectionError;
      const status = err instanceof OpenAI.APIError ? err.status : undefined;
      if (!(isConnection || RETRY_STATUS.has(status)) || attempt >= maxAttempts) throw err;
      const wait = isConnection ? null : retryAfterSeconds(err);
      if (wait !== null && wait > 30) throw err;
      const delay = wait !== null
        ? wait * 1000
        : Math.random() * Math.min(30_000, 1000 * 2 ** (attempt - 1));
      await sleep(delay);
    }
  }
}

What about SDK built-in retries?

The OpenAI and Anthropic SDKs already retry connection errors, 408, 409, 429 and 5xx responses, twice by default, and they read Retry-After. They do not retry 402, 403 or 404, which matches the table above.

So you have two sound options: keep the SDK retries and raise max_retries / maxRetries, or set it to 0 and use your own loop as shown. Do not do both. Three SDK attempts inside five loop attempts is fifteen requests for one user action.

With the Anthropic format (https://freemodel.in, /v1/messages), a temporarily unavailable model is reported as 529 overloaded_error with Retry-After: 3, which the Anthropic SDK treats as retryable.

Retrying streams

Errors before the first chunk behave like normal responses and can be retried the same way. Errors in the middle of a stream arrive as an error frame followed by [DONE] (see the streaming docs). Retrying at that point restarts the answer from the beginning, so clear what you have already shown the user first.

One billing detail: if you abort a stream after output has started, the output you already received counts. Set a sensible client timeout rather than cancelling and restarting slow answers.

Checklist

  • Retry only 429, 502, 503, 504 and connection errors.
  • Honour Retry-After; give up and tell the user if it is very long.
  • Use exponential backoff with full jitter, capped, for at most about five attempts.
  • Show the error message for 401, 402, 403 and 404 — it says what to do.
  • Keep one retry layer: SDK or your own, not both.
  • If 429s are routine, lower your request rate; see rate limits explained.

FAQ

Should I retry a 402 error?

No. A 402 means the plan tokens or a key limit is used up. The next attempt gets the same answer until you renew, upgrade or raise the limit.

How many times should I retry a 429?

Three to five attempts is a sensible ceiling. Wait the number of seconds in the Retry-After header first. If you keep hitting 429, slow your request rate instead of retrying harder.

Am I charged for a request that failed and was retried?

A request that fails is not charged. Only the attempt that succeeds counts. The exception is a stream you abort yourself after output has started: the output you already received counts.

Do the OpenAI and Anthropic SDKs retry on their own?

Yes. Both retry connection errors, 429 and 5xx responses twice by default. Either tune that setting or turn it off and use your own loop, but do not stack both.

Ready to build?

Grab a free API key — 1M tokens on 8 free models after a one-time Telegram verification, no card. Every model from $1.20.