Rate limits, retries and backpressure for LLM APIs
LLM calls fail in boring, predictable ways: you hit a rate limit, the provider is overloaded, a request times out halfway through a long generation, or your own GPU servers are saturated. None of that is avoidable, but all of it is manageable. The goal of this doc is a client and service design where overload produces slightly slower answers or clear "try again" messages, not a retry storm that takes everything down.
Why it matters
LLM requests are long (seconds to minutes), expensive, and limited along several dimensions at once. A naive loop that retries immediately on any error turns a brief provider hiccup into sustained overload, because every client retries at the same moment. In agent systems it is worse: a retried step that already called a tool can duplicate side effects such as sending an email twice.
How it works
What gets limited
Hosted providers usually enforce several limits per organisation (not per key) over a time window:
- Requests per minute (RPM).
- Input tokens per minute and output tokens per minute (sometimes combined as TPM).
- Sometimes concurrent requests or daily quotas.
Anthropic documents that its limits are enforced with a token bucket, so capacity refills continuously rather than resetting at the top of the minute. That means short bursts can be rejected even when your per-minute average is under the limit. OpenAI and Anthropic both return rate limit information in response headers, and a retry-after header on 429 responses tells you how long to wait. Check each provider's rate limit page for exact header names.
Which errors to retry
| Signal | Meaning | Retry? |
|---|---|---|
| 429 | You exceeded a limit | Yes, after retry-after or backoff |
| 529 (Anthropic) or 503 | Provider overloaded | Yes, with backoff; consider fallback |
| 500, 502 | Transient server error | Yes, a few times |
| Timeout or connection reset | Unknown outcome | Yes if idempotent |
| 400, 401, 403, 404, 413 | Your request is wrong | No |
Backoff with jitter
Exponential backoff increases the wait after each failure; jitter randomises it so clients spread out. The "full jitter" variant from the AWS Builders' Library is a good default:
sleep = random_between(0, min(cap, base × 2^attempt))
If the server sent retry-after, use that instead (plus a little jitter). Cap the number of attempts and the total time budget.
Rendering diagram…
Backpressure
Retries handle someone else's overload. Backpressure handles your own. The idea is to stop accepting work faster than you can finish it:
- Client-side token bucket. Track your own RPM and TPM budget (estimate input tokens before sending, reserve
max_tokensfor output) and wait locally instead of sending requests you know will be rejected. - Concurrency limits. A semaphore per provider or model caps in-flight requests.
- Bounded queues. Queue excess work with a maximum length and a maximum wait. When full, reject quickly with a clear error rather than letting latency grow without bound.
- Priority. Interactive requests go ahead of batch jobs; batch can use provider batch APIs where available.
- Load shedding at the server. Self-hosted engines expose queue depth (for vLLM, waiting requests in its metrics). A gateway can return 429 or 503 when the queue passes a threshold, which keeps latency acceptable for the requests you do accept.
Reference architecture
Rendering diagram…
The limiter updates itself from the provider's rate limit headers so it adapts when limits change. For multiple app instances, keep limiter state in Redis or run the limiter inside a shared gateway (see gateways and routing).
Code
A small async wrapper with full jitter, retry-after support, a concurrency cap and an idempotency key. Official SDKs already retry some errors by default (configurable with max_retries), so I disable SDK retries here to avoid double retrying.
import asyncio, random, uuid
import anthropic
client = anthropic.AsyncAnthropic(max_retries=0, timeout=60)
SEM = asyncio.Semaphore(16)
RETRYABLE = {429, 500, 502, 503, 529}
async def call_with_retries(messages, max_attempts=5, base=1.0, cap=30.0):
idem_key = str(uuid.uuid4()) # reuse for tool side effects downstream
for attempt in range(max_attempts):
try:
async with SEM:
return await client.messages.create(
model="claude-sonnet-4-5", max_tokens=1024, messages=messages,
metadata={"user_id": "svc-reports"},
)
except anthropic.APIStatusError as e:
if e.status_code not in RETRYABLE or attempt == max_attempts - 1:
raise
ra = e.response.headers.get("retry-after")
delay = float(ra) + random.uniform(0, 1) if ra else random.uniform(0, min(cap, base * 2 ** attempt))
except (anthropic.APIConnectionError, anthropic.APITimeoutError):
if attempt == max_attempts - 1:
raise
delay = random.uniform(0, min(cap, base * 2 ** attempt))
await asyncio.sleep(delay)
The idempotency key is not sent to the model provider here; it is what you attach to any tool execution or database write triggered by the response, so a retried step can detect "already done".
Trade-offs and pitfalls
- Double retries. SDK retries plus gateway retries plus your own loop can multiply attempts. Decide which layer owns retries and turn the others off or down.
- Retrying long generations is expensive. A timeout after 50 seconds of streaming wastes those tokens. Prefer streaming with progress, sensible
max_tokens, and timeouts sized to expected output length. - Mid-stream failures. If a stream breaks after partial output, decide whether to resume (send the partial answer back as context) or restart. Never silently concatenate two different attempts.
- Overload is shared. Retrying a provider-wide overload aggressively harms everyone, including you. Back off harder on overload errors than on your own rate limits, and consider failing over to another provider.
- Token estimates drift. Client-side token budgeting is approximate. Leave headroom and correct using the provider's headers.
- Agent side effects. Make tool calls idempotent or check-before-write. Retrying model calls is safe; retrying actions often is not.
Checklist
- Exactly one layer owns retries, with a capped attempt count and time budget.
- Backoff uses jitter and honours
retry-after. - Non-retryable 4xx errors fail fast with a useful message.
- In-flight requests are capped per provider and model.
- Queues are bounded, prioritised, and reject quickly when full.
- My limiter reads provider rate limit headers.
- Tool executions use idempotency keys.