Error Handling for LLM APIs in Production: Retries, Backoff, Timeouts and Broken Streams

Which errors to retry and which not to, exponential backoff and Retry-After, setting timeouts, handling streams that stop midway, and concurrency limits and circuit breaking — with a Python example and UnioAPI's error mapping.

3 min read

LLM APIs aren't quite like ordinary HTTP endpoints: a single request can run for tens of seconds or even minutes, models get temporarily overloaded, streams can stop halfway, and every retry may be charged. Handling these well is part of moving from a demo to production.

Step 1: know which errors to retry

StatusCommon causesRetry?
400Bad parameters, context too long, tier not offeredNo — fix the request
401Invalid, revoked or expired keyNo
402Insufficient balance, or the key reached its spend capNo — top up or adjust the cap
404Wrong model ID or endpointNo
429Rate or concurrency limit, Flex capacity, balance briefly heldYes — back off per Retry-After
500Internal errorYes, a limited number of times
503 / 529Model temporarily overloaded or unavailableYes, after backing off
504Processing timeoutDepends — consider splitting long tasks

Don't retry any 4xx except 429: sending the same request again won't change the outcome, it only wastes quota.

Step 2: exponential backoff with jitter

Don't resend immediately, and don't let every client resend at the same instant:

  • Honour the Retry-After header first;
  • Without it, start at 1 second and double each time (1, 2, 4, 8 …), with a ceiling;
  • Add a little random jitter so requests don't surge back together;
  • Cap the number of retries, typically 3 to 5.
import random, time
import openai
from openai import OpenAI

client = OpenAI(base_url="https://api.unioapi.com/v1", api_key="<UNIO_API_KEY>", max_retries=0, timeout=300)

RETRYABLE = (openai.RateLimitError, openai.InternalServerError, openai.APIConnectionError, openai.APITimeoutError)

def call_with_retry(**kwargs):
    for attempt in range(5):
        try:
            return client.responses.create(**kwargs)
        except RETRYABLE as err:
            if attempt == 4:
                raise
            headers = getattr(getattr(err, "response", None), "headers", {}) or {}
            delay = float(headers.get("retry-after", 2 ** attempt))
            time.sleep(min(delay, 30) + random.uniform(0, 0.5))

The official SDKs retry on their own (twice by default). If you implement retries yourself as above, set the SDK's max_retries to 0 so the two layers don't stack.

Step 3: set timeouts per workload

  • Ordinary chat: tens of seconds is usually enough.
  • Reasoning models at high effort: the first token can take a long time — stream, and allow several minutes in total.
  • The Pro line: a single request can run for minutes; allow at least 5.

The sneakiest problem with short timeouts: the client gives up while the server may still be generating. If the model has produced output, the call is still charged — and if you retry, you've paid twice.

Step 4: treat broken streams correctly

Streams have explicit end markers:

APINormal end
Chat Completionsdata: [DONE]
Responsesa terminal event such as response.completed
Messagesmessage_stop

No end marker means not finished, even if you already have plenty of text. Suggestions:

  • Keep the partial output in the UI and offer "regenerate";
  • Streams can't resume from the break point — a retry sends the full request again;
  • Log the request ID of the interrupted call so you can reconcile it later. On UnioAPI, an interrupted stream is billed for the output already delivered.

Step 5: limit concurrency, and break the circuit when needed

  • Bound concurrency with a semaphore: limits are counted per account and shared by all its keys, so batch jobs need a concurrency ceiling.
  • Circuit breaking: a burst of consecutive 503 / 529 responses means the model is temporarily overloaded. Rather than retrying nonstop, pause for tens of seconds, or move non-critical work to a backup model from the same vendor.
  • Give Flex jobs a fallback: on 429 flex_unavailable, retry later or drop service_tier to send as Standard.

Step 6: make every call traceable

  • Send your own X-Request-ID with each request (an order number plus a sequence, say); it's used as-is, so logs, bills and support tickets line up one to one;
  • Record status, model, usage and latency, and monitor error rates and usage;
  • Alert on 402 separately — balance and spend-cap errors don't fix themselves.

UnioAPI's error shapes

UnioAPI returns errors in the shape of the protocol you called — OpenAI's error.type / error.code or Anthropic's error.type — matching the official APIs, so existing error handling keeps working. The full mapping is in Errors; rate limits are in Rate limits.

Two billing rules worth remembering: requests rejected before execution (400, 401, 402, 404, 429 …) are free, and so are requests that fail before producing any output.

Keep reading