← All articles

Anthropic API 429 Rate Limit: Causes & Code Fix

Anthropic API 429 rate_limit_error: fix RPM, ITPM and OTPM limits with retry-after, jittered backoff in Python & TypeScript, plus a spend-cap guard.

UniRoute ·

One-sentence answer: An Anthropic API 429 (rate_limit_error) means your organization or session hit one of five quota limits—Requests Per Minute (RPM), Input Tokens Per Minute (ITPM), Output Tokens Per Minute (OTPM), a short-window Ramp / Acceleration Limit (error.details.error_code: "ramp_limit_exceeded"), or your monthly tier Spend Limit (enforced_spend_limit_reached, which omits retry-after and never succeeds on retry)—unlike HTTP 529 (overloaded_error), which is a global Anthropic capacity spike.

30-Second Anthropic 429 Diagnosis Table — match your status code, retry-after header, and error message before changing retry code:

Limit / Error CategoryHTTP Status & error.typeretry-after HeaderRoot CauseImmediate Fix
1. Requests Per Minute (RPM)429 · rate_limit_errorPresent (seconds)Excess concurrent calls or tight agent loops in a 60s bucket.Wait retry-after seconds, cap concurrency with a semaphore, or use Message Batches API.
2. Input Tokens Per Minute (ITPM)429 · rate_limit_errorPresent (...-input-tokens-remaining: 0)Large uncached system prompts, repo context, or history re-sent every turn.Enable Prompt Caching (cache_read_input_tokens do not count toward ITPM); run /compact in Claude Code.
3. Output Tokens Per Minute (OTPM)429 · rate_limit_errorPresent (...-output-tokens-remaining: 0)High actual output volume across concurrent long-form responses or extended thinking bursts.Tighten prompt verbosity / structured schemas, stagger long-output concurrency, and honor retry-after.
4. Monthly Tier Spend Cap (enforced_spend_limit_reached)429 · rate_limit_error (custom caps may return 400)Absent (None)Reached monthly USD spend ceiling for your Usage Tier.Stop retrying (retries fail 100%). Raise cap in Console or fail over via UniRoute.
5. Ramp Limit (ramp_limit_exceeded) / Claude Code OAuth Cap429 · rate_limit_error (error.details.error_code: "ramp_limit_exceeded" or Rate limit reached)Present (cooldown)Token usage spiked sharply even while under ITPM/OTPM ceilings, or hit the 5-hour Pro/Max OAuth window.For ramp_limit_exceeded, hold traffic steady at a successful baseline and step up at most once per minute (unchanged-load retries keep failing); in Claude Code run /status and switch from OAuth /login to API key (ANTHROPIC_AUTH_TOKEN).
6. Global Server Overload (529 — Not a 429)529 · overloaded_error ("Overloaded")Usually absentShared model cluster at capacity across all users (no quota consumed).Switch models (/model), or see Claude 529 Overloaded guide.

Anthropic API 429 vs 529 — 30-second triage flowchart showing RPM, ITPM, OTPM, and retry-after routing

Jump to section: Rate Limits & Reset Times · Headers Reference · Python Retry Code · TypeScript Retry Code · 4 Ways to Cut 429s · Multi-Channel Failover · FAQ


How Anthropic Enforces Rate Limits (RPM, ITPM, OTPM) & Reset Times

Every POST /v1/messages call checks three independent buckets (RPM, ITPM, OTPM) scoped per organization and model class—extra sk-ant-... API keys in the same workspace share the same quota. If any bucket hits 0, the API returns an anthropic api 429 rate limit (rate_limit_error) response even if the other two buckets have spare capacity.

1. How OTPM Counts Output Tokens (and Why max_tokens Is Not Upfront-Reserved)

Anthropic’s OTPM bucket meters actual output tokens produced—including thinking/reasoning tokens when extended thinking is enabled—rather than reserving your max_tokens parameter upfront. Setting a higher max_tokens ceiling does not by itself consume OTPM quota, so blindly slashing max_tokens risks truncating valid JSON or diffs without solving the root cause.

What does exhaust OTPM quickly is concurrent long-form generation: if your limit is 16,000 OTPM and 4 parallel workers each generate 4,500 output + reasoning tokens within a minute (18,000 actual tokens), the bucket drains to 0 and subsequent calls hit 429.

