LLM API Rate Limits: Causes of HTTP 429 Errors and Practical Solutions
Learn why LLM APIs return HTTP 429 errors and how to handle them with exponential backoff, concurrency limits, request throttling, and token usage controls. This guide also covers fallback strategies, monitoring, and working with API providers to manage persistent rate limits.
1. Understanding HTTP 429 in LLM APIs
HTTP 429 (Too Many Requests) indicates that a client has sent more requests within a given period than the server allows. Defined in RFC 6585, it is a standard signal for rate limiting. Because large language model inference is computationally expensive and resources are finite, providers commonly limit concurrent requests, requests per minute (RPM), and tokens per minute (TPM). As a result, 429 errors are particularly common in LLM services.
Developers encountering a 429 error for the first time may mistake it for a service outage. In practice, it usually means the service is operating but the current workload exceeds a quota or available capacity. The appropriate response is to reduce the request rate, wait before retrying, and build fault tolerance into the application.
This guide is intended for application developers troubleshooting rate limits and for architects and operations teams responsible for system reliability. It explains the main causes, then covers client-side controls and system-level responses.
2. Common Causes of Rate Limiting
Understanding where a limit comes from helps determine the right response.
2.1 Quotas and Rate Limits
Providers typically apply quotas at the account, API key, or organization level. Common dimensions include:
- Requests per second (QPS) or requests per minute (RPM).
- Tokens processed per minute (TPM), including input and output.
- Concurrent requests in progress.
- Total daily or monthly usage.
Exceeding a limit can trigger a 429 response, depending on the provider’s error conventions. TPM is especially easy to overlook: a few requests with long contexts can exhaust a token allowance even when request counts remain low.
2.2 Server Capacity Saturation
When total traffic exceeds the service cluster’s capacity, a provider may throttle requests across users. Error messages may simply indicate that the service is busy and ask clients to try again later.
This type of throttling is unrelated to an individual account’s quota. It often occurs during short traffic spikes, shortly after a model launch, or in response to sudden demand.
Latency and error rates may rise at the same time. Clients should distinguish capacity saturation from account-level limits because recovery times and appropriate responses can differ.
2.3 Client Traffic Patterns
Many rate-limit problems originate in client design. Examples include:
- Starting hundreds of threads simultaneously for a batch job.
- Sharing one API key across multiple service instances, each tracking its own rate without accounting for aggregate usage.
- Retrying immediately after failures, amplifying traffic as retries accumulate.
- Allowing repeated UI clicks to trigger separate model calls.
These patterns concentrate requests into bursts rather than distributing them over time. Smoothing traffic is often more effective than simply requesting a higher quota.
3. Distinguishing 429 Errors from Other Failures
An effective response starts with accurate error classification.
| Status code | Meaning | Recommended action |
|---|---|---|
| 400 | Invalid request parameters | Correct the request; do not retry it unchanged |
| 401 / 403 | Authentication failure or insufficient permissions | Check credentials and permissions; do not retry unchanged |
| 429 | Request limit exceeded | Back off before retrying and reduce the request rate |
| 500 / 502 / 503 / 504 | Server error or gateway timeout | Retry a limited number of times; use a fallback if necessary |
Some services place application-specific error codes in the response body while returning HTTP 200 or a generic 4xx status. The response parser should therefore inspect both the HTTP status and the error fields in the body.
Also check the Retry-After response header. It may specify either a delay in seconds or an HTTP date. When provided, clients should follow that value rather than blindly applying a fixed retry schedule.
4. Client Retries: Exponential Backoff and Jitter
Retries are the most direct response to a 429 error, but immediate retries can increase pressure on the service. The recommended approach is exponential backoff with random jitter.
- Exponential backoff: Increase the delay after each failure, for example from 1 second to 2 seconds to 4 seconds, up to a configured limit.
- Jitter: Randomize the delay so that many clients do not retry simultaneously and create another traffic spike.
- Bounded retries: Set a maximum backoff interval and retry count to prevent indefinite waiting from exhausting the calling workflow.
- Idempotency: Confirm that repeating a request is safe. LLM calls are typically queries without side effects, but repeated attempts may still consume quota and should be considered when estimating costs.
The following Python example uses requests to handle 429 responses and selected 5xx errors:
import randomimport timeimport requestsRETRYABLE_STATUS = {429, 500, 502, 503, 504}def post_with_backoff(url, payload, headers,max_retries=4, base_delay=1.0, max_delay=30.0):"""Retry rate limits and transient server errors with exponential backoff."""for attempt in range(max_retries + 1):try:resp = requests.post(url, json=payload, headers=headers, timeout=60)except requests.RequestException:resp = Noneif resp is not None and resp.status_code not in RETRYABLE_STATUS:return resp # Success or a non-retryable HTTP errorif attempt == max_retries:breakretry_after = resp.headers.get("Retry-After") if resp is not None else Noneif retry_after and retry_after.isdigit():delay = float(retry_after)else:ceiling = min(max_delay, base_delay * (2 ** attempt))delay = random.uniform(0, ceiling) # Full jittertime.sleep(delay)raise RuntimeError("Retry limit exhausted; the request did not succeed")
The key points are to retry only selected HTTP status codes, respect a server-provided delay, and spread retries using jitter. This example also retries request exceptions and handles the numeric form of Retry-After; an HTTP-date value requires parsing before it can be used as a delay.
5. Request Controls: Preventing Limits Before They Occur
Retries are reactive. A more reliable approach is to control traffic before sending requests so that usage stays within the applicable limits.
5.1 Limit Concurrency
Limiting the number of requests in progress is one of the simplest and most effective controls. A semaphore can enforce that limit:
import threadingfrom concurrent.futures import ThreadPoolExecutorMAX_CONCURRENCY = 8_semaphore = threading.BoundedSemaphore(MAX_CONCURRENCY)def limited_call(fn, *args, **kwargs):with _semaphore:return fn(*args, **kwargs)def run_batch(tasks, fn):with ThreadPoolExecutor(max_workers=MAX_CONCURRENCY) as pool:futures = [pool.submit(limited_call, fn, *t) for t in tasks]return [f.result() for f in futures]
Using the same limit for the thread pool and semaphore bounds the number of simultaneous calls in this batch. Choose the concurrency limit based on the provider’s published quotas and observed behavior rather than guesswork.
5.2 Apply Token-Bucket Rate Limiting
Concurrency controls answer “How many requests can be active at once?” A token bucket answers “How many requests can be sent per second?”
The bucket refills at a fixed rate, and each request consumes one token. It allows a controlled burst while limiting the long-term average request rate.
import threadingimport timeclass TokenBucket:def __init__(self, rate_per_sec, capacity):self.rate = rate_per_secself.capacity = capacityself.tokens = capacityself.updated = time.monotonic()self.lock = threading.Lock()def acquire(self):while True:with self.lock:now = time.monotonic()elapsed = now - self.updatedself.tokens = min(self.capacity, self.tokens + elapsed * self.rate)self.updated = nowif self.tokens >= 1:self.tokens -= 1returnwait = (1 - self.tokens) / self.ratetime.sleep(wait)bucket = TokenBucket(rate_per_sec=5, capacity=10)def send_request(payload):bucket.acquire()# Call the actual API here
For a per-minute limit, convert the refill rate to a per-second value. If both RPM and TPM limits apply, use separate buckets for requests and model-token usage. A request must obtain sufficient allowance from both before it is sent; the TPM bucket must account for token volume rather than simply deducting one unit per request.
5.3 Reduce Request Size
Under a TPM limit, the size of each request directly affects quota consumption. Useful controls include:
- Retain only conversation history relevant to the current task, and summarize earlier turns.
- Rerank retrieval-augmented generation results and include only the most relevant passages.
- Set a reasonable maximum number of generated tokens.
- Cache results for repeated or similar requests so that cache hits do not require another API call.
Set cache expiration policies and separate private user data from shared data to avoid exposing sensitive information.
5.4 Use Queues for Batch and Asynchronous Work
Tasks that do not require an immediate response can be placed in a message queue and processed by consumers at a controlled rate. During a brief rate-limit event, tasks then wait longer instead of failing immediately.
Design queue depth, processing rate, and timeouts together. Provide a way to requeue timed-out tasks or route them for manual handling.
6. Graceful Degradation and Failover
Even with client-side rate controls, capacity constraints can cause prolonged throttling. Define fallback paths in advance so that core functionality remains available.
- Alternative models: Configure a comparable backup model or region for critical workflows. Validate output quality before switching to avoid affecting business results.
- Rule-based fallbacks: Use rules or response templates for structured problems with a limited set of possible answers.
- Cached responses: Return the most recent successful result and clearly indicate its age.
- Feature prioritization: Temporarily disable nonessential features, such as automatic summaries or suggested copy, while preserving the main workflow.
- Clear user messaging: Explain that demand is high and provide an estimated wait time or a retry option rather than exposing a raw error code.
Test degradation strategies regularly. Injecting simulated 429 responses can help verify that circuit breakers, failover, and alerts behave as expected.
7. Observability and Alerting
Without monitoring, teams may not discover rate-limit problems until users report them. At a minimum, collect:
- Request counts by status code, with particular attention to the proportion of 429 responses.
- Retry-count distributions and final failure rates.
- Time spent waiting in local queues.
- P50, P95, and P99 end-to-end latency.
- Usage broken down by API key and service instance to identify abnormal traffic sources.
One alerting approach is to trigger when the 429 rate exceeds a multiple of its historical baseline over a five-minute window, while also checking whether final retry failures are increasing. Set thresholds from historical data rather than applying arbitrary fixed values.
Logs should include request identifiers, retry counts, and wait durations, but should not contain complete user prompts or sensitive information.
8. Working with the API Provider
For persistent rate limiting, technical controls can reduce the impact but may not resolve the underlying constraint. In that case:
- Review the provider’s quota documentation, service-level agreement, and billing terms to confirm the limits that apply to the account.
- Request a quota increase when needed, supported by realistic traffic forecasts.
- Retain incident timestamps, request identifiers, and error responses to help the provider investigate.
- Monitor provider announcements and adjust request strategies ahead of expected demand peaks or model upgrades.
For billing or compensation questions, rely on the provider’s formally published terms rather than assumptions.
9. Summary and Deployment Checklist
HTTP 429 is an expected signal that a system should be designed to handle, not automatically treated as an outage. Use this checklist before deployment:
- Distinguish 429 responses from other 4xx and 5xx errors, and handle them appropriately.
- Use exponential backoff with jitter and bounded retries.
- Honor the
Retry-Afterresponse header. - Control concurrency and request rates in line with applicable quotas.
- Trim long contexts to avoid rapidly exhausting TPM allowances.
- Configure caching, queues, or graceful degradation paths.
- Monitor 429 rates, retry counts, and queue wait times.
- Regularly test failure scenarios.
Treating rate limits as a routine system-design constraint rather than an exceptional incident can substantially reduce their impact on production workloads.
