Skip to main content
LLM API Rate Limits and Errors: Retries, Backoff and Fallbacks That Work
Back to Blog

LLM API Rate Limits and Errors: Retries, Backoff and Fallbacks That Work

429s and overload errors are part of running AI features in production. Which LLM API errors to retry, how to back off with jitter, how to prevent rate limits in the first place, and what to do when retries run out.

LuminaryEra Editorial
November 21, 202614 min read25 views

The short answer: Treat rate limits and overload errors from LLM APIs as normal operating conditions, not rare exceptions. Retry only errors that are temporary (429 rate limits, overload responses such as Anthropic's 529, 5xx server errors and timeouts), honour the retry-after header when it's present, otherwise use exponential backoff with jitter, and cap both the number of attempts and the total time spent retrying. Then prevent most 429s in the first place: limit your own concurrency, queue work that can wait, watch the rate-limit headers, and have a fallback (another model or a graceful message) for when retries run out.

Every team that ships an AI feature meets the same graph eventually. Traffic is fine for weeks. Then a newsletter goes out, a customer runs a bulk import, or an agent gets stuck in a loop, and the error rate jumps from nearly zero to a wall of 429 Too Many Requests. Users see spinners that never finish. Some requests fail outright. A few succeed after a long wait, and nobody can explain which ones or why.

The first instinct is to wrap the API call in a retry loop and move on. That helps, and it's also how teams accidentally make an outage worse: a thousand clients retrying immediately, in sync, is exactly the kind of traffic that keeps a rate limit tripped. Handling LLM API limits well takes a little more thought, but not much more code.

This guide covers what the different errors mean, which ones to retry and how, the backoff strategy that actually behaves well under load, and the design choices (concurrency limits, queues, fallbacks and monitoring) that stop you hitting limits in the first place. The examples use TypeScript and plain fetch, and the ideas apply to any provider.

LLM APIs have stricter limits than most

Most web APIs you call are cheap to serve: a database lookup, some JSON. LLM inference is expensive and uses scarce hardware, so providers ration it carefully. Limits typically apply along several dimensions at once:

  • Requests per minute: how many calls you can start.
  • Tokens per minute: how much text you send and receive. Often split into input and output tokens, and sometimes counted per model.
  • Spend limits: a monthly or daily budget cap for the account or project.
  • Concurrency: implicit or explicit limits on how many requests can be in flight.

Token limits catch people out. A feature can be well under its request limit and still hit the token limit, because one request with a large prompt or a long output uses as much budget as dozens of small ones. RAG features that stuff many documents into each prompt, and agents that resend growing conversation histories, are especially prone to this. The guide on cutting LLM API costs covers how to shrink prompts, which also gives you headroom on token limits.

Separately from your own limits, providers sometimes run short of capacity overall, during a big launch or a traffic spike across all customers. That produces a different error, one you can't fix by slowing down your own traffic. It's worth handling it as its own case.

Reading the errors correctly

The first job of any retry logic is to tell temporary failures from permanent ones. Retrying a permanent error wastes time and money; giving up on a temporary one fails requests that would have succeeded a second later.

ResponseMeaningRetry?
429 rate limitYou exceeded a request or token limitYes, after waiting
Overload (e.g. Anthropic 529, OpenAI 503 server_is_overloaded)The provider is short of capacityYes, with backoff; consider a fallback
500, 502, 504, connection errors, timeoutsTransient server or network problemYes, a limited number of times
400 invalid requestSomething is wrong with what you sentNo: fix the request
401 / 403Authentication or permission problemNo
404Wrong model name or endpointNo
Spend or quota exhaustedAccount budget reachedNo, until someone raises the limit

Provider documentation spells out the details. Anthropic's error reference lists 429 with the type rate_limit_error and 529 with overloaded_error for when the API is temporarily overloaded. OpenAI's rate limit guide describes 429s for rate limits and a separate 503 with the code server_is_overloaded for overload.

One subtle case deserves a mention: not every 429 is temporary. Anthropic's rate limit documentation notes that a 429 caused by hitting a spend cap never includes a retry-after header. Retrying that kind of 429 won't help; it needs a human to change a budget. Your code should recognise it from the error body and fail fast with a clear alert rather than spinning through retries.

The rate-limit headers are a gift: use them

Both major providers return headers describing your current limits on successful responses, not just on errors. Anthropic uses names like anthropic-ratelimit-requests-remaining, anthropic-ratelimit-requests-reset and token variants such as anthropic-ratelimit-input-tokens-remaining (see its rate limits documentation). OpenAI uses x-ratelimit-remaining-requests, x-ratelimit-remaining-tokens and matching x-ratelimit-reset-* headers.

Two headers matter most:

  • retry-after on a 429 or overload response tells you how many seconds to wait. OpenAI's guide describes it as the minimum time to wait and recommends adding a small random delay on top, so many clients don't retry at the same moment. When it's present, it beats any backoff formula you invent.
  • The remaining-capacity headers on successful responses let you slow down before you hit the limit. If remaining tokens are running low, a well-behaved client can pause new work briefly rather than firing requests that will be rejected.

Log these headers. When someone asks "why did we start getting 429s at 3pm?", the remaining-capacity values over time usually answer the question immediately.

Retrying well: backoff with jitter

When there's no retry-after header, use exponential backoff: wait a short time after the first failure, then double the wait for each subsequent attempt. Add jitter, a random component, so that many clients that failed at the same moment don't all retry at the same moment too. Without jitter, retries arrive in synchronised waves that can keep a limit tripped indefinitely, a pattern often called a thundering herd. Marc Brooker's widely cited article on exponential backoff and jitter shows why "full jitter", choosing a random wait between zero and the exponential ceiling, works well in practice.

Equally important are the limits on retrying itself. OpenAI's guide puts it well: limit both the number of attempts and the total time spent retrying. A user waiting on a chat response won't wait two minutes for your retry loop to give up.

Timeline comparing retries without jitter, where many clients retry at the same instants and keep hitting the rate limit, with full-jitter backoff, where retries spread out randomly under a growing ceiling and get through

Here's a compact, provider-agnostic implementation:

const RETRYABLE = new Set([408, 409, 429, 500, 502, 503, 504, 529]);

interface RetryOptions {
  maxAttempts?: number;  // total tries, including the first
  baseDelayMs?: number;  // first backoff ceiling
  maxDelayMs?: number;   // cap on any single wait
  deadlineMs?: number;   // total time budget for all attempts
}

export async function fetchWithRetry(
  url: string,
  init: RequestInit,
  { maxAttempts = 4, baseDelayMs = 500, maxDelayMs = 20_000, deadlineMs = 45_000 }: RetryOptions = {},
): Promise<Response> {
  const started = Date.now();

  for (let attempt = 1; ; attempt++) {
    let res: Response | undefined;
    try {
      res = await fetch(url, init);
      if (!RETRYABLE.has(res.status)) return res; // success or a permanent error
    } catch (err) {
      if (init.signal?.aborted) throw err; // the caller cancelled: don't retry
      // network error: fall through and retry
    }

    if (attempt >= maxAttempts) {
      if (res) return res; // let the caller see the final error response
      throw new Error("Request failed after retries");
    }

    // Prefer the server's instruction; otherwise exponential backoff with full jitter.
    const retryAfter = Number(res?.headers.get("retry-after"));
    const ceiling = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1));
    const wait = Number.isFinite(retryAfter) && retryAfter > 0
      ? retryAfter * 1000 + Math.random() * 500
      : Math.random() * ceiling;

    if (Date.now() - started + wait > deadlineMs) {
      if (res) return res;
      throw new Error("Retry budget exhausted");
    }
    await new Promise((r) => setTimeout(r, wait));
  }
}

