# Fix HTTP 429 LLM Rate Limits: TPM vs RPM in OpenAI, Claude & Gemini

> Canonical URL: https://stackquota.com/guides/fix-429-rate-limit-tpm-rpm-openai-anthropic-gemini/
> Checked: 2026-12-04 · Published: 2026-12-04

Resolve HTTP 429 rate_limit_exceeded and RESOURCE_EXHAUSTED errors across OpenAI, Anthropic, and Gemini with header-aware token buckets and jitter.

Production `HTTP 429 Too Many Requests` incidents almost never happen because your application sustained 60 full seconds of peak load. They happen at `:00.120` of a cron tick, webhook fan-out, or user search burst when 40 concurrent workers dispatch 12,000-token prompts simultaneously, draining a continuous token bucket before your provider dashboard registers a blip on its 1-minute aggregation chart.

Stopping 429 errors in production comes down to treating `RPM` (Requests Per Minute), `ITPM` (Input Tokens Per Minute), and `OTPM` (Output Tokens Per Minute) as distinct, header-driven state machines rather than wrapping SDK calls in blind `sleep(2000)` loops.

## Why do LLM APIs return HTTP 429 when your dashboard shows spare quota?

**Quick answer:** Providers enforce rate limits using continuous token buckets that replenish incrementally every millisecond and reserve `max_output_tokens` upfront before generation starts. Sending 1/10th of your per-minute quota inside a 100 ms burst (or hitting a `$0` prepaid balance (`insufficient_quota`)) triggers `HTTP 429` even when 60-second usage charts look nearly empty.

When paging into a 429 spike, your first diagnostic step is separating **billing lockouts**, **token-bucket micro-bursts**, and **upstream compute overload** (`529` / transient capacity 429s). All three surface as rate-limit exceptions in generic HTTP wrappers, yet retrying a billing lockout wastes worker CPU while retrying an unjittered burst creates a synchronized retry storm.

Inspect the exact wire payloads and response headers returned by each provider:

```http
HTTP/2 429 Too Many Requests
date: Fri, 04 Dec 2026 00:14:02 GMT
content-type: application/json
retry-after: 2
retry-after-ms: 1840
x-ratelimit-limit-requests: 10000
x-ratelimit-limit-tokens: 2000000
x-ratelimit-remaining-requests: 9942
x-ratelimit-remaining-tokens: 840
x-ratelimit-reset-requests: 348ms
x-ratelimit-reset-tokens: 1.84s

{
  "error": {
    "message": "Rate limit reached for gpt-5 in organization org-9x8a7b on tokens per min (TPM): Limit 2000000, Used 1999160, Requested 14500. Please try again in 1.84s.",
    "type": "tokens",
    "param": null,
    "code": "rate_limit_exceeded"
  }
}
```

Compare that OpenAI `rate_limit_exceeded` response against three frequent lookalikes:

- **OpenAI `code: "insufficient_quota"`**: Returns `HTTP 429` without depleted bucket headers when prepaid credits hit `$0` or your monthly hard spend cap trips. Never retry; trip a billing circuit breaker immediately.
- **Anthropic `rate_limit_error`**: Returns `HTTP 429` with separate `anthropic-ratelimit-input-tokens-remaining` and `anthropic-ratelimit-output-tokens-remaining` headers plus `retry-after`. Draining `OTPM` while `ITPM` stays 90% free happens whenever routes hardcode `max_tokens: 16384` on short JSON calls.
- **Google Gemini `429 RESOURCE_EXHAUSTED`**: Returns gRPC JSON containing `google.rpc.RetryInfo` (`retryDelay: "4s"`) and `QuotaFailure` entries pinpointing `GenerateContentInputTokensPerModelPerMinute` or `RequestsPerDay`.

## How do OpenAI, Anthropic, and Gemini measure TPM, ITPM, and OTPM differently?

**Quick answer:** OpenAI meters a unified `TPM` pool per model family and reserves prompt plus `max_completion_tokens` at admission, Anthropic enforces independent `ITPM` and `OTPM` buckets where cached reads bypass `ITPM`, and Google Gemini layers per-minute `RPM`/`TPM` with daily `RPD` project caps.

Assuming identical token accounting across providers causes subtle admission bugs. On Anthropic Claude Sonnet 5.5 and Opus 5.5, `cache_read_input_tokens` do not count against `ITPM` on standard paid tiers, so a 90% cache hit rate multiplies sustainable input throughput by 10x. Conversely, if a key-ordering bug breaks your prefix hash (see [fixing silent prompt caching misses](/guides/prompt-caching-miss-bugs-openai-anthropic-gemini/)), `ITPM` burn jumps 10x instantly alongside a 10x input cost spike.

