← Back to Blog
Claude API

Claude API 限流完整指南:RPM、TPD、并发上限全解析(2026)

(no oficial)

Esta guía la mantiene la comunidad de forma independiente. No está afiliada, respaldada ni patrocinada por el proveedor de la herramienta de terceros que trata. Todas las marcas de terceros son propiedad de sus respectivos titulares.

May 11, 2026
Claude API 限流完整指南:RPM、TPD、并发上限全解析(2026)

TL;DR

Claude API 限流分三层:RPM(每分钟请求数)、TPD(每日 token 配额)、并发连接数。触发后返回 HTTP 429,附带retry-after秒数。本文实测各层限制、给出错误处理代码,并解释通过 CodeGateway 接入如何平滑接触这三类限制。

一、为什么会被限流?

Anthropic 对 Claude API 设置了四层独立的访问限制:

RPM:每分钟最多发送多少次请求,触发 429 rate_limit_error

TPD(输入/输出):每日 token 配额上限,触发 429 或 529 overloaded_error

并发:同时在途的最大请求数,触发 529 overloaded_error

这四个维度相互独立——RPM 没超,但并发超了一样返回错误。

实测背景:在 CodeGateway 的后台日志里,90% 以上的限流出现在批量任务(一次性并发发 10+ 请求)和流量高峰两个场景。单用户正常使用几乎不会触发。

二、Anthropic 官方限制档位(2026 年)

Anthropic 按 Tier 1–5 划分限制,新账号从 Tier 1 开始,累计消费后自动升级。

Tier 1(新账号):RPM 50,输入 TPD 5M,输出 TPD 100K

Tier 2(累计 $40):RPM 1,000,输入 TPD 40M,输出 TPD 400K

Tier 3(累计 $200):RPM 2,000,输入 TPD 200M,输出 TPD 2M

Tier 4(累计 $2,000):RPM 4,000,输入 TPD 1B,输出 TPD 10M

数据来源:Anthropic 官方限流文档(2026-05),具体数字随 Anthropic 策略调整。

▶ 查看最新档位:Anthropic Rate Limits 官方文档

对 CodeGateway 用户的含义:使用 CodeGateway 的 API Key,实际消耗的是 CodeGateway 在 Cloudflare AI Gateway 上的配额。CodeGateway 内部做了多 provider 分发,理论 RPM 上限高于单个 Anthropic 账号 Tier 1 的 50 RPM。

三、错误码识别与处理

HTTP 状态码

429 rate_limit_error:RPM 超限,等retry-after秒

529 overloaded_error:服务过载(含并发超限),等待后重试

500 api_error:服务器错误,不属于限流

429 响应头解读

触发限流时,Anthropic 在响应头给出等待时间:

bash
retry-after: 12
x-ratelimit-limit-requests: 50
x-ratelimit-remaining-requests: 0
x-ratelimit-reset-requests: 2026-05-11T04:00:00Z

retry-after:等待秒数,到期后重试成功率 >95%

x-ratelimit-reset-requests:本 RPM 窗口重置时间(ISO 8601)

实测错误处理代码(Python)

python
import anthropic
import time

client = anthropic.Anthropic(
    api_key="your-codegateway-key",
    base_url="https://api.codegateway.dev/v1"
)

def call_with_retry(prompt: str, max_retries: int = 5) -> str:
    for attempt in range(max_retries):
        try:
            response = client.messages.create(
                model="claude-sonnet-4-5",
                max_tokens=1024,
                messages=[{"role": "user", "content": prompt}]
            )
            return response.content[0].text
        except anthropic.RateLimitError as e:
            retry_after = int(e.response.headers.get("retry-after", 60))
            print(f"限流,等待 {retry_after}s(第 {attempt+1} 次重试)")
            time.sleep(retry_after)
        except anthropic.APIStatusError as e:
            if e.status_code == 529:
                wait = 30 * (2 ** attempt)
                print(f"服务过载,等待 {wait}s")
                time.sleep(wait)
            else:
                raise
    raise RuntimeError("超过最大重试次数")

