Your AI feature works perfectly on your laptop. Then you run it on real traffic, or point a batch job at 2,000 customer messages, and the logs fill with 429 Too Many Requests. Some calls succeed, some fail, and your retry loop makes it worse.
Every hosted LLM API limits how fast you can call it. This guide explains what LLM API rate limits are, which errors are worth retrying, and how to build a small Node.js wrapper that retries the right failures, respects the provider's instructions, and stops before it burns your budget.
What LLM API Rate Limits Are
A rate limit caps how much you can send to a provider in a window of time. LLM providers count two things at once:
- Requests per minute. How many calls you make, whatever their size.
- Tokens per minute. How much text you send and receive. A single call with a long prompt and a large
max_tokenscan use a big share of the budget on its own. Our guide to LLM tokens explains how text turns into tokens.
Limits depend on your account. OpenAI's rate limit guide describes usage tiers and shows each account's current limits on its organization limits page. Anthropic's errors documentation refers to usage tiers and spend caps in the same way. So a call pattern that is fine on one account can fail on a newer one.
Providers tell you where you stand. OpenAI returns headers such as x-ratelimit-remaining-requests, x-ratelimit-remaining-tokens, and reset times on every response. When you go over, you get a 429.
Not Every Error Deserves a Retry
The most common mistake is retrying everything. Some failures fix themselves with time. Others fail the same way forever, and retrying them only adds cost and noise. This is how the Claude API's documented status codes split, read on November 24, 2026:
| Status | Meaning | Retry? |
|---|---|---|
400 invalid_request_error | Something in your request is wrong, such as a prompt that is too long for the model | No. Fix the request. |
| 401 and 403 | The API key is wrong, revoked, or not allowed to use the resource | No. Fix the key or permissions. |
413 request_too_large | The request body is over the size limit | No. Send less. |
429 rate_limit_error | You hit a rate limit | Yes, after waiting. Read the note on spend caps below. |
500 api_error | Something failed inside the provider | Yes, with exponential backoff. |
504 timeout_error | The request timed out while processing | Yes, and consider streaming for long answers. |
529 overloaded_error | The API is overloaded across all users | Yes, with backoff. |
OpenAI's equivalent of the overloaded case is a 503 with server_is_overloaded. Network failures, such as a dropped connection or a timeout on your side, have no status code at all. Treat them as retryable too.
One 429 is a trap. Anthropic's documentation says a 429 caused by reaching your usage tier's monthly spend cap has no retry-after header and keeps failing until access resumes. OpenAI's guide makes the same point about quota and billing errors: retrying does not fix them. Your retry logic needs a time budget so a capped account fails fast instead of hanging.
How Retries Should Wait
Retrying immediately is the worst option. OpenAI's rate limit guide says unsuccessful requests still count toward your per-minute limit, so a tight retry loop keeps you over the limit. Three rules fix that.
Follow Retry-After When the Provider Sends It
When a 429 comes with a Retry-After header, the provider is telling you how many seconds to wait. OpenAI's guide says to treat that value as a minimum and add a small random delay so many clients do not retry at the same moment.
Back Off Exponentially When It Does Not
Without a hint, double the wait after each failure: about half a second, then 1 second, then 2, up to a cap. Each failure buys the provider more time to recover.
Add Jitter
If 50 workers all fail at the same second and all wait exactly 1 second, they all retry together and fail together. Jitter picks a random wait between zero and the backoff value, which spreads the retries out. This variant is often called full jitter.
Step 1: Write a Retry Wrapper
This function takes any async call and retries it according to the rules above. It works with an SDK or plain fetch, as long as the error carries a status and, for the hint, a headers object. Create the file with-retry.js:
// with-retry.js
const RETRYABLE = new Set([408, 429, 500, 502, 503, 504, 529]);
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function retryAfterMs(error) {
const value = error.headers?.get?.("retry-after");
const seconds = Number(value);
return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : null;
}
export async function withRetry(fn, {
maxAttempts = 4, // the first try plus 3 retries
baseDelayMs = 500,
maxDelayMs = 20_000,
budgetMs = 60_000, // give up when the next wait would pass this
} = {}) {
const started = Date.now();
for (let attempt = 1; ; attempt++) {
try {
return await fn(attempt);
} catch (error) {
const status = error.status;
const retryable = status === undefined || RETRYABLE.has(status);
if (!retryable || attempt >= maxAttempts) throw error;
const backoff = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1));
const jittered = Math.random() * backoff; // "full jitter"
const hint = retryAfterMs(error);
const wait = hint === null ? jittered : hint + Math.random() * 1000;
if (Date.now() - started + wait > budgetMs) throw error;
console.warn(`attempt ${attempt} failed with ${status ?? "network error"}, retrying in ${Math.round(wait)} ms`);
await sleep(wait);
}
}
}
Here is what each part does:
RETRYABLElists the statuses worth another try. An error with no status at all is a network failure or timeout, so it is retried as well. Anything else, such as a 400 or 401, is thrown straight back.maxAttemptslimits the total tries. Four attempts means one call plus three retries.- The wait uses the server's
retry-aftervalue as a minimum when it exists, plus up to 1 second of jitter. Otherwise it uses exponential backoff with full jitter, capped atmaxDelayMs. budgetMsis the total time you are willing to spend. If the next wait would go past it, the function gives up and throws the last error. This is what stops a spend-capped account from retrying for minutes.
Step 2: Cap How Many Calls Run at Once
Most 429s in a new AI feature are self-inflicted. A loop calls Promise.all() on 2,000 support messages, every request starts at once, and the account's per-minute limit is gone in the first second. Retries help after the fact. A concurrency cap stops the burst from happening. Create the file limiter.js:
// limiter.js
export function createLimiter(maxConcurrent) {
let active = 0;
const queue = [];
const next = () => {
if (active >= maxConcurrent || queue.length === 0) return;
active++;
const { task, resolve, reject } = queue.shift();
task().then(resolve, reject).finally(() => {
active--;
next();
});
};
return (task) => new Promise((resolve, reject) => {
queue.push({ task, resolve, reject });
next();
});
}
createLimiter(4) returns a function that runs at most 4 tasks at a time and queues the rest. When one finishes, the next one starts. Libraries such as p-limit do the same job with more options, but these few lines are enough to understand and own.
Pick the number from your limits, not from a guess. If your account allows 50 requests per minute and each call takes about 6 seconds, 4 or 5 concurrent calls keep you under the limit with room to spare.
Step 3: Put It Together
The final piece wraps a real model call. It uses the Anthropic TypeScript SDK, installed with npm install @anthropic-ai/sdk, with your key in the ANTHROPIC_API_KEY environment variable. Add "type": "module" to your package.json, then create the file ask-model.js:
// ask-model.js
import Anthropic from "@anthropic-ai/sdk";
import { withRetry } from "./with-retry.js";
import { createLimiter } from "./limiter.js";
const client = new Anthropic({
maxRetries: 0, // we own the retries, so the SDK must not add its own
timeout: 60_000, // abort a single attempt after 60 seconds
});
const limit = createLimiter(Number(process.env.LLM_MAX_CONCURRENCY ?? 4));
export function askModel(prompt) {
return limit(() =>
withRetry(async () => {
const message = await client.messages.create({
model: process.env.CLAUDE_MODEL,
max_tokens: 512,
messages: [{ role: "user", content: prompt }],
});
return message.content.find((block) => block.type === "text")?.text ?? "";
})
);
}
Two settings matter here:
maxRetries: 0turns off the SDK's own retries. Anthropic's errors documentation says the official SDK retries connection errors, rate limits, and 5xx errors twice by default with exponential backoff. That is a good default if you write no retry code. Once you addwithRetry(), leaving it on means up to 3 SDK tries inside each of your 4 attempts: 12 requests for one question. OpenAI's guide gives the same warning about nested retry loops multiplying requests.timeoutlimits a single attempt. Without it, one hung connection can hold a slot in your limiter for minutes. A timeout throws an error with no status, sowithRetry()treats it as retryable.
The model name comes from the CLAUDE_MODEL environment variable. Model names change, so check your provider's models page and keep the name out of your code.
Now a batch job is safe to run:
import { askModel } from "./ask-model.js";
const summaries = await Promise.all(
messages.map((text) => askModel(`Classify this payment complaint in 3 words: ${text}`))
);
All the calls are created at once, but only 4 run at a time, and each one retries on its own schedule.
What to Do When Retries Run Out
withRetry() eventually throws. What happens next depends on the feature.
- Interactive chat. Show a clear message and a retry button. Keep the user's input so they do not have to type it again. If you stream answers, our guide to streaming LLM responses in Node.js covers the extra case of an error arriving halfway through a reply, after the 200 status is already sent.
- Background jobs. Put the failed item back on a queue with a later run time instead of retrying inside the same process. If the job writes to your database, make sure a second run cannot write twice. Our newsletter issue on idempotency in API design explains the pattern.
- A fallback model. When the error is an overload (529 or 503), trying a different model, or a different provider, often works. Keep the fallback name in configuration and log every time you use it, because the answers can differ.
Log the provider's request ID on every failure. Anthropic returns it in the request-id header and in error bodies, and it is the first thing support will ask for. Our guide on how to debug AI backend systems shows how to trace one request across your services.
Rate Limits Cost Money Before They Cost Uptime
Hosted LLM APIs bill in dollars, and many teams pay with a card that has a fixed monthly limit. A retry loop without a budget does not just slow your app down. It can keep sending large prompts through a long outage, and every successful retry is billed.
A few habits keep the bill predictable:
- Set a spend limit in your provider's console. A hard stop is better than a surprise at the end of the month.
- Keep prompts and
max_tokenssmall. Smaller calls use less of your tokens-per-minute limit and cost less when they are retried. - Cache repeat answers. If 300 users ask what your refund policy is, you do not need 300 model calls.
- Develop against a local model. Ollama runs open-weight models on your own machine with no per-token bill and no account rate limit, so you can test your retry and limiter code before you pay for anything. It is also forgiving when your connection drops, because nothing leaves your machine.
This guide is about the client side: calling a provider without getting blocked. If you run your own AI API and need to protect it from your users, that is the other side of the same problem, covered in our guide to implementing rate limiting for AI APIs.
How We Tested This Code
We ran every block on November 24, 2026, with Node.js 22 and @anthropic-ai/sdk 1.13.0, against a local server that returns the Claude API's documented error shapes. We checked five cases: a 429 with retry-after: 1 followed by success, a 529 then a 500 then success, a 400 that must not be retried, four 529s in a row that exhaust the attempts, and 10 parallel calls through a limiter set to 4. The 400 failed on the first attempt, the 429 waited just over 1 second before its retry, and the server never saw more than 4 requests at once. We did not call the paid API.
Retries, limits, and timeouts are one layer of a production AI backend. The AI Engineering course covers the rest in order, from working with the API and handling errors to RAG pipelines, agents, and taking a prototype to production.
Sources
- Claude API errors, Claude Platform documentation, read November 24, 2026.
- Rate limits, OpenAI API documentation, read November 24, 2026.
Summary
LLM API rate limits cap the requests and tokens you can send per minute, and they vary by account. When you hit one, you get a 429. Retry 429s, 5xx errors, overloads, timeouts, and dropped connections. Never retry 400, 401, 403, or 413.
Wait before each retry. Follow Retry-After when the provider sends it, and use exponential backoff with jitter when it does not. Cap the attempts and the total time so a spend-capped account fails fast. Turn off the SDK's built-in retries when you write your own, cap concurrency so you stop causing 429s in the first place, and decide in advance what the user sees when retries run out.
Frequently Asked Questions
What Does a 429 Error Mean on an LLM API?
A 429 means you sent more requests or tokens than your account is allowed in the current window. Anthropic returns it as rate_limit_error and OpenAI as rate_limit_error too. It is usually temporary: wait, then retry. The exception is a 429 caused by a spend cap, which keeps failing until the cap resets or you raise it.
How Long Should I Wait Before Retrying an LLM API Call?
If the response has a Retry-After header, wait at least that many seconds. OpenAI's rate limit guide says to treat the value as a minimum and add a small random delay. Without the header, use exponential backoff with jitter: a short random wait after the first failure, a longer one after the second, with a cap.
Which LLM API Errors Should I Retry?
Retry rate limits (429), server errors (500, 502, 503, 504), Anthropic's overloaded error (529), timeouts, and dropped connections. Do not retry 400, 401, 403, or 404. Those mean the request, the key, or the permissions are wrong, and sending the same request again gives the same answer.
Do Failed Requests Count Toward My Rate Limit?
Yes, for OpenAI. Its rate limit guide says unsuccessful requests contribute to your per-minute limit, so resending a request in a tight loop makes the problem worse. That is why backoff waits longer after each failure instead of retrying immediately.
Does the Anthropic SDK Retry Automatically?
Yes. Anthropic's errors documentation says the official SDK retries connection errors, rate limits, and 5xx errors twice by default with exponential backoff, and honors the retry-after header. Set maxRetries to change that. If you write your own retry loop, set maxRetries to 0 so the two layers do not multiply each other.
How Do I Avoid Hitting Rate Limits in the First Place?
Cap how many calls run at once, keep prompts and max_tokens small, cache answers you can reuse, and move bulk work to a batch API where your provider offers one. Most self-inflicted 429s come from a loop that fires hundreds of calls in parallel.