| Provider & Models | Quota Dimensions | Primary Headers | Upfront Output Reservation | Cached Reads Count Toward TPM? | Batch Pool |
| :--- | :--- | :--- | :--- | :--- | :--- |
| **OpenAI** (`gpt-5`, `gpt-5-mini`, `gpt-4.1`, `o4-mini`) | `RPM`, `TPM`, Batch `TPD` | `x-ratelimit-remaining-tokens`, `x-ratelimit-reset-tokens`, `retry-after-ms` | `max(input, max_completion_tokens)` reconciled on finish | **Yes** - full prompt counts | Separate 24h pool (50% off) |
| **Anthropic** (`claude-sonnet-5.5`, `opus-5.5`, `haiku-5.5`) | `RPM`, `ITPM`, `OTPM` | `anthropic-ratelimit-input-tokens-remaining`, `...-output-tokens-remaining`, `retry-after` | Full `max_tokens` locked in `OTPM` until stream closes | **No** - `cache_read_input_tokens` bypass `ITPM` | Message Batches (50% off) |
| **Google** (`gemini-3.1-pro`, `2.5-flash`, `2.5-flash-lite`) | `RPM`, `TPM`, `RPD` | `retry-after`, `RetryInfo.retryDelay` | Prompt metered on ingress; output metered rolling | **Yes** - cached tokens count | Batch mode (50% off) |

Watch **upfront output reservation** closely. On a Tier 2 Anthropic workspace with `90,000 OTPM` for `claude-sonnet-5.5`, setting `max_tokens: 16000` on an endpoint averaging 400 output tokens causes the sixth concurrent request (`6 * 16,000 = 96,000` reserved tokens) to fail with `HTTP 429`, even though the five active calls emit only `2,000` tokens total. Right-sizing `max_tokens` to `1,024` lifts instant concurrency from 5 to 87 requests without a tier upgrade, provided schemas stay concise enough to avoid a [structured JSON truncation retry loop](/guides/llm-structured-json-truncation-retry-cost-loop/).

## What does uncontrolled 429 retry amplification actually cost in production?

**Quick answer:** Default SDK retries (`maxRetries: 2`) nested inside BullMQ, SQS, or workflow retries multiply burst traffic by 6x–9x, triggering expensive upward model failovers or stranding edge worker sockets until gateway timeouts discard paid tokens.

Pure 429 rejections do not bill tokens, yet unhandled retry storms inflate monthly invoices through three production failure paths:

1. **Upward model spillover**: When unthrottled background jobs saturate `gpt-5-mini` (`$0.25/1M` input, `$2.00/1M` output) or `gemini-2.5-flash` (`$0.30/1M` input, `$2.50/1M` output), naive routers fail traffic upward to `gpt-5` (`$1.25/$10.00`) or `claude-opus-5.5` (`$5.00/$25.00`) just to reach an idle bucket.
2. **Gateway deadline aborts**: When three SDK retries stall 14 seconds before attempt four starts streaming, a 15-second API gateway timeout severs the stream mid-flight, billing prompt and partial output tokens your caller never receives, while stalled buffers risk [Cloudflare Workers Error 1102 CPU and memory limits](/guides/cloudflare-workers-error-1102-cpu-memory-limit-fix/).
3. **Unbounded reasoning fallback**: Failing a throttled `gpt-4.1` (`$2.00/$8.00`) route onto `o4-mini` (`$1.10/$4.40`) without capping `reasoning_effort` burns thousands of internal reasoning tokens billed at `$4.40/1M` output.

Take a triage pipeline running **30 million calls/month** (`3,000` input + `400` output tokens; `90B` input and `12B` output tokens monthly):

- **Steady baseline on `gpt-5-mini` (80% cached prefix)**: `72,000M * $0.025` (`$1,800`) + `18,000M * $0.25` (`$4,500`) + `12,000M * $2.00` (`$24,000`) = **$30,300/mo**.
- **Naive upward spillover (25% of traffic spills to uncached `claude-sonnet-5.5`)**: `22,500M * $2.00` (`$45,000`) + `3,000M * $10.00` (`$30,000`) = **$75,000/mo** for that 25% slice alone—**2.5x the entire baseline**.
- **Peer-tier cross-provider fallback (`gemini-2.5-flash` at `$0.30/$2.50`)**: That same 25% overflow costs `$6,750` input + `$7,500` output = **$14,250/mo**, saving **$60,750/mo** while isolating quota across Google Cloud.

Simulate your own burst spillover and cache hit ratios in our [LLM API Pricing Calculator](/calculators/llm-api-pricing/).

