---
title: "How do I handle 429 rate limit errors from an LLM API?"
description: "A 429 means you hit a requests-per-minute or tokens-per-minute cap. Let the SDK retry, back off with jitter, cap concurrency, and move non-urgent work to batches."
url: https://www.danny.engineering/answer/ai/how-do-i-handle-429-rate-limit-errors-from-an-llm-api
author: Danny
published: 2026-12-03T00:00:00.000Z
updated: 2026-12-03T15:34:00.000Z
tags: ["AI"]
---

# How do I handle 429 rate limit errors from an LLM API?

## The short answer


A 429 is the API telling you to slow down, not that something is broken. The Anthropic SDK already retries 429s with exponential backoff; raise `maxRetries` for anything that is not interactive, catch `Anthropic.RateLimitError` for the cases that still get through, and stop firing hundreds of requests at once. For batch jobs, limit concurrency with a small queue, or use the Message Batches API and let the provider schedule the work.


```typescript
import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic({ maxRetries: 5 });

try {
  const response = await client.messages.create({
    model: 'claude-haiku-5-5',
    max_tokens: 512,
    messages: [{ role: 'user', content: prompt }],
  });
} catch (err) {
  if (err instanceof Anthropic.RateLimitError) {
    // Retries are exhausted. Queue it, show a message, or fail the job.
  } else {
    throw err;
  }
}
```


## What it means


Most providers enforce two limits per model, measured over a rolling minute: requests per minute (RPM) and tokens per minute (TPM, often split into input and output). Your tier sets the numbers, and you can usually see them, and the remaining headroom, in response headers or the provider console. Hit either ceiling and you get HTTP 429 with a `retry-after` header saying how many seconds to wait.


The two limits fail in different ways. RPM bites when you send many small requests at once: a loop over a thousand rows with `Promise.all` fires a thousand requests in the same second, and most of them come back as 429. TPM bites when requests are large: a few hundred requests that each carry a 20,000-token document will exhaust the token budget long before the request count matters. Knowing which one you hit tells you whether to send fewer requests or smaller ones.


A 429 is designed to be retried. The request did nothing and cost nothing. The only mistake is retrying immediately, which keeps you pinned against the ceiling and makes the problem worse for every other request you have in flight.


## How to fix it


### Lean on the SDK's built-in retries


By default the SDK retries 429 and 5xx responses twice, with exponential backoff, and honours `retry-after` when it is present. For a background job you can afford to wait longer, so raise the count. You can set it per client or per request.


```typescript
const client = new Anthropic({ maxRetries: 5 });

// Or override for one call
await client.messages.create({ ...params }, { maxRetries: 8 });
```


For a user-facing request where waiting twenty seconds is worse than failing fast, leave the default and handle the error in the UI.


### Catch the typed error


When retries run out the SDK throws `Anthropic.RateLimitError`. Catch the most specific class first, then fall through to `Anthropic.APIError`, which has a `status` property.


```typescript
try {
  return await client.messages.create(params);
} catch (err) {
  if (err instanceof Anthropic.RateLimitError) {
    await queue.requeue(job, { delaySeconds: 60 });
    return;
  }
  if (err instanceof Anthropic.APIError) {
    console.error('API error', err.status, err.message);
  }
  throw err;
}
```


### Write your own backoff only if you have to


If you are calling the HTTP API directly, or wrapping a different provider's client, the pattern is: wait, double the wait, add randomness, give up after a few tries. The randomness (jitter) matters. Without it, every request that failed at the same moment retries at the same moment and you get a second wave of 429s.


```typescript
async function withBackoff<T>(fn: () => Promise<T>, attempts = 5): Promise<T> {
  for (let i = 0; ; i++) {
    try {
      return await fn();
    } catch (err) {
      const isRateLimit = err instanceof Anthropic.RateLimitError;
      if (!isRateLimit || i >= attempts - 1) throw err;
      const base = Math.min(30_000, 1000 * 2 ** i);
      const delay = base / 2 + Math.random() * (base / 2);
      await new Promise((r) => setTimeout(r, delay));
    }
  }
}
```


If the response gives you `retry-after`, use that value instead of your computed delay; the server knows when the window resets and you do not.


### Cap concurrency with a queue


Retries treat the symptom. The cause is usually sending too many requests at once. A concurrency limiter keeps a fixed number in flight and starts the next as each finishes, so you never exceed the ceiling in the first place. `p-limit` is the smallest tool for the job.


```typescript
import pLimit from 'p-limit';

const limit = pLimit(4); // at most 4 requests in flight

const summaries = await Promise.all(
  documents.map((doc) => limit(() => summarise(doc))),
);
```


Start low (3 to 5) and raise it until you see occasional 429s, then back off one step. If your limit is in tokens rather than requests, also sort or chunk your inputs so one huge document does not land at the same time as several others.


### Use the Message Batches API for non-urgent work


If nobody is waiting on the result, do not fight the per-minute limits at all. The Batches API accepts up to thousands of requests in one call, processes them within 24 hours (usually much sooner), and charges half the normal price. Results come back in any order, so give each request a `custom_id` you can join on.


```typescript
const batch = await client.messages.batches.create({
  requests: documents.map((doc) => ({
    custom_id: doc.id,
    params: {
      model: 'claude-haiku-5-5',
      max_tokens: 512,
      messages: [{ role: 'user', content: `Summarise:\n\n${doc.text}` }],
    },
  })),
});
```


Nightly classification, backfills, evaluation runs and report generation all belong here.


### Reduce token pressure


If you hit the tokens-per-minute limit, every token you do not send is headroom. Trim the system prompt. Send the relevant section of a document rather than the whole thing. Use prompt caching for a large fixed prefix: a system prompt or reference document marked with `cache_control: { type: 'ephemeral' }` is read from cache on later requests, which is cheaper, and on most providers cached tokens count less (or not at all) towards the token limit. Check `usage.cache_read_input_tokens` to confirm the cache is being hit, and check your provider's docs for how cached tokens are counted against limits.


## Common pitfalls

- **Retrying immediately in a tight loop.** You stay pinned at the ceiling and turn one 429 into fifty. Always wait, and always increase the wait.
- **No jitter.** Synchronised retries produce a second spike exactly one backoff interval later. Add randomness to every delay.
- **`Promise.all`** **over a large array.** This is the single most common cause of 429s in batch scripts. Wrap each call in a concurrency limiter.
- **Setting** **`maxRetries`** **high on interactive requests.** A user will not wait a minute for a chat reply. Fail fast there and retry generously only in the background.
- **Treating 429 as a bug in your code.** It is a capacity signal. Log it, count it, and use the count to decide whether to lower concurrency or ask your provider for a higher tier.
- **Ignoring the tokens-per-minute limit.** If you are far below your request limit and still seeing 429s, look at the size of your prompts, not the number of them.

## Related reading

- [Rate limits in the Claude docs](https://platform.claude.com/docs/en/api/rate-limits)
- [Message Batches in the Claude docs](https://platform.claude.com/docs/en/build-with-claude/batch-processing)
- [Prompt caching in the Claude docs](https://platform.claude.com/docs/en/build-with-claude/prompt-caching)
- [HTTP 429 Too Many Requests on MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429)
