Sub topic 3
Understanding Rate Limits and 429 Responses
This chapter assumes you can read Python and know what an HTTP status code and a response header are. It also assumes you have called an LLM API at least once. Earlier chapters sorted errors into retryable and permanent. Here we look at the most common retryable error, HTTP 429, and at the limits that cause it.
What a rate limit is
A rate limit is a cap the provider puts on how much you can use the API in a window of time. It protects shared capacity, so one customer cannot slow down everyone else. When you exceed the cap, the provider rejects the request with status 429 Too Many Requests. The request was valid. The server is telling you to slow down.
A 429 is different from a 400 or 401. Those mean the request itself is wrong, and sending it again changes nothing. A 429 usually clears by itself once the window moves on, so it is normally retryable.
The kinds of limits
Providers use several limits at once. You hit whichever you reach first.
| Limit | Measures | Typical trigger |
|---|---|---|
| Requests per minute (RPM) | Number of calls | Many small calls in a loop |
| Tokens per minute (TPM) | Input plus output tokens | Few calls with large prompts |
| Requests or tokens per day | Daily totals | Batch jobs running for hours |
| Concurrent requests | Calls in flight at once | Large worker pools |
| Spend or quota | Money or credits | Billing cap reached |
Some providers count input and output tokens separately, so you may see input tokens per minute and output tokens per minute as two limits. The names and numbers differ by provider and by account tier. Read your provider's limits page and your account dashboard instead of assuming numbers.
Why token limits surprise people
RPM is easy to reason about. TPM is harder, because the cost of a request depends on its size. Ten requests with 50,000-token prompts can exhaust a limit that a thousand short requests would not.
Some providers also estimate the cost of a request before it runs. They may count your max_tokens setting toward the limit even if the model writes far fewer tokens. A large max_tokens on every call can therefore trigger 429 responses earlier than the real output would. Set max_tokens close to what you need.
Reading a 429 response
A 429 response carries three useful kinds of information.
- The status code, 429.
- A JSON body with an error type or code and a human-readable message.
- Headers, which often include
Retry-Afterand the state of your limits.
Header names vary by provider. OpenAI uses names such as x-ratelimit-remaining-requests and x-ratelimit-reset-tokens. Anthropic uses an anthropic-ratelimit- prefix. Both send retry-after on many 429 responses. The reset values may be durations like 6m0s, timestamps, or plain seconds, so check the format for your provider before parsing them.
Headers on successful responses are valuable too. If remaining values are shrinking toward zero, you can slow down before the first 429 arrives.
A 429 is not always retryable
Some providers return 429 for an exhausted quota or spending cap. OpenAI, for example, uses the error code insufficient_quota for this. Waiting a few seconds will not fix it. Someone has to add credit or raise the cap. Retrying such an error wastes time and hides a billing problem.
The next example separates the two cases and extracts the header values worth logging. It builds sample responses by hand so you can run it without an API key.
import httpx
def classify_429(resp: httpx.Response) -> str:
"""Return 'rate_limited' (retry later) or 'quota_exhausted' (do not retry)."""
try:
body = resp.json()
except ValueError:
return "rate_limited"
error = body.get("error") if isinstance(body, dict) else None
if isinstance(error, dict):
code = error.get("code") or error.get("type") or ""
if code == "insufficient_quota":
return "quota_exhausted"
return "rate_limited"
def rate_limit_info(resp: httpx.Response) -> dict:
"""Collect rate-limit headers worth logging. Missing headers become None."""
names = (
"retry-after",
"x-ratelimit-remaining-requests",
"x-ratelimit-remaining-tokens",
"x-ratelimit-reset-requests",
"x-ratelimit-reset-tokens",
)
return {name: resp.headers.get(name) for name in names}
busy = httpx.Response(
429,
headers={"retry-after": "7", "x-ratelimit-remaining-requests": "0"},
json={"error": {"type": "rate_limit_exceeded", "message": "Too many requests"}},
)
broke = httpx.Response(
429,
json={"error": {"code": "insufficient_quota", "message": "Quota exceeded"}},
)
for resp in (busy, broke):
print(classify_429(resp), rate_limit_info(resp))The first response is classified as rate_limited and the second as quota_exhausted. Your retry logic should retry only the first.
How the limit is enforced
Most providers describe their limits as a token bucket, which is the same model as the client-side limiter later in this tutorial. The bucket holds a maximum number of units, such as requests or tokens. It refills at a steady rate. Each request removes units. If the bucket cannot cover your request, you get a 429.
This has two practical effects:
- Limits are not always enforced per whole minute. A limit of 600 requests per minute may behave like 10 per second. A burst of 100 calls in one second can be rejected even though you are far below 600 for the minute.
- Capacity returns gradually. Waiting a short time often frees enough room for the next request, so a precise
Retry-Afteris usually short.
Where limits apply
Limits attach to specific scopes. Knowing the scope explains why a 429 can appear when your own traffic looks light.
- Per account or organization. All your services and teammates share one pool. A nightly batch job can cause 429 responses in a user-facing app.
- Per model. Many providers set separate limits for each model, and a request to one model does not use another's allowance.
- Per project or API key. Some providers let you set a lower limit on a key to protect the rest of your account.
- Per region or deployment. Cloud-hosted offerings often set limits per deployment.
Because the pool is shared across processes, each process cannot see the others' usage. The server's headers are the only combined view, and they are a reason to log them.
Capacity errors that look similar
Rate limits are about your usage. A provider can also be short on capacity overall. That shows up as 503 or a provider-specific code, such as 529 for overloaded at Anthropic. These are retryable, and the response is the same: wait, then try again. Still, log them separately from 429 responses. A rising 429 count points to your own traffic, while a rising 503 count points to the provider.
What to do when you receive a 429
- Classify it. If it signals an exhausted quota, stop and surface the error.
- Look for
Retry-After. If present, wait at least that long. - If absent, use exponential backoff with jitter, covered in the next chapters.
- Cap the number of attempts.
- Log the headers, so you can see which limit you hit.
Common mistakes
- Treating all 429 responses as retryable, including exhausted quotas.
- Ignoring
Retry-Afterand guessing a wait time. - Setting a large
max_tokenson every call, which can use up the token allowance faster than the output requires. - Measuring only requests per minute when the real constraint is tokens per minute.
- Testing with one worker and then deploying many, so the combined traffic crosses the shared limit.
Exercise
Your service gets a 429 with the body {"error": {"code": "insufficient_quota"}} and no Retry-After header. Should it retry with backoff? Explain why.
Show answer
No. insufficient_quota means the account has run out of credit or hit a spending cap, not that it is sending requests too fast. Waiting does not restore quota, so retries only delay the failure. The service should stop, surface the error, and alert someone who can add credit or raise the cap.
Exercise
A job sends only 20 requests per minute, well under its 500 RPM limit, but still receives 429 responses. Name two limits that could explain this.
Show answer
Likely causes are the tokens-per-minute limit, because each request has a very large prompt or a large max_tokens value, and a shared account-level pool, because other services using the same account or key consume the allowance. A concurrency limit or a short-burst limit could also apply.