Skip to content
MangoBoost

How to Retry 429 and 503 Errors From an LLM API

How to Retry 429 and 503 Errors From an LLM API

Retry 429 and 5xx responses with backoff, wait as long as Retry-After says, and do it in exactly one place in your code. Don't retry 400-level errors such as a bad request or an invalid key: the second attempt fails the same way.

It's easy to miss that the OpenAI SDK already retries, so a retry loop you add on top of it multiplies every failed call.

What do 429 and 503 mean?

Both mean "not now", for different reasons:

  • 429 Too Many Requests: you went over a rate limit, usually requests per minute or concurrent requests for your API key or organization. Waiting fixes it.
  • 503 Service Unavailable (and 502, 529): the server side is busy, starting up or briefly unreachable. Waiting usually fixes it too.

On Mango Inference's shared (serverless) models, a 429 always comes from your own key's or organization's limits. When a model's inference engine is full, you get a 503 with the code upstream_at_capacity or upstream_rate_limited instead, so you can tell "slow down" from "the model is busy". Both can carry a Retry-After header. The full list of codes is in Reliability and error handling.

Which errors should you retry?

Retry only errors that can succeed if you send the same request again later:

Retry decision: your app sends every request through one retry layer to the Mango Inference API. A 2xx response is returned. A 429 or 5xx waits for Retry-After, or an exponential backoff with jitter, and tries again until the attempt or time limit. A 400, 401, 402, 403 or 404 fails right away without a retry.
Retry decision: your app sends every request through one retry layer to the Mango Inference API. A 2xx response is returned. A 429 or 5xx waits for Retry-After, or an exponential backoff with jitter, and tries again until the attempt or time limit. A 400, 401, 402, 403 or 404 fails right away without a retry.
  • 429: Retry?: Yes, after Retry-After; Why: The limit resets on its own
  • 500, 502, 503, 529: Retry?: Yes, with backoff; Why: Temporary server-side problem
  • Network error or timeout: Retry?: Yes, with backoff; Why: The request may not have arrived
  • 400, 404: Retry?: No; Why: The request itself is wrong
  • 401, 403: Retry?: No; Why: The key is invalid, disabled or not allowed this model
  • 402: Retry?: No; Why: The balance is too low; top up first

Does the OpenAI SDK already retry?

Yes. The OpenAI Python SDK retries twice by default. We read the source of version 3.60.0: it retries 408, 409, 429, every 5xx and connection errors, waits 0.5 s, then 1 s (doubling up to 8 s, each wait shortened at random by up to 25%), and follows Retry-After when it is two minutes or less.

That changes how many requests a single call turns into. We pointed clients at a local test server that always answered with an error and counted the requests:

  • SDK defaults: Server answer: 429, Retry-After: 1; Requests for one call: 3
  • Your own 3-attempt loop around the SDK defaults: Server answer: 503; Requests for one call: 9
  • SDK retries off, the function below: Server answer: 429, Retry-After: 1; Requests for one call: 4
  • SDK retries off, the function below: Server answer: 401; Requests for one call: 1

※ Run on November 27, 2026, against a local mock server, openai 3.60.0.

Nine requests for one call can stretch a short 503 into a long one. With a whole fleet of clients doing the same, retries become most of the traffic, and they arrive exactly when the server or your quota is already at its limit. If you also retry in a job queue or an API gateway, multiply again.

So choose one layer. If the SDK's defaults suit you, raise or lower them with OpenAI(max_retries=..., timeout=...) and don't add a loop. If you need your own rules, turn the SDK's retries off.

What does a retry function look like?

This version turns SDK retries off and keeps all the rules in one function: retry only 429, 5xx and network errors, follow Retry-After, otherwise back off with jitter, and stop after four attempts or 30 seconds in total, counting the time each request takes.

python
import os
import random
import time

from openai import APIConnectionError, APIStatusError, OpenAI

client = OpenAI(
    base_url="https://api.mangoboost.io/v1",
    api_key=os.environ["MANGOINFERENCE_API_KEY"],
    max_retries=0,  # retries happen in one place: below
)
RETRYABLE = {429, 500, 502, 503, 529}

def create_with_retry(max_attempts=4, deadline_s=30, **kwargs):
    start = time.monotonic()
    for attempt in range(1, max_attempts + 1):
        remaining = deadline_s - (time.monotonic() - start)
        try:
            # Each attempt gets only the time that is left, so the whole call ends within deadline_s.
            return client.with_options(timeout=remaining).chat.completions.create(**kwargs)
        except (APIStatusError, APIConnectionError) as e:
            status = getattr(e, "status_code", None)  # None: network error or timeout
            if status is not None and status not in RETRYABLE:
                raise  # 400, 401, 402, 403, 404: retrying won't help
            headers = e.response.headers if status else {}
            retry_after = headers.get("retry-after")
            if retry_after:
                delay = float(retry_after)
            else:
                delay = min(8, 0.5 * 2 ** attempt) * random.uniform(0.5, 1)
            if attempt == max_attempts or time.monotonic() - start + delay >= deadline_s:
                raise
            print(f"{status or 'network error'} (x-request-id {headers.get('x-request-id')}), "
                  f"retry {attempt} in {delay:.1f}s")
            time.sleep(delay)