## How do you implement Header-Aware token buckets with Full-Jitter backoff and Cross-Provider fallback?

**Quick answer:** Initialize provider SDKs with `maxRetries: 0`, gate calls against an in-memory or Redis bucket synced from `x-ratelimit-remaining-*` headers, sleep using server-floored full jitter, and fail over across peer-priced providers whenever reset windows exceed your latency budget.

Disable built-in SDK retries so retry state lives in one place; `new OpenAI({ maxRetries: 2 })` inside a 3-try router fires `9` upstream attempts per request. Read raw response headers on every response and distinguish `insufficient_quota` from retryable `429`/`529` throttling:

```typescript
export interface RateLimitSnapshot {
  remainingRequests: number;
  remainingTokens: number;
  resetAtEpochMs: number;
}

const bucketState = new Map<string, RateLimitSnapshot>();

function parseResetMs(raw: string | null): number {
  if (!raw) return 0;
  if (/^\d+(\.\d+)?$/.test(raw)) return Math.ceil(parseFloat(raw) * 1000);
  let ms = 0;
  for (const [re, mult] of [[/(\d+(?:\.\d+)?)m(?!s)/, 60_000], [/(\d+(?:\.\d+)?)s/, 1_000], [/(\d+(?:\.\d+)?)ms/, 1]] as const) {
    const m = raw.match(re);
    if (m) ms += parseFloat(m[1]) * mult;
  }
  return Math.ceil(ms);
}

export function syncRateLimitHeaders(key: string, h: Headers): void {
  const waitMs = Math.max(
    parseResetMs(h.get("retry-after-ms")) || parseResetMs(h.get("retry-after")),
    parseResetMs(h.get("x-ratelimit-reset-tokens"))
  );
  const remReq = Number(h.get("x-ratelimit-remaining-requests") ?? h.get("anthropic-ratelimit-requests-remaining") ?? 1e9);
  const aIn = h.get("anthropic-ratelimit-input-tokens-remaining");
  const aOut = h.get("anthropic-ratelimit-output-tokens-remaining");
  const remTok = aIn && aOut ? Math.min(Number(aIn), Number(aOut)) : Number(h.get("x-ratelimit-remaining-tokens") ?? 1e9);

  bucketState.set(key, {
    remainingRequests: Number.isFinite(remReq) ? remReq : 1e9,
    remainingTokens: Number.isFinite(remTok) ? remTok : 1e9,
    resetAtEpochMs: Date.now() + waitMs,
  });
}

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

export interface ProviderCall<T> {
  providerKey: string;
  estimatedTokens: number;
  maxWaitMs: number;
  invoke: () => Promise<{ data: T; headers: Headers }>;
}

export async function executeWithAdaptiveFallback<T>(candidates: ProviderCall<T>[]) {
  let attempts = 0;
  for (const c of candidates) {
    const snap = bucketState.get(c.providerKey);
    if (snap && (snap.remainingRequests < 1 || snap.remainingTokens < c.estimatedTokens) && snap.resetAtEpochMs - Date.now() > c.maxWaitMs) {
      continue;
    }
    for (let attempt = 0; attempt < 2; attempt++) {
      attempts++;
      try {
        const res = await c.invoke();
        syncRateLimitHeaders(c.providerKey, res.headers);
        return { data: res.data, providerUsed: c.providerKey, attempts };
      } catch (err: any) {
        if (err?.headers instanceof Headers) syncRateLimitHeaders(c.providerKey, err.headers);
        if ((err?.error?.code ?? err?.code) === "insufficient_quota") break;
        const status = err?.status ?? err?.statusCode;
        if (status === 429 || status === 529) {
          const floorMs = Math.max(0, (bucketState.get(c.providerKey)?.resetAtEpochMs ?? 0) - Date.now());
          if (floorMs > c.maxWaitMs || attempt === 1) break;
          const jitter = Math.floor(Math.random() * Math.min(c.maxWaitMs, 400 * 2 ** attempt));
          await sleep(Math.min(c.maxWaitMs, Math.max(floorMs || 1_000, jitter)));
          continue;
        }
        throw err;
      }
    }
  }
  throw new Error(`All LLM providers exhausted after ${attempts} attempts.`);
}
```

Three design decisions keep this wrapper stable under burst load:

