429 Too Many Requests(请求过多)错误意味着你在当前时间窗口内发送的请求数或令牌数超过了你的限制。OpenAI、Anthropic 和 OpenRouter 均会返回此错误,它通常出现在应用程序在真实负载下首次运行,或批处理作业分散到多个工作进程时。
大多数人会选择重试,但在默认设置下,这往往不够。当我们通过 OpenAI Python SDK 对每分钟限制执行包含 60 个提示的批处理时,在 SDK 进行重试后,仍有 23 个请求失败。SDK 放弃每个请求后的 4 到 8 秒内,时间窗口才会重置。
本指南从真实的 429 错误出发,解读其响应头,并提供三种修复方法:在错误给出的重置时间进行重试、将溢出流量发送到备用模型,以及让其他提供商服务同一模型。我们在 OpenRouter API 上运行了所有示例,每个代码块下方的输出即为我们获得的结果。
简而言之
429 意味着你在当前窗口内达到了限制。在 OpenRouter 上,error.metadata.limit_source 会告诉你这是谁的限额。
使用默认设置时,OpenAI Python SDK 会对每个 429 错误重试两次,并在约 2 秒后放弃。针对每分钟限制,我们批处理中的 60 个请求仍有 23 个失败。
等待 Retry-After 或 X-RateLimit-Reset 的重试在每次运行中完成了全部 60 个请求,耗时分别为 Python 的 89 到 92 秒和 TypeScript 的 106 到 218 秒。
使用模型备用方案在 13 秒内完成了全部 60 个请求,费用为 0.000066 美元,且无需等待。
固定在一个提供商且关闭故障转移时,每次运行最多有 32 个请求失败(共 150 个)。开启故障转移后,每次运行的 150 个请求全部成功。
429 速率限制错误看起来是什么样?
我们向 poolside/lagina-s-2.1:free(一个每分钟限制为 20 次请求的免费模型)同时发送了 40 个请求。其中 38 个成功,另外两个返回了来自服务该模型的提供商的 429 错误:
200: 38 429: 2 other: 0
429 limit_source: {'upstream_provider_shared_pool': 2}
来自我们自身免费层级限制的 429 错误带有不同的 limit_source。以下是另一次运行的结果:
{
"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
}
}
响应头中包含你需要的数值。X-RateLimit-Limit 是上限,X-RateLimit-Remaining 是剩余数量,而 X-RateLimit-Reset 是重试可能成功的最早时间,以毫秒为单位的 Unix 时间戳表示。正文部分添加了 limit_source,说明你触发了谁的限额,以及 remedy_hint(补救提示),这是写给阅读日志的人看的。在代码中应根据 limit_source 进行分支判断,而不是根据提示文本。
OpenAI 和 Anthropic 使用不同的名称发送相同的信息。OpenAI 的 x-ratelimit-reset-requests 是一个持续时间(如 1s),而两个提供商都可以将 retry-after 作为秒数发送。
为什么速率限制会在不同的请求数量下触发?
40 个请求中有 38 个通过了 20 的限制。限流器可以接受在计数追上之前同时到达的请求,并且大多数限流器不会在每个分钟开始时干净地重置。Anthropic 使用持续补充的令牌桶。OpenAI 可能会在你的流量增长过快时返回带有 slow_down 代码的 429 错误,即使你仍在每分钟限制之内。
为了查看我们免费模型的限制计数方式,我们以不同的模式发送了另外 161 个请求。以下是其中三种:
测试 在该分钟内成功数
空闲两分钟后顺序发送 30
紧接着的分钟顺序发送 30
30 个并发请求 29
由此得出了两点结论。在我们测试的每一分钟内,超过 20 个请求都成功了,因此应将 20 视为 429 错误可能开始的阈值,而非精确计数。当我们在 poolside/laguna-s-2.1:free 上剩余 58 秒窗口期时触发限制,五个发往 minimax/minimax-m3.1-flash:free 的请求立即通过,而 Laguna 仍被屏蔽。但这并不意味着限制是按每个模型单独计算的。OpenRouter 对账户中的所有免费模型应用统一的分流限速器,因此对另一个免费模型的请求也可能收到相同的 429 错误。
第一步:确认你触发了谁的限额
等待仅在限额按时间表重置时才能解决 429 错误,因此在确定修复方案前,请先检查 limit_source:
limit_source | 状态 | 谁的限额 | 修复方法
openrouter_free_tier_per_minute | 429 | 我们的免费模型上限 | 等待 X-RateLimit-Reset(第二步),或回退到付费模型(第三步)
upstream_provider_shared_pool | 429 | 提供该模型的提供商 | 使用另一个提供商(第四步)或回退模型(第三步)
openrouter_in_flight_budget | 402 | 你的进行中支出预算 | 等待 Retry-After 并重试
openrouter_key_limit, openrouter_credits | 402 | 你的密钥信用额度或余额 | 提高密钥限额或充值
上游 429 意味着提供该模型的提供商已无容量。提供商不会说明容量何时释放,因此在我们的运行中,这些错误没有携带重置头信息。Gemma 4 31B 的免费版本返回了以下内容:
google/gemma-4-31b-it:free is temporarily rate-limited upstream. Please retry shortly, or add your own key to accumulate your rate limits.
使用付费变体作为回退的同一请求利用了另一家提供商的容量,并在 DeepInfra 上以 0.0000037 美元成功执行。
一些看似限速的错误实际上与资金有关。当你达到月度支出上限时,OpenAI 和 Anthropic 都会返回 429 错误,在限额重置前重试无法解决此问题。在 OpenRouter 上,信用问题则返回 402 错误。
第二步:在错误提示的重置时间重试
OpenAI 和 Anthropic 的 Python SDK 默认会重试两次 429 错误,采用较短的退避机制,起始时间为 0.5 秒,且最长等待不超过 8 秒。当服务器发送 Retry-After 头时,它们会遵循该指示。
我们的免费层 429 错误发送的是 X-RateLimit-Reset,而 SDK 不会读取此字段,因此两次重试都落在了同一个完整分钟内。以下是通过 OpenAI SDK(openai 3.26.1)以默认设置分批处理 60 个提示词(每次 10 个)的结果:
openai 3.26.1 | max_retries 默认值: 2
耗时 12s(发送 HTTP 请求数: 112)
成功: 37 次重试后仍出现 RateLimitError: 23 次
最慢的失败在 2.3s 后放弃
消息: 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 窗口在 SDK 放弃后 8s 重置
limit_source=openrouter_free_tier_per_minute x-ratelimit-reset: 1792444980000 retry-after: None 窗口在 SDK 放弃后 7s 重置
...
limit_source=openrouter_free_tier_per_minute x-ratelimit-reset: 1792444980000 retry-after: None 窗口在 SDK 放弃后 4s 重置
SDK 为 60 个提示词发送了 112 个 HTTP 请求,仍有 23 个失败。增加 max_retries 最终可以成功,但这意味着每 8 秒向已满的窗口发送一次请求,且 OpenAI 的文档指出失败的请求仍会计入你的每分钟限额。更好的重试方式是等待服务器指定的时间。要运行全部 60 个提示词,请使用账户中当天剩余至少 60 次免费模型请求额度的账号,因为未购买 10 个信用点的账户每天可获得 50 次:
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):
"""429 错误后等待的秒数:优先使用 Retry-After,其次 X-RateLimit-Reset,最后采用退避策略。"""
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 时间戳,单位为毫秒
if reset:
return max ( 0.0 , int (reset) / 1000 - time.time()) + random.uniform( 1 , 5 )
return min ( 2 ** attempt, 60 ) * random.uniform( 0.5 , 1 ) # 带抖动的指数退避
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" : # 在 UTC 午夜重置,因此不要在此前休眠
r.raise_for_status()
if r.status_code != 429 and source != "openrouter_in_flight_budget" :
r.raise_for_status()
return r.json()
if attempt == max_attempts - 1 :
break # 尝试次数用尽,因此在失败前不要等待
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: # 相同的批处理任务:60 个提示,每次 10 个
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), attempt 1: waiting 19.7s
429 (openrouter_free_tier_per_minute), attempt 1: waiting 15.6s
429 (openrouter_free_tier_per_minute), attempt 1: waiting 14.8s
429 (openrouter_free_tier_per_minute), attempt 1: waiting 16.4s
429 (openrouter_free_tier_per_minute), attempt 2: waiting 61.7s
429 (openrouter_free_tier_per_minute), attempt 2: waiting 58.9s
429 (openrouter_free_tier_per_minute), attempt 2: waiting 60.1s
429 (openrouter_free_tier_per_minute), attempt 2: waiting 57.8s
60 of 60 completed in 89s
所有 60 个请求均已完成,但批处理耗时 89 秒而非 12 秒。使用此方法不会发生任何失败,每个触及限制的请求都会等待窗口期结束。
retry_delay 首先检查 Retry-After,因为它是服务器的直接指令,而 X-RateLimit-Reset 仅标记窗口期的重置时间。1 到 5 秒的随机延迟可防止 10 个工作者在同一时刻重试并一次性填满新窗口。
尽管如此,本次运行中有四个请求在新窗口已填满后才进行重试,因此它们等待了第二次。如果你像这样将 SDK 调用包裹在循环中,请在客户端设置 max_retries=0,否则你的每次尝试都会变成三次请求。
TypeScript 中的相同重试逻辑
retry.ts 遵循相同的顺序:Retry-After,然后 X-RateLimit-Reset,最后退避。它使用内置的 fetch,因此不需要任何包。我们在 Node 24 上使用 npx tsx retry.ts 运行了它:
const URL = "https://openrouter.ai/api/v1/chat/completions" ;
const HEADERS = {
Authorization: Bearer ${ process . env . OPENROUTER_API_KEY } ,
"Content-Type" : "application/json" ,
};
const sleep = ( ms : number ) => new Promise (( resolve ) => setTimeout (resolve, ms));
const randomBetween = ( min : number , max : number ) => min + Math. random () * (max - min);
/* 429 错误后的等待秒数:优先 Retry-After,其次 X-RateLimit-Reset,最后退避。 /
export function retryDelay ( headers : Headers , attempt : number ) : number {
const retryAfter = headers. get ( "Retry-After" );
if (retryAfter) {
const seconds = Number (retryAfter);
if ( ! Number. isNaN (seconds)) return seconds;
const when = Date. parse (retryAfter); // HTTP 日期
if ( ! Number. isNaN (when)) return Math. max ( 0 , (when - Date. now ()) / 1000 );
}
const reset = headers. get ( "X-RateLimit-Reset" ); // Unix 时间戳,单位为毫秒
if (reset) {
// 在重置后的几秒内分散客户端请求,避免它们同时重试。
return Math. max ( 0 , ( Number (reset) - Date. now ()) / 1000 ) + randomBetween ( 1 , 5 );
}
return Math. min ( 2 ** attempt, 60 ) * randomBetween ( 0.5 , 1 ); // 指数退避并添加抖动
}
export async function chat ( body : object , maxAttempts = 6 ) : Promise < any > {
let res : Response | undefined ;
for ( let attempt = 0 ; attempt < maxAttempts; attempt ++ ) {
res = await fetch ( URL , { method: "POST" , headers: HEADERS , body: JSON . stringify (body) });
if (res.status !== 402 && res.status !== 429 ) {
if ( ! res.ok) throw new Error ( HTTP ${ res . status }: ${ await res . text () } );
return res. json ();
}
const error = ( await res. json ()).error;
const source = error?.metadata?.limit_source;
// 来自运行中预算的 402 错误会在 Retry-After 后清除;其他 402 错误需要积分。
if (res.status === 402 && source !== "openrouter_in_flight_budget" ) {
throw new Error ( HTTP 402: ${ JSON . stringify ( error ) } );
}
if (source === "openrouter_free_tier_daily" ) {
throw new Error ( HTTP 429: ${ JSON . stringify ( error ) } ); // 在 UTC 午夜重置,因此不要等到那时再休眠
}
if (attempt === maxAttempts - 1 ) break ; // 尝试次数用尽,因此在失败前不等待
const wait = retryDelay (res.headers, attempt);
console. log ( ${ res . status } (${ source }), attempt ${ attempt + 1 }: waiting ${ wait . toFixed ( 1 ) }s );
await sleep (wait * 1000 );
}
throw new Error ( Still rate limited after ${ maxAttempts } attempts );
}
// 相同的批处理任务:60 个提示词,每次 10 个。
async function main () {
const prompts = Array. from ({ length: 60 }, ( _ , i ) => i);
const results : any [] = [];
const worker = async () => {
for ( let i = prompts. shift (); i !== undefined ; i = prompts. shift ()) {
results[i] = await chat ({
model: "poolside/laguna-s-2.1:free" ,
messages: [{ role: "user" , content: Reply with the number ${ i }. }],
max_tokens: 16 ,
});
}
};
const t0 = Date. now ();
await Promise . all (Array. from ({ length: 10 }, worker));
const completed = results. filter (Boolean). length ;
console. log ( ${ completed } of 60 completed in ${ Math . round (( Date . now () - t0 ) / 1000 ) }s );
}
main ();
429 (openrouter_free_tier_per_minute), attempt 1: waiting 34.9s
429 (openrouter_free_tier_per_minute), attempt 1: waiting 34.6s
429 (openrouter_free_tier_per_minute), attempt 1: waiting 35.1s
429 (openrouter_free_tier_per_minute), attempt 1: waiting 33.5s
429 (openrouter_free_tier_per_minute), attempt 2: waiting 60.5s
429 (openrouter_free_tier_per_minute), attempt 2: waiting 58.6s
429 (openrouter_free_tier_per_minute), attempt 2: waiting 60.6s
60 of 60 completed in 106s
总耗时取决于批处理启动时窗口的位置以及模型提供商的繁忙程度。我们的两次 TypeScript 运行分别耗时 218 秒和 106 秒,两次 Python 运行分别耗时 92 秒和 89 秒。所有四次运行都完成了全部请求。
步骤 3:将溢出流量发送到备用模型
如果第二个模型的回答可以接受,你完全不需要等待。提供商的速率限制仅针对单个提供商中的单一模型,因此不同的模型使用独立的容量。免费层级的上限是一个例外,因为你账户上的所有 :free 模型共享该上限。通过 models 参数,我们会按顺序尝试每个模型,并在出现任何错误(包括 429)时移至下一个模型,而不会让任何错误直接返回到你的代码中:
import os
import time
from collections import Counter
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 job (i):
r = requests.post( URL , headers = HEADERS , timeout = 120 , json = {
"models" : [ "poolside/laguna-s-2.1:free" , "deepseek/deepseek-v4.1-flash" ]
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 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:
Test Succeeded in that minute
Sequential, after two idle minutes 30
Sequential, the minute right after 30
30 concurrent 29
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_source Status Whose limit What fixes it
openrouter_free_tier_per_minute 429 Our free-model cap Wait for X-RateLimit-Reset (Step 2), or fall back to a paid model (Step 3)
upstream_provider_shared_pool 429 The provider serving the model Another provider (Step 4) or a fallback model (Step 3)
openrouter_in_flight_budget 402 Your in-flight spending budget Wait for Retry-After and retry
openrouter_key_limit, openrouter_credits 402 Your key’s credit limit or your balance Raise 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:
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()
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), attempt 1: waiting 19.7s
429 (openrouter_free_tier_per_minute), attempt 1: waiting 15.6s
429 (openrouter_free_tier_per_minute), attempt 1: waiting 14.8s
429 (openrouter_free_tier_per_minute), attempt 1: waiting 16.4s
429 (openrouter_free_tier_per_minute), attempt 2: waiting 61.7s
429 (openrouter_free_tier_per_minute), attempt 2: waiting 58.9s
429 (openrouter_free_tier_per_minute), attempt 2: waiting 60.1s
429 (openrouter_free_tier_per_minute), attempt 2: waiting 57.8s
60 of 60 completed in 89s
All 60 requests finished, but the batch took 89 seconds instead of 12. Nothing fails with this approach, and every request that hits the limit waits out the window.
retry_delay checks Retry-After first because it’s the server’s direct instruction, while X-RateLimit-Reset only marks when the window rolls over. The random 1 to 5 seconds keeps the 10 workers from retrying at the same instant and filling the new window at once.
Even so, four requests in this run retried after the new window had already filled, so they waited a second time. If you wrap an SDK call in a loop like this, set max_retries=0 on the client, or each of your attempts turns into three requests.
The same retry in TypeScript
retry.ts follows the same order: Retry-After, then X-RateLimit-Reset, then backoff. It uses the built-in fetch, so it needs no packages. We ran it on Node 24 with npx tsx retry.ts:
const URL = "https://openrouter.ai/api/v1/chat/completions" ;
const HEADERS = {
Authorization: Bearer ${ process . env . OPENROUTER_API_KEY } ,
"Content-Type" : "application/json" ,
};
const sleep = ( ms : number ) => new Promise (( resolve ) => setTimeout (resolve, ms));
const randomBetween = ( min : number , max : number ) => min + Math. random () * (max - min);
/* Seconds to wait after a 429: Retry-After, then X-RateLimit-Reset, then backoff. /
export function retryDelay ( headers : Headers , attempt : number ) : number {
const retryAfter = headers. get ( "Retry-After" );
if (retryAfter) {
const seconds = Number (retryAfter);
if ( ! Number. isNaN (seconds)) return seconds;
const when = Date. parse (retryAfter); // HTTP date
if ( ! Number. isNaN (when)) return Math. max ( 0 , (when - Date. now ()) / 1000 );
}
const 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 Math. max ( 0 , ( Number (reset) - Date. now ()) / 1000 ) + randomBetween ( 1 , 5 );
}
return Math. min ( 2 ** attempt, 60 ) * randomBetween ( 0.5 , 1 ); // exponential backoff with jitter
}
export async function chat ( body : object , maxAttempts = 6 ) : Promise < any > {
let res : Response | undefined ;
for ( let attempt = 0 ; attempt < maxAttempts; attempt ++ ) {
res = await fetch ( URL , { method: "POST" , headers: HEADERS , body: JSON . stringify (body) });
if (res.status !== 402 && res.status !== 429 ) {
if ( ! res.ok) throw new Error ( HTTP ${ res . status }: ${ await res . text () } );
return res. json ();
}
const error = ( await res. json ()).error;
const source = error?.metadata?.limit_source;
// A 402 from the in-flight budget clears after Retry-After; other 402s need credits.
if (res.status === 402 && source !== "openrouter_in_flight_budget" ) {
throw new Error ( HTTP 402: ${ JSON . stringify ( error ) } );
}
if (source === "openrouter_free_tier_daily" ) {
throw new Error ( HTTP 429: ${ JSON . stringify ( error ) } ); // resets at UTC midnight, so don't sleep until then
}
if (attempt === maxAttempts - 1 ) break ; // out of attempts, so don't wait before failing
const wait = retryDelay (res.headers, attempt);
console. log ( ${ res . status } (${ source }), attempt ${ attempt + 1 }: waiting ${ wait . toFixed ( 1 ) }s );
await sleep (wait * 1000 );
}
throw new Error ( Still rate limited after ${ maxAttempts } attempts );
}
// The same batch job: 60 prompts, 10 at a time.
async function main () {
const prompts = Array. from ({ length: 60 }, ( _ , i ) => i);
const results : any [] = [];
const worker = async () => {
for ( let i = prompts. shift (); i !== undefined ; i = prompts. shift ()) {
results[i] = await chat ({
model: "poolside/laguna-s-2.1:free" ,
messages: [{ role: "user" , content: Reply with the number ${ i }. }],
max_tokens: 16 ,
});
}
};
const t0 = Date. now ();
await Promise . all (Array. from ({ length: 10 }, worker));
const completed = results. filter (Boolean). length ;
console. log ( ${ completed } of 60 completed in ${ Math . round (( Date . now () - t0 ) / 1000 ) }s );
}
main ();
429 (openrouter_free_tier_per_minute), attempt 1: waiting 34.9s
429 (openrouter_free_tier_per_minute), attempt 1: waiting 34.6s
429 (openrouter_free_tier_per_minute), attempt 1: waiting 35.1s
429 (openrouter_free_tier_per_minute), attempt 1: waiting 33.5s
429 (openrouter_free_tier_per_minute), attempt 2: waiting 60.5s
429 (openrouter_free_tier_per_minute), attempt 2: waiting 58.6s
429 (openrouter_free_tier_per_minute), attempt 2: waiting 60.6s
60 of 60 completed in 106s
The total time depends on where the window is when the batch starts and on how busy the model’s provider is. Our two TypeScript runs took 218 and 106 seconds, and our two Python runs took 92 and 89. All four finished every request.
Step 3: Send overflow to a fallback model
If an answer from a second model is acceptable, you don’t have to wait at all. A provider rate limit applies to one model at one provider, so a different model uses separate capacity. The free-tier cap is the exception, because every :free model on your account shares it. With the models parameter, we try each model in order and move to the next on any error, including a 429, before anything reaches your code :
import os
import time
from collections import Counter
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 job (i):
r = requests.post( URL , headers = HEADERS , timeout = 120 , json = {
"models" : [ "poolside/laguna-s-2.1:free" , "deepseek/deepseek-v4.1-flash" ]
首次收录 · 2026-11-12 · 9.95 分