How to Handle LLM API Rate Limits (HTTP 429): A Practical Guide
This article explains what an HTTP 429 response from a large language model API actually means, why rate limiting tends to appear as usage grows, and how to respond to it. It covers the main quota layers behind throttling, including concurrency limits, requests per minute (RPM), tokens per minute (TPM), key-level quotas, and backend capacity protection. It then walks through four layers of defense: retrying with exponential backoff and jitter, shaping client-side traffic with token buckets and concurrency gates, compressing context to reduce token consumption, and falling back across multiple models or asynchronous queues. It also outlines the observability metrics worth tracking and a practical approach to quotas and billing expectations. The goal is to treat rate limiting as a normal constraint and design for it rather than patching around occasional failures.
1. What Actually Happens When the API Returns 429
In AI coding tools, conversational applications, or batch text-processing tasks, developers frequently run into call failures that look like this:
RateLimitError [HTTP 429]Error: The model is currently receiving too many requests. Please try again later.Details: {'code': '1305', 'message': 'The model is currently receiving too many requests. Please try again later.'}Elapsed: 0.37sContext: 64 msgs, ~43,303 tokensRate limited. Waiting 2.2s (attempt 2/3)...Rate limited. Waiting 4.8s (attempt 3/3)...Rate limited after 3 retries
This log carries three key signals. First, the HTTP status code is 429, which means “Too Many Requests.” It is a throttling signal that the client can perceive, not a server crash. Second, the response body includes a business error code and a message, which shows the request was rejected at the gateway’s load-protection layer and never actually entered the model inference queue. Third, the client made three built-in retries with waits of 2.2 seconds and 4.8 seconds, but all three failed, and the flow terminated with an exception.
It is important to distinguish 429 from 5xx errors. A 5xx usually indicates an internal server error, and retrying may help. A 429 means the current quota or concurrency allowance is already fully used, so blind high-frequency retries only make congestion worse and create a “retry storm.” The correct first response is to reduce the request rate, not to retry faster.
2. Why Rate Limiting Tends to Emerge as Usage Grows
Rate limiting for large model services is usually determined by several layers of quotas working together. Understanding these layers is the key to addressing the problem.
- Concurrency limit: There is a cap on how many requests can be processed at the same time within a given window, and burst traffic triggers it most easily.
- Requests per minute (RPM) limit: Unlike concurrency, this counts the total number of requests within a sliding window.
- Tokens per minute (TPM) limit: Measured by the combined input and output tokens, this is easily hit in long-context scenarios.
- Account- or key-level quota: When the same key is shared across multiple applications or environments, the allowance gets spread thin.
- Backend capacity protection: When the inference cluster is under heavy load, the gateway proactively rejects new requests to keep existing sessions stable.
The original scenario showed a context size of 64 msgs, ~43,303 tokens, which is a typical sign of the TPM dimension being consumed quickly: the larger a single request is, the fewer requests per minute the quota can support. It is also common in the industry for a model service to become periodically overloaded after rapid user growth, so the application side must assume that “rate limiting is the norm, not an exception” and design the call chain accordingly.
3. First Line of Defense: Get the Retry Strategy Right
Retrying at fixed intervals is the most common mistake. The correct approach is exponential backoff combined with random jitter, so that all clients do not wake up at the same moment.
import random, timedef call_with_backoff(fn, max_attempts=5, base=1.0, cap=30.0):for attempt in range(max_attempts):try:return fn()except RateLimitError:if attempt == max_attempts - 1:raise# Exponential backoff plus jitter to spread out concurrency peaksdelay = min(cap, base * (2 ** attempt)) + random.uniform(0, 1.0)time.sleep(delay)
There are three accompanying points. First, if the response returns a Retry-After header, you should follow that value rather than calculating your own. Second, set a maximum backoff cap to prevent the wait time from growing without bound. Third, distinguish retryable from non-retryable errors: retrying invalid parameters or an over-length context is pointless, so those should fail immediately and trigger an alert.
4. Second Line of Defense: Traffic Shaping on the Client Side
Retries are only a remedy; real stability comes from flattening the peaks.
- Token bucket rate limiting: Maintain a local rate limit on the client and proactively keep the request rate below the quota, reducing 429s at the source.
- Request queue and concurrency gate: Use a semaphore to control how many requests are in flight at once; the queue length needs a cap along with a timeout.
- Batching and merging: Combine multiple small tasks into a single call to reduce the number of requests, while balancing latency against throughput.
- Priority scheduling: Prioritize interactive requests, and have offline batch tasks automatically slow down and yield when throttling is detected.
A sample concurrency gate looks like this:
import asynciosem = asyncio.Semaphore(4) # Upper limit on in-flight requestsasync def guarded_call(coro):async with sem:return await coro
5. Third Line of Defense: Compress Context to Reduce Token Consumption
When the bottleneck is TPM rather than RPM, reducing the tokens per request is more effective than lowering the request frequency. Practical measures include: using a sliding window to keep only the most recent few turns of conversation, summarizing and compressing historical messages, replacing full-history injection with retrieval-based recall, and stripping redundant tool outputs and repeated system prompts. Compressing a context of more than forty thousand tokens down to a few thousand can often increase the number of available requests by an order of magnitude.
You should also validate the input budget: estimate the token size before sending, and trigger compression or splitting once it exceeds a threshold, rather than sending an over-length request and waiting for it to be rejected.
6. Fourth Line of Defense: Fallback and Multi-Model Redundancy
A mature solution does not bet availability on a single model. A common practice is to maintain a call priority chain: when the primary model is unavailable, switch to a backup model of the same capability; if that is also unavailable, switch to a smaller, faster lightweight model; and as a last resort, fall back to a queuing message or an asynchronous task. The switching should be abstracted into a unified adapter layer that wraps the differences between sources inside the adapters, so business code depends only on a unified interface.
Primary model → Backup model → Lightweight model → Async queue / manual fallback
In addition, non-real-time tasks can be turned into asynchronous jobs, buffered with a message queue, and called at a controlled, steady rate by consumers, which naturally avoids burst throttling.
7. Observability: Make Rate Limiting Measurable and Attributable
Without measurement there is no optimization. It is recommended to collect the following metrics and set up monitoring and alerts: the 429 rate, the distribution of retry counts, end-to-end latency, token consumption trends, and the success rate broken down by model. Keep the request identifier, model identifier, token size, and elapsed time in the logs to make it easy to trace and locate issues. When the 429 ratio stays above a set threshold, trigger an alert and automatically reduce the client’s send rate, forming a closed loop.
8. A Rational View of Billing and Entitlements
When developers hit rate limits, they often wonder about cost and entitlements. The proper approach is to rely on the quota descriptions in the service agreement and official documentation, check current usage and limits through the console or a quota interface, and submit a support ticket through the proper process to report anomalies, rather than making assumptions in application code. At the architecture level, you should always reserve a fallback path for “quota exhausted” and keep the uncertainty of external dependencies isolated at the system boundary.
9. Summary
When facing 429 rate limiting, the core ideas come down to four points: recognize the error semantics and do not retry blindly; use backoff plus jitter to spread out peaks; combine client-side rate limiting with context compression to reduce load at the source; and use multi-model fallback and asynchronous buffering as a safety net to keep the experience continuous. Designing with rate limiting as a normal constraint, rather than patching it as an occasional failure, is what keeps the call chain stable under the dual pressure of high concurrency and tight resources.