resp = create_with_retry(
    model="deepseek-ai/DeepSeek-V4.1-Flash-1017",
    messages=[{"role": "user", "content": "Say OK."}],
)
print(resp.choices[0].message.content)

On December 3, 2026, against the real API, the call returned OK, and a wrong key failed at once with 401 invalid_api_key, without a retry. Against a local server that never answered, a 6-second deadline ended the call after 6.0 seconds. The x-request-id it logs is what support needs to find a failed request.

A streamed response can also fail after it has started. Retrying it sends the whole prompt again and bills the tokens twice, so decide whether a partial answer is good enough before you retry.

How do you get fewer 429s in the first place?

Send less at once. Retries recover from a rate limit; they don't raise it.

  • Cap concurrency in your own code, for example with a semaphore or a worker pool, at or below your key's limit. On Mango Inference, a key on the first tier (Tier 1) is limited to 40 requests per minute and 4 concurrent requests.
  • Spread batch jobs out instead of starting them all at the top of the minute.
  • Split traffic across keys only if it is really separate work. Organization limits apply across all keys.
  • Ask for higher limits through support when your steady load needs them. There is no self-service control.

To check which limit tier your account is on and what each tier allows, read Rate limits.

Running an LLM feature in production?

If you are hitting rate limits or planning capacity for a production workload and want to talk through limits, models or dedicated deployment, contact us.

Related Posts

Function Calling Mistakes That Make LLMs Invent Results
Guides

Function Calling Mistakes That Make LLMs Invent Results

Learn more
How to Build a Voice AI Agent That Makes Phone Calls
Guides

How to Build a Voice AI Agent That Makes Phone Calls

Learn more
Why Agentic AI Breaks Classic Inference Infrastructure
Technical Insights

Why Agentic AI Breaks Classic Inference Infrastructure

Learn more
MangoBoost Launches Mango Inference, Emerging as a Key Partner Powering AMD's Enterprise AI Ecosystem
Technical Insights

MangoBoost Launches Mango Inference, Emerging as a Key Partner Powering AMD's Enterprise AI Ecosystem

Learn more
The First AMD Instinct™ Submission to MLPerf® Inference with Prefill/Decode-Disaggregated Deployment, and the Largest Multi-Region Cluster Ever Submitted
Benchmark Results

The First AMD Instinct™ Submission to MLPerf® Inference with Prefill/Decode-Disaggregated Deployment, and the Largest Multi-Region Cluster Ever Submitted

Learn more
First-ever Multi-region Heterogeneous Inference: MangoBoost Sets New Standards for Global AI Scaling in MLPerf Inference v6.0
Benchmark Results

First-ever Multi-region Heterogeneous Inference: MangoBoost Sets New Standards for Global AI Scaling in MLPerf Inference v6.0

Learn more
MangoBoost Pushes AI Scalability in MLPerf Training v5.1: First-ever Multi-node MI325X Results Highlight AMD's Scaling Capabilities
Benchmark Results

MangoBoost Pushes AI Scalability in MLPerf Training v5.1: First-ever Multi-node MI325X Results Highlight AMD's Scaling Capabilities

Learn more
Pioneering Multi-node Heterogeneous Inference: MangoBoost and AMD, in Collaboration with OEM Partners, Set Record Llama2-70B Performance in MLPerf Inference v5.1
Benchmark Results

Pioneering Multi-node Heterogeneous Inference: MangoBoost and AMD, in Collaboration with OEM Partners, Set Record Llama2-70B Performance in MLPerf Inference v5.1

Learn more
MangoBoost Demonstrates Record-Breaking Performance in AI Training Storage Solution with MLPerf® Storage v2.0
Benchmark Results

MangoBoost Demonstrates Record-Breaking Performance in AI Training Storage Solution with MLPerf® Storage v2.0

Learn more
MangoBoost Sets a New MLPerf Training v5.0 Standard for Multi-nodes Llama2-70B-LoRA on AMD Instinct™ MI300X GPU!
Benchmark Results

MangoBoost Sets a New MLPerf Training v5.0 Standard for Multi-nodes Llama2-70B-LoRA on AMD Instinct™ MI300X GPU!

Learn more
MangoBoost Sets The Highest MLPerf Inference v5.0 Result in History for Llama2-70B Offline!
Benchmark Results

MangoBoost Sets The Highest MLPerf Inference v5.0 Result in History for Llama2-70B Offline!

Learn more
MangoBoost Demonstrates Mango GPUBoost RDMA™ with MLPerf Training v4.1 on a Multi-node System Powered by AMD MI300X GPUs
Benchmark Results

MangoBoost Demonstrates Mango GPUBoost RDMA™ with MLPerf Training v4.1 on a Multi-node System Powered by AMD MI300X GPUs

Learn more
MangoBoost Demonstrates Turn-Key Storage Solution for AI Training with MLPerf® Storage v1.0
Benchmark Results

MangoBoost Demonstrates Turn-Key Storage Solution for AI Training with MLPerf® Storage v1.0

Learn more
MangoBoost Demonstrates a Turn-Key LLM Inference Serving Solution on AMD Instinct™ MI300X GPUs with the MLPerf® Inference v4.1 Llama Benchmark
Benchmark Results

MangoBoost Demonstrates a Turn-Key LLM Inference Serving Solution on AMD Instinct™ MI300X GPUs with the MLPerf® Inference v4.1 Llama Benchmark

Learn more