1. **Proactive pre-admission skipping**: Once Worker A records `x-ratelimit-remaining-tokens: 840` and `x-ratelimit-reset-tokens: 4.2s`, sibling calls see `resetAtEpochMs - now > maxWaitBudgetMs` and route straight to `gemini-2.5-flash` in `0 ms` without wasting an HTTP round-trip.
2. **Server-floor full jitter**: Standard full jitter samples `random(0, base * 2^attempt)`. When Anthropic sends `Retry-After: 2`, waking at `310 ms` guarantees a repeat `429`. Taking `Math.max(floorMs, jitter)` honors the server refill clock while desynchronizing workers above that floor.
3. **Peer-tier pairing**: Match unit economics and context ceilings, pair `gpt-5` (`$1.25/$10.00`) with `claude-sonnet-5.5` (`$2.00/$10.00`) or `gemini-3.1-pro` (`$2.00/$12.00` `<=200K`), and `gpt-5-mini` (`$0.25/$2.00`) with `gemini-2.5-flash` (`$0.30/$2.50`) or `claude-haiku-5.5` (`$0.10/$0.50` `<=100K`).

## When should you offload traffic to batch APIs instead of scaling synchronous tiers?

**Quick answer:** Move every workload without a human waiting on a synchronous HTTP response (nightly evaluations, catalog enrichment, embeddings backfill, and bulk classification) onto Batch APIs to bypass real-time `RPM`/`TPM` buckets and cut token bills by 50%.

Running cron backfills through the same synchronous API key serving live users is the top cause of daytime `HTTP 429` incidents. Every major LLM vendor isolates async batch queues from synchronous rate limits at a flat **50% Batch discount**:

- **OpenAI Batch API**: Cuts `gpt-5` to **`$0.625` input / `$5.00` output** per 1M tokens and `gpt-4.1` to **`$1.00` input / `$4.00` output** within a 24-hour window.
- **Anthropic Message Batches**: Cuts `claude-sonnet-5.5` to **`$1.00` input / `$5.00` output** and `claude-opus-5.5` to **`$2.50` input / `$12.50` output** without touching live `ITPM` or `OTPM`.
- **Google Gemini Batch Mode**: Cuts `gemini-3.1-pro` (`<=200K`) to **`$1.00` input / `$6.00` output** and `gemini-2.5-flash-lite` to **`$0.05` input / `$0.20` output**.

For sub-minute background jobs that cannot wait for Batch turnaround, isolate them onto a dedicated Project API key with a console RPM/TPM cap and size queue consumer concurrency directly from your bucket ceiling:

```text
MaxSafeWorkers = floor((TargetBucketTPM * AvgLatencySeconds) / (60 * (AvgInputTokens + MaxOutputTokens)))
```

At `1,000,000 TPM`, `2.4s` average latency, and `4,000` reserved tokens per call, capping concurrency at `floor((1,000,000 * 2.4) / (60 * 4,000)) = 10` workers eliminates steady-state 429s at >92% bucket utilization.

## How do you verify Rate-Limit headers and fallback telemetry before shipping?

**Quick answer:** Run a raw `curl -i` probe against each configured API key to confirm your live tier headers match your limiter math, inject deterministic `429` responses in staging to prove SDK double-retries are disabled, and alert on `rate_limit_fallback_total` before unit costs drift.

Never trust tier tables in documentation alone, workspace limits depend on historical spend, organization verification, and project-level overrides. Run this non-destructive `16-token` header probe in your deployment pipeline or terminal to inspect your exact live quota headers:

```bash
curl -i -sS https://api.openai.com/v1/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-5-mini",
    "max_completion_tokens": 16,
    "messages": [{"role": "user", "content": "Reply OK"}]
  }' | grep -iE "^(http/|retry-after|x-ratelimit-)"
```

Before closing your rate-limit incident review, verify all five items on this checklist:

1. **Zero hidden SDK retry multiplication**: Confirm every OpenAI, Anthropic, and Google GenAI client initializes with `maxRetries: 0` when wrapped by your adaptive router or message queue.
2. **Tight `max_output_tokens` budgets**: Audit every route and replace copy-pasted `8192` or `16384` output ceilings with `2x` your observed P99 completion length so Anthropic `OTPM` and OpenAI pre-flight reservations stop blocking healthy concurrency.
3. **Distinct handling for `insufficient_quota`**: Test a mock `429` carrying `"code": "insufficient_quota"` and verify your service fails over immediately and fires a critical billing page rather than sleeping in a backoff loop.
4. **Header-driven telemetry tags**: Emit OpenTelemetry metrics `llm.ratelimit.remaining_tokens_ratio` (`remaining / limit`) and `llm.fallback.triggered_total{from,to,reason}` so you spot buckets crossing 80% saturation days before users hit hard 429s.
5. **Batch separation**: Confirm cron jobs, eval suites, and bulk re-indexing pipelines either target async Batch endpoints at 50% cost or use a dedicated project key capped below 30% of organization quota.
