Causes of HTTP 429 Rate Limiting in LLM APIs and Strategies for Stable API Calls
Learn what causes HTTP 429 errors in large language model APIs, why repeated retries can continue to fail, and how to build a more reliable client with exponential backoff, jitter, concurrency and rate control, context optimization, fallback mechanisms, monitoring, and user-friendly error handling.
1. What Does HTTP 429 Mean?
HTTP 429 (Too Many Requests) means that a client has sent more requests within a given period than the service allows. It is usually a temporary condition and does not necessarily indicate that the request itself is invalid.
A service may return HTTP 429 for several reasons:
- Account quota exhaustion: The request rate, number of concurrent connections, or token usage has exceeded the limit of the current plan.
- Overall service overload: When inference infrastructure is under heavy load, the provider may apply rate limits to protect availability. In this case, many callers may be affected at the same time, regardless of an individual account’s usage.
- Sudden traffic spikes: A large number of requests may be sent within a short period. Even when the average rate is within the allowed range, a burst can still trigger a limit.
The first step in identifying the cause is to inspect both the HTTP status code and the error body. Many services also include a Retry-After header that tells the client how many seconds to wait before trying again. Error code systems vary between providers, so always refer to the relevant API documentation instead of relying on assumptions.
2. Why the Same Request May Keep Failing
A common pattern in production logs is that the same request fails repeatedly. The client waits longer after each failure, then eventually gives up after reaching the retry limit. This indicates that basic retry logic is already in place, but the strategy may still need improvement.
Three common causes are:
- Retry intervals are too short: Fixed or very short delays can continue to pressure the service while it is recovering, potentially extending the congestion.
- Synchronized retries: If many clients fail at the same time and retry during the same second, they create another traffic spike.
- High per-request cost: Long contexts consume more tokens, take longer to process, and use more inference resources. This increases the likelihood of rate limiting.
If logs show a context of approximately 64 messages and more than 40,000 tokens, the third cause is especially relevant. The longer the conversation history, the more content must be submitted again for each call, increasing the load on the service.
3. Retry Strategy: Exponential Backoff and Jitter
Exponential backoff increases the waiting time after each failure and applies a maximum delay. Jitter adds randomness to the delay so that different clients do not retry simultaneously.
Common formulas include:
- Theoretical delay =
min(maximum delay, base delay × 2^retry attempt) - Actual delay = a random value between
0and the theoretical delay, using the full-jitter approach
The following example is independent of any particular service:
import randomimport timeRETRYABLE_STATUS = {429, 500, 502, 503, 504}def call_with_backoff(send_request, max_retries=5, base_delay=1.0, max_delay=30.0):"""Retry recoverable errors with exponential backoff and jitter."""for attempt in range(max_retries + 1):response = send_request()if response.status_code not in RETRYABLE_STATUS:return responseif attempt == max_retries:breakretry_after = response.headers.get("Retry-After")if retry_after and retry_after.isdigit():delay = float(retry_after) # Prefer the server-provided delayelse:ceiling = min(max_delay, base_delay * (2 ** attempt))delay = random.uniform(0, ceiling) # Full jitter spreads out retriestime.sleep(delay)raise RuntimeError("The request was rate-limited after multiple retries. ""Reduce the request rate or try again later.")
Keep the following design principles in mind:
- Honor
Retry-Afterfirst: The server’s recommended delay is generally more accurate than a client-side estimate. - Retry only recoverable errors: Retrying parameter errors such as 400, or authentication and authorization errors such as 401 and 403, will not help. Fix the underlying issue instead.
- Set a retry limit: Unlimited retries can consume threads and leave users waiting indefinitely.
- Log every retry: Retry records help identify failure patterns and determine whether the issue is caused by traffic, quotas, or service-side overload.
4. Client-Side Concurrency and Rate Control
Retries are a recovery mechanism. A better approach is to control the request rate before requests are sent. Two common techniques are concurrency limits and token-bucket rate limiting.
Concurrency Limits
Limit the number of requests that can be in progress at the same time. The following example uses a semaphore:
import threadingclass ConcurrencyGate:def __init__(self, limit: int):self._sem = threading.BoundedSemaphore(limit)def __enter__(self):self._sem.acquire()return selfdef __exit__(self, exc_type, exc, tb):self._sem.release()gate = ConcurrencyGate(limit=4)def guarded_call(send_request):with gate:return send_request()
Token-Bucket Rate Limiting
A token bucket adds tokens at a fixed rate. Each request consumes one token, and a request must wait when the bucket is empty. This allows small short-term bursts while limiting the long-term average rate.
The bucket capacity and refill rate should be based on the account quota and load-test results rather than arbitrary values.
Concurrency limits and rate limiting are often used together. The former protects local resources, while the latter controls the pace of outbound requests.
5. Reduce the Cost of Individual Requests
Reducing the workload of each request is one of the most direct ways to lower the probability of rate limiting.
- Trim the context: Keep system instructions and the most recent conversation turns. Summarize older content before sending it again. For a conversation with 64 messages, retain only key decisions and unfinished tasks when possible.
- Limit output length: Set a reasonable maximum output token count based on the use case to prevent unnecessarily long responses.
- Cache results: For identical inputs, reuse an existing result. Caching is often effective for queries with fixed parameters.
- Prioritize tasks: Process interactive requests first. Run offline batch jobs during low-traffic periods and order them in a queue.
Context reduction often provides the greatest benefit. Compressing tens of thousands of historical tokens into a few thousand can reduce the computation required for each inference call. Lower overall request costs also reduce the likelihood of rate limiting.
6. Degradation and Fallback Design
Even with proper retries and rate controls, service-side overload may continue for several minutes or longer. The application should still provide a reasonable result under these conditions.
- Backup models or nodes: Switch to a comparable fallback option when the primary model is unavailable. Record the model actually used so that quality differences can be evaluated later.
- Circuit breakers: After a threshold of consecutive failures, stop sending requests to the affected service for a cooling period. After the cooling period, send a small number of probe requests to check whether the service has recovered. This prevents the client from continuously consuming connections and threads during an incident.
- Asynchronous processing: For long-running tasks, accept the request and place it in a queue. Return the result later through polling or a callback so that the user does not have to wait inside one long-running request.
- Fallback content: For non-critical features, return a predefined message or a previously generated result to keep the main user flow available.
Fallback strategies should be designed in advance and tested regularly. Implementing them only after an incident begins often leaves important request paths uncovered.
7. Monitoring and Alerting
Without observability, it is difficult to determine whether a problem is isolated or persistent. At minimum, collect the following metrics:
- The proportion and trend of 429 responses and other error codes;
- The number of retries per request and the final success rate;
- Request latency at the P50, P95, and P99 percentiles;
- Local queue depth and concurrency utilization;
- The distribution of input and output tokens per request.
Alert thresholds should be based on historical baselines. For example, an alert may be appropriate when the proportion of 429 responses remains several times above normal, or when the final failure rate after retries continues to increase.
Logs should include request identifiers so that incidents can be correlated with provider support cases. Do not log API keys, personal information, or other sensitive data.
8. User Experience During Rate Limiting
Retries may be invisible at the technical level, but the way the application communicates the problem directly affects the user experience.
- Show a clear status message, such as “There is currently heavy traffic. The system is retrying automatically,” instead of displaying only the raw error code.
- Provide an estimated wait time or progress indicator to reduce repeated user clicks and the additional requests they create.
- Preserve user input and allow a one-click retry without requiring the user to enter the content again.
- For tasks that cannot be completed quickly, provide an option to check the result later.
9. Service Availability and Dependency Selection
Service-side overload directly affects applications that depend on the service. During provider selection, evaluate the following factors:
- Published rate-limit rules and quota documentation;
- Incident notification mechanisms and service status information;
- Availability commitments and compensation terms in the service agreement. Specific compensation rules should be determined from the agreement itself;
- The cost of migrating to or switching to a fallback solution.
For critical workloads, avoid concentrating every capability in a single service. Keep enough architectural flexibility to replace or add a provider when necessary.
10. Production Checklist
Use the following checklist when launching or optimizing an LLM API integration:
- Retry only recoverable errors such as 429 and 5xx responses;
- Use exponential backoff and jitter, while honoring
Retry-Afterwhen provided; - Set a maximum retry count and an overall timeout;
- Apply a local concurrency limit or rate limiter;
- Trim context when appropriate and define a clear output length limit;
- Provide a circuit breaker, fallback option, or fallback content;
- Monitor the 429 ratio, retry success rate, and latency percentiles;
- Give users clear feedback when requests are being rate-limited.
With these measures in place, an application can remain broadly available during short periods of service-side overload and automatically return to normal operation after the service recovers.