2. When Does the Claude API Rate Limit Reset?

When diagnosing a Claude rate limit reset, recovery depends on which limit triggered:

  • Per-minute API buckets (RPM, ITPM, OTPM) refill continuously: Anthropic uses a continuous token bucket, not a fixed :00 clock reset. A 60,000 ITPM bucket refills at 1,000 tokens/second (limit / 60).
  • Two exact reset timers in HTTP headers:
    1. retry-after (integer seconds): Wait seconds until enough quota refills for your next single request.
    2. anthropic-ratelimit-*-reset (RFC 3339 UTC timestamp, e.g., 2026-11-25T09:15:12Z): Exact UTC time when that bucket refills to 100% capacity (limit).
  • Monthly spend cap (enforced_spend_limit_reached): Omits retry-after. Resets at 00:00 UTC on day 1 of the next month (or when raised in Console).
  • Claude Code OAuth subscription (Rate limit reached): Claude Pro/Max logins enforce a 5-hour rolling session window (plus weekly caps). Run /status in Claude Code for your reset countdown, or compare OAuth vs API billing in CLI vs API Pricing.

3. How Anthropic Usage Tiers Work Today (Start, Build & Scale)

Anthropic consolidated its legacy numbered tiers into Start, Build, and Scale plans in the Claude Console (replacing the older fixed Tier 1–4 deposit-and-calendar-wait ladder):

Console TierTarget WorkloadHow to Raise LimitsCommon Production Bottleneck
StartInitial integration & light testingUpgrade / add billing in Claude ConsoleLow starter ITPM/OTPM; multi-turn coding agents hit 429 quickly.
BuildGrowing production apps & agent workflowsRequest a tier increase directly in Console (Limits page)Parallel CI jobs, uncached repo context, or concurrent long outputs saturate ITPM/OTPM.
ScaleHigh-throughput & custom enterprise workloadsRequest custom rate limits via Anthropic Console / salesBurst acceleration limits or single-organization monthly spend ceilings (enforced_spend_limit_reached).

Even without fixed calendar wait tables, requesting higher limits in Console still requires review/approval and may not unblock an active production spike immediately.


Anthropic Rate-Limit Response Headers Reference

On HTTP 429 Too Many Requests, Anthropic returns a rate_limit_error JSON payload and rate-limit headers:

{
  "type": "error",
  "error": {
    "type": "rate_limit_error",
    "message": "This request would exceed your organization's rate limit of 40,000 input tokens per minute."
  },
  "request_id": "req_018X9zExampleRateLimit429"
}

Inspect these 11 official headers on 200 OK and 429 responses:

Response HeaderFormatMeaning
retry-afterInteger (seconds)Wait seconds before retrying. Honor first. Absent on enforced_spend_limit_reached.
anthropic-ratelimit-requests-limitIntegerMax requests per minute (RPM) for the model class.
anthropic-ratelimit-requests-remainingIntegerRemaining requests in RPM bucket (0 when throttled).
anthropic-ratelimit-requests-resetRFC 3339 (ISO 8601)UTC timestamp when RPM bucket refills to 100% of limit.
anthropic-ratelimit-input-tokens-limitIntegerMax uncached input tokens per minute (ITPM).
anthropic-ratelimit-input-tokens-remainingIntegerRemaining ITPM capacity (0 when throttled).
anthropic-ratelimit-input-tokens-resetRFC 3339 (ISO 8601)UTC timestamp when ITPM bucket refills to 100% of limit.
anthropic-ratelimit-output-tokens-limitIntegerMax output tokens per minute (OTPM).
anthropic-ratelimit-output-tokens-remainingIntegerRemaining OTPM capacity based on actual output tokens produced.
anthropic-ratelimit-output-tokens-resetRFC 3339 (ISO 8601)UTC timestamp when OTPM bucket refills to 100% of limit.
request-idString (req_...)Unique request ID for logs and support tickets.

Production Retry Code (Python & TypeScript: retry-after + Jitter + Spend-Cap Guard)