A few details in there matter. The function returns the last error response instead of swallowing it, so the caller can show a useful message. It respects cancellation, so a user who has given up doesn't keep a retry loop alive. And it checks the total deadline before sleeping, not after.

Use your SDK's retries, but configure them

Official SDKs usually retry for you. Anthropic's SDKs, for example, retry connection errors and 408, 409, 429 and 5xx responses twice by default, and let you change that with a max_retries (or maxRetries) option and a timeout setting. OpenAI's SDKs have similar settings. Don't stack your own retry loop on top of the SDK's without thinking: three SDK retries inside four application retries is twelve attempts and a very long wait. Pick one layer to own retries, and configure it deliberately.

Retries and streaming

Streaming responses need a different rule. If a request fails before the first token arrives, retrying is invisible to the user and usually the right call. Once text is on the screen, retrying silently means either duplicating text or stitching together two different generations. The guide to streaming LLM responses covers this in detail: retry automatically only before the stream starts, and after that show the partial answer and let the user choose to retry.

Preventing 429s instead of recovering from them

Retries are the safety net. The better strategy is not to need them often. Most rate-limit trouble comes from bursts that your own system created, and a few design choices smooth them out.

Limit your own concurrency

If one user action can trigger many LLM calls (an agent with tools, a batch summary, a page that generates several sections at once), cap how many calls run in parallel. A simple semaphore stops one busy user or job from consuming your entire account limit:

