翻篇收录说明
翻篇网页快照

LLM API Rate Limits: How to Fix OpenAI and Claude 429 Errors

https://openrouter.ai/blog/tutorials/llm-api-rate-limits/

最近抓取:2026-12-03 11:23:03(北京时间)

最近内容变化:2026-11-30 08:57:01(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

A 429 Too Many Requests error means you sent more requests or tokens than your limit allows in the current time window. OpenAI, Anthropic and OpenRouter

正文摘录

LLM API Rate Limits: How to Fix OpenAI and Claude 429 ErrorsOpenRouter ·11/11/2026Tl;drTl;drWhat does a 429 rate limit error look like?Why do rate limits trigger at different request counts?Step 1: Read whose limit you hitStep 2: Retry at the reset time the error gives youStep 3: Send overflow to a fallback modelStep 4: Let another provider serve the same modelHow do you avoid hitting rate limits at all?Frequently asked questionsNext stepsA 429 Too Many Requests error means you sent more requests or tokens than your limit allows in the current time window. OpenAI, Anthropic and OpenRouter all return it, and it usually shows up the first time an app runs under real load or a batch job fans out across several workers. Most people reach for a retry, and with default settings that often isn’t enough. When we ran a 60-prompt batch through the OpenAI Python SDK against a per-minute limit, 23 requests still failed after the SDK’s retries. The window reset 4 to 8 seconds after the SDK gave up on each one. This guide starts from a real 429, reads its headers, and fixes it three ways: retry at the reset time the error gives you, send overflow to a fallback model, and let another provider serve the same model. We ran every example against the OpenRouter API, and the output under each code block is what we got. Tl;dr A 429 means you hit a limit in the current window. On OpenRouter, error.metadata.limit_source tells you whose limit it was. With default settings, the OpenAI Python SDK retried each 429 twice and gave up within about 2 seconds. Against a per-minute limit, 23 of 60 requests in our batch still failed. A retry that waits for Retry-After or X-RateLimit-Reset finished all 60 in every run, in 89 to 92 seconds in Python and 106 to 218 seconds in TypeScript. A models fallback finished all 60 in 13 seconds, for $0.000066, with no waiting. Pinned to one provider with failover off, up to 32 of 150 requests failed per run. With failover on, all 150 succeeded in every run. What does a 429 rate limit error look like? We sent 40 requests at once to poolside/laguna-s-2.1:free, a free model with a limit of 20 requests per minute. Thirty-eight succeeded, and two came back as 429 from the provider serving the model: 200: 38 429: 2 other: 0 429 limit_source: {'upstream_provider_shared_pool': 2} A 429 from our own free-tier limit carries a different limit_source. Here’s one from a separate run: { "message": "Rate limit exceeded: free-models-per-min. ", "code": 429, "metadata": { "headers": { "X-RateLimit-Limit": "20", "X-RateLimit-Remaining": "0", "X-RateLimit-Reset": "1792448640000" }, "limit_source": "openrouter_free_tier_per_minute", "remedy_hint": "Slow down requests to free models, or retry after the per-minute window resets.", "provider_name": null } } The headers carry the numbers you need. X-RateLimit-Limit is the cap, X-RateLimit-Remaining is what’s left, and X-RateLimit-Reset is the earliest time a retry can succeed, as a Unix timestamp in milliseconds. The body adds limit_source, which says whose limit you hit, and a remedy_hint written for people reading logs. Branch on limit_source in your code, not on the hint text. OpenAI and Anthropic send the same information under different names. OpenAI’s x-ratelimit-reset-requests is a duration such as 1s, and both providers can send retry-after as a number of seconds. Why do rate limits trigger at different request counts? Thirty-eight of 40 requests got through a limit of 20. The limiter can accept requests that arrive at the same moment before the count catches up, and most limiters don’t reset cleanly at the top of each minute. Anthropic uses a token bucket that refills continuously. OpenAI can return a 429 with the code slow_down when your traffic ramps up too fast, even while you’re under your per-minute limits. To see how our free-model limit counts, we sent 161 more requests in different patterns. Here are three of them: TestSucceeded in that minuteSequential, after two idle minutes30Sequential, the minute right after3030 concurrent29 Two things came out of it. More than 20 requests succeeded in every minute we tested, so treat 20 as the point where 429s can start, not an exact count. When we hit it on poolside/laguna-s-2.1:free with 58 seconds left in the window, five requests to minimax/minimax-m3.1-flash:free went through right away, while Laguna stayed blocked. That doesn’t make the cap per model, though. OpenRouter applies one per-minute limiter to all free models on an account, so a request to a different free model can get the same 429. Step 1: Read whose limit you hit Waiting fixes a 429 only when the limit resets on a schedule, so check limit_source before you pick a fix: limit_sourceStatusWhose limitWhat fixes itopenrouter_free_tier_per_minute429Our free-model capWait for X-RateLimit-Reset (Step 2), or fall back to a paid model (Step 3)upstream_provider_shared_pool429The provider serving the modelAnother provider (Step 4) or a fallback model (Step 3)openrouter_in_flight_budget402Your in-flight spending budgetWait for Retry-After and retryopenrouter_key_limit, openrouter_credits402Your key’s credit limit or your balanceRaise the key’s limit or add credits An upstream 429 means the provider serving the model is out of capacity. Providers don’t say when that capacity will free up, so these errors carried no reset header in our runs. The free variant of Gemma 4 31B returned this: google/gemma-4-31b-it:free is temporarily rate-limited upstream. Please retry shortly, or add your own key to accumulate your rate limits. The same request with the paid variant as a fallback used a different provider’s capacity and succeeded at DeepInfra for $0.0000037. Some errors that look like rate limits are about money. OpenAI and Anthropic both return a 429 when you reach a monthly spend cap, and retrying won’t fix it until the cap resets. On OpenRouter, credit problems come back as 402 instead. Step 2: Retry at the reset time the error gives you The OpenAI and Anthropic Python SDKs retry a 429 twice by default, with a short backoff that starts at 0.5 seconds and never waits more than 8. They follow a Retry-After header when the server sends one. Our free-tier 429 sends X-RateLimit-Reset instead, which the SDKs don’t read, so both retries landed in the same full minute. Here’s a 60-prompt batch, 10 at a time, through the OpenAI SDK (openai 3.26.1) with default settings: openai 3.26.1 | max_retries default: 2 finished in 12s (HTTP requests sent: 112) succeeded: 37 RateLimitError after retries: 23 slowest failure gave up after 2.3s message: Rate limit exceeded: free-models-per-min. | limit_source: openrouter_free_tier_per_minute limit_source=openrouter_free_tier_per_minute x-ratelimit-reset: 1792444980000 retry-after: None window reset 8s after the SDK gave up limit_source=openrouter_free_tier_per_minute x-ratelimit-reset: 1792444980000 retry-after: None window reset 7s after the SDK gave up ... limit_source=openrouter_free_tier_per_minute x-ratelimit-reset: 1792444980000 retry-after: None window reset 4s after the SDK gave up The SDK sent 112 HTTP requests for 60 prompts, and 23 still failed. Raising max_retries would eventually get through, but only by sending a request into a full window every 8 seconds, and OpenAI’s docs note that failed requests still count toward your per-minute limit. A better retry waits until the time the server gives you. To run all 60 prompts, use an account with at least 60 free-model requests left for the day, because accounts that haven’t bought 10 credits get 50 a day: import email.utils import os import random import time from concurrent.futures import ThreadPoolExecutor import requests URL = "https://openrouter.ai/api/v1/chat/completions" HEADERS = {"Authorization": f"Bearer {os.environ['OPENROUTER_API_KEY']}"} def retry_delay(headers, attempt): """Seconds to wait after a 429: Retry-After, then X-RateLimit-Reset, then backoff.""" retry_after = headers.get("Retry-After") if retry_after: if retry_after.replace(".", "", 1).isdigit(): return float(retry_after) when = email.utils.parsedate_to_datetime(retry_after).timestamp() return max(0.0, when - time.time()) reset = headers.get("X-RateLimit-Reset") # Unix time in milliseconds if reset: # Spread clients over a few seconds after the reset, so they don't all retry at once. return max(0.0, int(reset) / 1000 - time.time()) + random.uniform(1, 5) return min(2 ** attempt, 60) * random.uniform(0.5, 1) # exponential backoff with jitter def chat(body, max_attempts=6): for attempt in range(max_attempts): r = requests.post(URL, headers=HEADERS, json=body, timeout=120) source = None if r.status_code in (402, 429): source = r.json()["error"].get("metadata", {}).get("limit_source") if source == "openrouter_free_tier_daily": # resets at UTC midnight, so don't sleep until then r.raise_for_status() # A 402 from the in-flight budget clears after Retry-After; other 402s need credits. if r.status_code != 429 and source != "openrouter_in_flight_budget": r.raise_for_status() return r.json() if attempt == max_attempts - 1: break # out of attempts, so don't wait before failing wait = retry_delay(r.headers, attempt) print(f"{r.status_code} ({source}), attempt {attempt + 1}: waiting {wait:.1f}s") time.sleep(wait) r.raise_for_status() if __name__ == "__main__": def job(i): return chat({ "model": "poolside/laguna-s-2.1:free", "messages": [{"role": "user", "content": f"Reply with the number {i}."}], "max_tokens": 16, }) t0 = time.time() with ThreadPoolExecutor(max_workers=10) as pool: # the same batch job: 60 prompts, 10 at a time results = list(pool.map(job, range(60))) print(f"{len(results)} of 60 completed in {time.time() - t0:.0f}s") 429 (openrouter_free_tier_per_minute), attempt 1: waiting 19.3s 429 (openrouter_free_tier_per_minute), attempt 1: waiting 19.1s 429 (openrouter_free_tier_per_minute), attempt 1: waiting 18.8s 429 (openrouter_free_tier_per_minute), attempt 1: waiting 17.2s 429 (openrouter_free_tier_per_minute), at