Official anthropic (Python) and @anthropic-ai/sdk (TypeScript) clients retry rate limits twice by default (max_retries=2 / maxRetries: 2). In multi-worker queues, default retries break for three reasons:

  1. Nested retry amplification: Wrapping an SDK client with max_retries=2 inside a 5-attempt loop fires 15 requests (3 × 5). Always set max_retries=0 on the SDK client.
  2. Thundering herd after retry-after: If 10 workers receive retry-after: 8 and sleep 8.000s, all 10 slam the API at once. Add random positive jitter (+0.25s–+1.5s).
  3. Infinite spend-cap loops: Monthly spend caps (enforced_spend_limit_reached, no retry-after) never recover via retry. Circuit-break immediately.

Python: Production Retry Wrapper with retry-after & Jitter

To handle an anthropic api 429 rate limit in Python, set max_retries=0 on AsyncAnthropic, honor retry-after with positive jitter, and circuit-break on monthly spend caps:

import os, random, asyncio
from typing import Any
import anthropic
from anthropic import AsyncAnthropic

client = AsyncAnthropic(
    api_key=os.environ["ANTHROPIC_API_KEY"],
    base_url=os.environ.get("ANTHROPIC_BASE_URL", "https://api.anthropic.com"),
    max_retries=0,  # Disable built-in retries so our wrapper owns backoff
)

def is_spend_limit(err: anthropic.RateLimitError) -> bool:
    headers = err.response.headers if err.response else {}
    body = str(err.body or err.message).lower()
    if "enforced_spend_limit_reached" in body or "spend limit" in body:
        return True
    return headers.get("retry-after") is None and ("monthly" in body or "credit" in body)

def wait_seconds(err: anthropic.APIStatusError, attempt: int, base: float = 1.0, cap: float = 60.0) -> float:
    headers = err.response.headers if err.response else {}
    ra = headers.get("retry-after")
    if ra is not None:
        try:
            # Always wait at least retry-after (never cap below the server-directed wait)
            return max(0.0, float(ra)) + random.uniform(0.25, 1.5)
        except ValueError:
            pass
    return random.uniform(base, max(base, min(cap, base * (2 ** attempt))))

async def create_message_with_backoff(
    *,
    model: str = "claude-sonnet-5-5",
    max_tokens: int = 2048,
    messages: list[dict[str, Any]],
    system: Any = anthropic.NOT_GIVEN,
    max_attempts: int = 6,
) -> anthropic.types.Message:
    for attempt in range(max_attempts):
        try:
            return await client.messages.create(
                model=model, max_tokens=max_tokens, system=system, messages=messages
            )
        except anthropic.RateLimitError as err:
            if is_spend_limit(err):
                raise RuntimeError(f"Monthly spend cap reached (req_id={err.request_id}).") from err
            if attempt + 1 >= max_attempts:
                raise
            await asyncio.sleep(wait_seconds(err, attempt))
        except anthropic.APIStatusError as err:
            if (err.status_code < 500 and err.status_code != 429) or attempt + 1 >= max_attempts:
                raise
            await asyncio.sleep(wait_seconds(err, attempt))
    raise RuntimeError("Exhausted max_attempts")

TypeScript: Production Retry Wrapper with retry-after & Jitter

For Node.js and TypeScript services using @anthropic-ai/sdk, apply the same single-owner retry controller (maxRetries: 0):

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

const client = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
  baseURL: process.env.ANTHROPIC_BASE_URL ?? 'https://api.anthropic.com',
  maxRetries: 0,
});

function isSpendLimit(err: InstanceType<typeof Anthropic.APIError>): boolean {
  const retryAfter = err.headers?.['retry-after'];
  const msg = JSON.stringify(err.error ?? err.message ?? '').toLowerCase();
  if (msg.includes('enforced_spend_limit_reached') || msg.includes('spend limit')) return true;
  return !retryAfter && (msg.includes('monthly') || msg.includes('credit'));
}

function waitMs(err: InstanceType<typeof Anthropic.APIError>, attempt: number, base = 1000, cap = 60_000): number {
  const ra = err.headers?.['retry-after'];
  if (ra) {
    const parsed = Number.parseFloat(ra);
    if (Number.isFinite(parsed) && parsed >= 0) {
      // Never cap below the server-directed retry-after duration
      return parsed * 1000 + 250 + Math.random() * 1250;
    }
  }
  return base + Math.random() * Math.max(0, Math.min(cap, base * 2 ** attempt) - base);
}

