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.


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

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.


_10
const client = new Anthropic({ maxRetries: 5 });
_10
_10
// Or override for one call
_10
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.


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

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.


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

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.


_10
import pLimit from 'p-limit';
_10
_10
const limit = pLimit(4); // at most 4 requests in flight
_10
_10
const summaries = await Promise.all(
_10
documents.map((doc) => limit(() => summarise(doc))),
_10
);

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.


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

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.
#

quick question

Was this resource helpful?