实测结论:用retry-after头里的精确等待时间,比固定等 60 秒要好——实际平均只需等 8–15 秒。

四、并发限制:经常被忽略的一层

RPM 是每分钟请求次数,并发是同时在途的请求数。两者独立。

典型踩坑场景:RPM=50/分钟,但用asyncio.gather()同时发了 20 个请求 → 并发超限 → 529,即使 RPM 计数器没超。

控制并发的标准写法:

python
import asyncio
import anthropic

async def batch_process(prompts: list[str], max_concurrent: int = 5) -> list[str]:
    semaphore = asyncio.Semaphore(max_concurrent)
    client = anthropic.AsyncAnthropic(
        api_key="your-codegateway-key",
        base_url="https://api.codegateway.dev/v1"
    )
    
    async def single_call(prompt):
        async with semaphore:
            response = await client.messages.create(
                model="claude-sonnet-4-5",
                max_tokens=1024,
                messages=[{"role": "user", "content": prompt}]
            )
            return response.content[0].text
    
    return await asyncio.gather(*[single_call(p) for p in prompts])

推荐并发上限:Tier 1 用max_concurrent=3,Tier 2+ 可以放到 8–10。

五、降低限流概率的工程技巧

请求平铺(Rate Spreading)

与其 1 秒内发 50 个请求,不如匀速发送:

python
import time

def rate_limited_batch(prompts, rpm_limit=40):
    interval = 60.0 / rpm_limit  # 留 20% 余量
    results = []
    for prompt in prompts:
        start = time.time()
        results.append(call_with_retry(prompt))
        elapsed = time.time() - start
        if elapsed < interval:
            time.sleep(interval - elapsed)
    return results

Token 预算管理

不要把max_tokens设成 4096 当保险。Anthropic 按max_tokens请求值计入日配额,设太大加速消耗 TPD。

主动监控剩余配额

python
def check_quota_health(response_headers):
    remaining = int(response_headers.get("x-ratelimit-remaining-requests", 999))
    if remaining < 5:
        print(f"⚠️ RPM 配额告急:剩余 {remaining} 次,暂停批量任务")
        return False
    return True

六、Q&A

Q: 我的代码每次只发一个请求,为什么还是 429?

A: 常见原因是多个进程或服务共用同一个 API Key,累计 RPM 超限。建议在 CodeGateway 后台看请求日志,确认是哪个进程在消耗配额。

Q: 升级到 Tier 2 需要多久?

A: Anthropic Tier 升级是自动的,累计消费满 $40 后通常 1–2 个工作日生效。CodeGateway 内部多 provider 分发从实际使用感知上等效于更高配额。

Q: 529 和 429 哪个更严重?

A: 两者都是临时性的。429 是配额问题,等retry-after即可;529 是服务侧过载,通常 30–60 秒后自动恢复,跟配额无关。

Q: max_tokens 设多少合适?

A: 设实际需要的最大值。不必要的大max_tokens消耗日 TPD 配额(即使实际输出很短),会加速到达每日上限。

总结

遇到限流不要慌——绝大多数 429/529 在等待 10–60 秒后都能恢复。核心是把重试逻辑写对(用retry-after精确等待),其次才是升级配额。

Author:CodeGateway TeamReviewed on:2026-05-16

Resuelve los límites de claves de API y de facturación con CodeGateway

¿Sin clave de API oficial o con problemas para pagar con tarjeta internacional? Crea una clave sk-cg- al instante. Una sola clave para Claude, GPT, Gemini y DeepSeek: los modelos de texto de Claude y Gemini usan el protocolo Anthropic Messages (/v1/messages); los endpoints de texto compatibles con OpenAI no los aceptan. Incluye enrutamiento inteligente y créditos de prueba.

Crear cuenta gratis