export async function createMessageWithBackoff(
  params: Anthropic.MessageCreateParamsNonStreaming,
  maxAttempts = 6
): Promise<Anthropic.Message> {
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
    try {
      return await client.messages.create(params);
    } catch (error) {
      if (!(error instanceof Anthropic.APIError)) throw error;
      if (error.status === 429 && isSpendLimit(error)) {
        throw new Error(`Monthly spend cap reached (req_id=${error.request_id ?? 'n/a'}).`);
      }
      if ((error.status && error.status < 500 && error.status !== 429) || attempt + 1 >= maxAttempts) {
        throw error;
      }
      await new Promise((r) => setTimeout(r, waitMs(error, attempt)));
    }
  }
  throw new Error('Exhausted maxAttempts');
}

Single-account Console quota bottlenecking production? Set base_url="https://api.uniroute.app" (or ANTHROPIC_BASE_URL=https://api.uniroute.app) with a UniRoute API key for pre-stream multi-channel failover without changing your retry wrapper—see gateway setup below.


4 Ways to Cut 429 Errors Without Waiting for a Tier Upgrade

These four engineering levers prevent your token bucket from hitting zero.

1. Enable Prompt Caching (cache_read_input_tokens Are Excluded from Standard ITPM)

On Claude models (Claude Sonnet 5.5, Claude Opus 5.5, and Claude Fable 5.2), tokens read from the prompt cache (usage.cache_read_input_tokens) do not count against your standard ITPM rate limit.

If your agent sends a 40K-token system prompt + repo map every turn, 2 uncached calls consume 80,000 ITPM (429 on Start/Build starter quotas). With cache_control: {"type": "ephemeral"}, Request #1 caches the 40K prefix and subsequent calls only deduct the new ~500-token user message from ITPM:

response = await client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=2048,
    system=[
        {
            "type": "text",
            "text": "<LARGE_REPO_ARCHITECTURE_AND_CODING_RULES_40K_TOKENS>",
            "cache_control": {"type": "ephemeral"},
        }
    ],
    messages=[{"role": "user", "content": "Refactor the retry handler in src/api.py"}],
)

2. Trim Output Verbosity and Stagger Long-Output Concurrency (OTPM)

Because Anthropic counts actual output tokens (including extended-thinking tokens) against OTPM as they are produced—and max_tokens does not reserve quota upfront—control real output volume rather than artificially choking max_tokens:

  • Enforce concise formats: Use structured JSON schemas or terse diff/patch instructions so the model does not burn 3,000 prose tokens on a 300-token answer.
  • Scope extended thinking: Enable high thinking budgets only on hard synthesis or debugging steps, not routine classification or tool-routing turns.
  • Cap parallel long-form workers: Put a concurrency semaphore in front of streaming jobs that routinely emit 4K–16K tokens so they do not empty your 1-minute OTPM bucket together.

3. Offload Non-Interactive Workloads to the Message Batches API

Send background jobs (PR audits, evals, backfills) to POST /v1/messages/batches (client.messages.batches.create). Batch jobs execute from a separate asynchronous pool (zero impact on real-time RPM, ITPM, or OTPM) at 50% of list price.

4. Fix claude code rate limit reached (429) in Claude Code CLI

If you hit API Error: Rate limit reached or 429 delays in Claude Code:

  1. Run /compact before the 5-minute cache TTL expires: Pausing >5 minutes expires the ephemeral cache, re-sending your 100K+ history as uncached ITPM on the next turn.
  2. Check /status for OAuth vs. API Key limits: Per anthropics/claude-code Issue #31021, Claude Pro/Max /login enforces a 5-hour OAuth rolling window. Switch to an API key (ANTHROPIC_AUTH_TOKEN; see Claude Code API Key guide and CLI vs API Pricing) for pay-as-you-go billing.
  3. Use CLAUDE_CODE_RETRY_WATCHDOG=1 for claude -p: Per our Claude 529 Overloaded guide, export CLAUDE_CODE_RETRY_WATCHDOG=1 waits out transient 429/529 windows while aborting on spend-limit 429 errors.
  4. Distinguish upfront 429s from mid-stream stalls: For stalls after HTTP 200 OK, see Claude Stream Idle Timeout and Claude Code API Error 500.

