Rate Limits & Errors

Handle 429 rate limits and 5xx errors gracefully, and let the SDK retry for you.

In production, requests sometimes fail: you can hit a rate limit or the service can be briefly overloaded. Robust apps handle this without crashing.

Common error codes

CodeMeaningRetry?
400Bad request (fix your input)No
401Invalid or missing API keyNo
429Rate limited (too many requests)Yes
500 / 529Server error / overloadedYes

Let the SDK help

The official SDKs automatically retry 429 and 5xx errors with backoff. You catch the typed error classes for anything you need to handle yourself.

Example

Example Β· javascript
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();

try {
  const res = await client.messages.create({
    model: "claude-opus-4-8", max_tokens: 512,
    messages: [{ role: "user", content: "Hi" }],
  });
} catch (err) {
  if (err instanceof Anthropic.RateLimitError) {
    console.warn("Rate limited β€” the SDK already retried; back off further.");
  } else if (err instanceof Anthropic.BadRequestError) {
    console.error("Fix the request:", err.message);
  } else {
    console.error("Unexpected error:", err);
  }
}

When to use it

  • Catch 429 errors from the Anthropic API and queue retries with exponential backoff for your background job.
  • Display a 'Claude is busy, please wait' message when a 529 overload response arrives instead of showing an error.
  • Use the SDK's built-in automatic retry to handle transient 5xx errors without writing custom retry logic.

More examples

SDK auto-retry on 429 and 5xx

Shows the maxRetries option that activates the SDK's built-in exponential-backoff retry logic.

Example Β· javascript
// The SDK retries automatically with exponential backoff
const client = new Anthropic({
  maxRetries: 3, // default is 2
});

// This request will retry up to 3 times on 429 or 503
const msg = await client.messages.create({
  model: "claude-haiku-4-5",
  max_tokens: 128,
  messages: [{ role: "user", content: "Hello" }],
});

Catch and handle a rate-limit error

Catches the typed RateLimitError class so you can show a user-friendly message and read the retry-after header.

Example Β· javascript
import { RateLimitError, APIError } from "@anthropic-ai/sdk";

try {
  const msg = await client.messages.create({ /* ... */ });
} catch (err) {
  if (err instanceof RateLimitError) {
    console.warn("Rate limited β€” retry after:", err.headers["retry-after"]);
    return { error: "Service busy. Please try again in a moment." };
  }
  if (err instanceof APIError) {
    console.error(`API error ${err.status}:`, err.message);
  }
  throw err;
}

Exponential backoff for batch jobs

A manual backoff helper for batch scripts where the SDK's built-in retry is insufficient.

Example Β· javascript
async function callWithBackoff(fn, retries = 4) {
  for (let i = 0; i < retries; i++) {
    try {
      return await fn();
    } catch (err) {
      if (err.status === 429 && i < retries - 1) {
        const delay = Math.pow(2, i) * 1000; // 1s, 2s, 4s, 8s
        await new Promise(r => setTimeout(r, delay));
      } else throw err;
    }
  }
}

Discussion

  • Be the first to comment on this lesson.