export function createLimiter(maxConcurrent: number) {
  let active = 0;
  const waiting: (() => void)[] = [];

  return async function run<T>(task: () => Promise<T>): Promise<T> {
    if (active >= maxConcurrent) await new Promise<void>((resolve) => waiting.push(resolve));
    active++;
    try {
      return await task();
    } finally {
      active--;
      waiting.shift()?.();
    }
  };
}

const llm = createLimiter(8);
const summaries = await Promise.all(docs.map((d) => llm(() => summarise(d))));

This in-process limiter works within one server instance. If you run many instances or serverless functions, you need a shared limit, typically a token bucket in Redis or a queue with a fixed number of workers.

Queue anything that can wait

Not every LLM call needs an answer within seconds. Report generation, nightly classification, backfilling summaries and evaluation runs can all go through a queue processed at a steady rate below your limits. A queue turns a spike of a thousand requests into a smooth stream, and it gives you somewhere to retry failed jobs without a user waiting. For large volumes, providers' batch APIs are often cheaper too, as described in the cost guide.

Give each feature a budget

When several features share one API key, the noisiest one can starve the others. Separate keys or projects per feature (where your provider supports them) or a per-feature limiter in your own code keeps a runaway batch job from breaking the customer-facing chat. Interactive features should get priority; background work should yield.

Shrink what you send

Token limits are hit by large requests, so every token you remove from prompts buys headroom. Trimming retrieved context, clearing old tool results in agents and using prompt caching all reduce pressure on token-per-minute limits as well as on cost.

Estimating tokens before you send

Request limits are easy to respect: count requests. Token limits are harder, because you only learn how many tokens a request used after it finishes. A client that waits for the response to update its budget will regularly overshoot during bursts, especially when several large requests start at once.

The fix is to estimate before you send. Before each call, estimate its input tokens, add the maximum output tokens you've allowed for it, and reserve that amount from a shared budget. When the response arrives, replace the estimate with the real usage reported by the API. If the budget for the current minute is exhausted, the request waits in a queue instead of going out to collect a 429.

Estimates don't need to be perfect. For English prose, a rough rule of thumb is about four characters per token, but tokenizers differ between providers and models, and code, other languages and unusual text can vary a lot. Some providers offer a token-counting endpoint you can call when precision matters, for example before sending a very large document. For ordinary traffic, a conservative character-based estimate corrected by actual usage works well, as long as you reserve the full max_tokens for output rather than guessing low.

This approach pays off most for features with highly variable request sizes, such as document summarisation or RAG over long sources, where a handful of huge requests can consume a minute's token budget on their own. It also gives you a natural place to apply priorities: interactive requests can draw from the budget first, while batch work waits until there's room.

Keep the budget slightly below the provider's published limit, leaving headroom for estimation error and for other services that share the same account. A limiter set to exactly the limit will still trip it occasionally, which defeats the purpose.

Fallbacks: what happens when retries run out

Eventually some requests will fail even after sensible retries, especially during a provider-wide overload. Decide in advance what happens then, per feature.

  • Fall back to another model. A different model from the same provider, or another provider entirely, can carry traffic during an overload. This needs testing: prompts tuned for one model may behave differently on another, and structured output formats may need adjusting. Some providers now offer built-in fallback options for particular error types; check what yours supports.
  • Degrade gracefully. A search feature can fall back to plain keyword search. A summary can show the original text with a note. A writing assistant can say it's busy and offer to try again, while keeping the user's input safe.
  • Defer. For non-urgent work, put the request back on a queue with a longer delay rather than failing it.
  • Fail clearly. When nothing else applies, tell the user what happened and what to do, instead of a spinner that never ends.

Circuit breakers

If a provider is clearly overloaded, hammering it with retries from every request helps nobody. A circuit breaker watches the recent failure rate and, when it crosses a threshold, "opens": for a short period, requests go straight to the fallback without trying the overloaded provider at all. After the cooldown, a few trial requests test whether it has recovered. This protects your latency, your users' patience and the provider's recovery.

Agents need limits on themselves