Route Through a Multi-Channel Gateway (UniRoute Failover)

Disclosure: UniRoute is our unified AI API gateway. Routing through UniRoute provides pre-stream multi-channel failover across capacity pools, though it cannot switch channels mid-response after an HTTP 200 stream has started.

When your team outgrows a single Console Start/Build bucket or hits a monthly spend cap mid-sprint, pointing the Anthropic SDK or Claude Code to UniRoute (https://api.uniroute.app) removes single-account quota lock-in while keeping the exact Messages API format and model IDs (claude-sonnet-5-5, claude-opus-5-5, claude-fable-5-2, claude-haiku-5-5):

  1. No single-org tier review delay: Call Claude models immediately from one USD balance without waiting on a manual Console limit increase during an active incident.
  2. Pre-stream failover: If one channel hits rate control or 529 before streaming begins, UniRoute automatically fails over to a backup channel (channel management docs).
  3. Transparent pricing: Pay as you go. Prices are listed per model on the model page and compared with the provider's published list price; a standard channel matches list price and a discounted channel is available for many models. Compare rates on UniRoute Model Pricing.

Option A: Switch Your Python or TypeScript SDK (ANTHROPIC_BASE_URL)

Create a UniRoute API key (Console → API Keys), then point base_url / baseURL to https://api.uniroute.app:

import os
from anthropic import Anthropic

client = Anthropic(
    api_key=os.environ["UNIROUTE_API_KEY"],
    base_url="https://api.uniroute.app",
)

Option B: Connect Claude Code CLI in 60 Seconds

Run the setup utility (Node.js 22+; backs up ~/.claude/settings.json):

npx --yes --package=https://uniroute.app/community/uniroute-setup-0.1.2.tgz uniroute-setup configure claude --model claude-sonnet-5-5

Or set ANTHROPIC_BASE_URL and ANTHROPIC_AUTH_TOKEN in ~/.claude/settings.json (Claude Code CLI setup guide · Claude Code Relay Guide):

{
  "env": {
    "ANTHROPIC_BASE_URL": "https://api.uniroute.app",
    "ANTHROPIC_AUTH_TOKEN": "YOUR_UNIROUTE_API_KEY"
  },
  "model": "claude-sonnet-5-5"
}

When setting a retry budget, use the Claude Fable 5.2 API pricing and monthly calculator to estimate how request volume, cache hits and thinking tokens affect cost.

Frequently Asked Questions (FAQ)

1. Why am I getting an Anthropic API 429 rate_limit_error when my usage is well below my monthly limit?

Anthropic enforces three independent per-minute token buckets (RPM, ITPM, OTPM) plus short-window acceleration limits, separate from your monthly spend cap. A single uncached 50K-token prompt or a burst of concurrent long-output responses can exhaust your 1-minute bucket even when your monthly bill is under $1.

2. When does the Claude API rate limit reset, and how do I increase it?

Per-minute buckets (RPM, ITPM, OTPM) refill continuously (limit / 60 per second); check retry-after for the wait seconds until your next call, and anthropic-ratelimit-*-reset for the UTC timestamp when the bucket refills to 100%. Anthropic now organizes Console accounts into Start, Build, and Scale tiers—you can request a tier or limit increase directly in the Claude Console Limits page. To expand effective headroom immediately, enable Prompt Caching, trim verbose outputs and cap concurrent long generations, offload background runs to the Message Batches API, or route through UniRoute (https://api.uniroute.app).

3. What is the difference between Anthropic Error 429 (rate_limit_error) and Error 529 (overloaded_error)?

HTTP 429 (rate_limit_error) is an organization or session quota limit (RPM, ITPM, OTPM, burst limit, or monthly spend cap). HTTP 529 (overloaded_error) is a global server-side capacity spike across all users on that model; it does not consume quota and can be mitigated via /model or pre-stream failover (Claude 529 Overloaded guide).

4. Why does my Anthropic 429 error have no retry-after header and keep failing on retry?

When an HTTP 429 omits retry-after and cites "enforced_spend_limit_reached", your organization hit its monthly USD spending ceiling rather than a 1-minute bucket (custom spend caps may also return HTTP 400). Stop retrying immediately—retries fail until your billing cycle resets, you raise your cap in Console, or you fail over to another funded endpoint.