Agents deserve special attention because they generate their own traffic. A loop that calls the model, runs a tool and calls the model again can produce dozens of requests per user task, and a bug that makes the agent repeat itself can burn through your rate limit and your budget at once. Protect against it:

  • Cap the number of steps and the total tokens per task.
  • Rate-limit tool calls that hit external services too, not just model calls.
  • Detect repeated identical tool calls and stop the loop.
  • Alert on unusual spend per hour per feature.

The guide to designing tools for AI agents covers how good tool design reduces wasted steps in the first place.

Monitoring: see trouble before users do

Record, per feature and per model:

  • Counts of 429, overload and other errors, and how many requests needed retries.
  • Retry counts and the total extra latency they added.
  • Remaining-capacity headers over time.
  • Fallback activations and circuit-breaker state.
  • Final failures that reached users.

Alert on rates, not individual errors. A few 429s a day are normal; a sudden rise is worth a look. The guide on LLM observability shows how to capture this alongside the rest of each request's trace.

Testing your retry logic

Retry code is the kind that only runs when things go wrong, which means it's often broken without anyone knowing. Test it deliberately:

  • Point your client at a fake server that returns 429 with and without retry-after, overload errors, 500s, timeouts and a spend-cap 429, and check the behaviour for each.
  • Assert that permanent errors are not retried.
  • Assert that total retry time stays within the deadline.
  • Run a small load test against the fake server to confirm that jitter actually spreads retries out.
  • Check that cancelling a request stops its retries.

Use fake timers in unit tests so you're not waiting for real backoff delays.

A checklist

  • ☐ Permanent errors (400, 401, 403, 404, spend caps) are never retried
  • ☐ 429, overload, 5xx and network errors are retried a limited number of times
  • ☐ retry-after is honoured, with a little added jitter
  • ☐ Otherwise, exponential backoff with full jitter, capped per wait and in total
  • ☐ Exactly one layer owns retries: the SDK or your code, not both
  • ☐ Streams retry automatically only before the first token
  • ☐ Concurrency is limited per process, and shared limits exist across instances
  • ☐ Background work goes through a queue at a steady rate
  • ☐ Each feature has a fallback and a clear failure message
  • ☐ Agents have step, token and spend limits
  • ☐ Rate-limit errors, retries and remaining-capacity headers are monitored

Frequently asked questions

How should I handle 429 errors from an LLM API?

Treat 429 as temporary unless it's a spend or quota cap. Wait for the number of seconds in the retry-after header if it's present, adding a little random delay; otherwise use exponential backoff with jitter. Limit both the number of attempts and the total retry time, and reduce future 429s by limiting your own concurrency and queueing non-urgent work.

What is the difference between a rate limit error and an overloaded error?

A rate limit error means your account or project exceeded its own request or token limits, so slowing down fixes it. An overload error, such as Anthropic's 529 or OpenAI's 503 server_is_overloaded, means the provider is short of capacity generally. Backoff helps with both, but overloads are also a good reason to switch to a fallback model or degrade gracefully.

What is exponential backoff with jitter?

Exponential backoff means waiting longer after each failed attempt, typically doubling the wait each time up to a maximum. Jitter adds randomness to each wait, so many clients that failed together don't retry at the same moment. Choosing a random wait between zero and the exponential ceiling, called full jitter, spreads retries out effectively.

Should I retry LLM requests inside my code or rely on the SDK?

Either works, but only one layer should own retries. Official SDKs commonly retry certain errors automatically and let you configure the maximum retries and timeouts. If you add your own retry loop, reduce or disable the SDK's retries so attempts don't multiply.

How do I avoid hitting LLM rate limits?

Limit how many requests run in parallel, use a shared limiter or queue across server instances, process background work at a steady rate, give each feature its own budget, cap agent loops, and send fewer tokens per request through trimmed context and prompt caching. Monitor the remaining-capacity headers to slow down before limits are reached.

The takeaway

Rate limits and overloads aren't edge cases for AI features; they're part of normal operation, especially as traffic grows. Retry the right errors, wait the right amount of time with jitter, and put firm limits on how long you try. Then do the more valuable work: smooth out your own bursts, give each feature a budget, and decide in advance what users see when the model isn't available. Done well, a provider's bad afternoon becomes a slightly slower afternoon for your users rather than an outage.

Share this article
LuminaryEra Editorial
Editorial

Author at LuminaryEra

The LuminaryEra editorial desk publishes long-form, hands-on guides on AI-assisted development, large language models, developer tools and web engineering. Articles are researched and drafted with the help of AI tools, link to their sources, and are corrected when readers report errors.

View all articles