LLM API Rate Limits: Retry Strategies and Capacity Management for HTTP 429
Learn how to handle LLM API rate limits with exponential backoff, jitter, Retry-After headers, and retry budgets. This article explains how inference capacity and long contexts contribute to overload, and outlines practical approaches to context reduction, fallback routing, traffic smoothing, monitoring, and quota planning.
1. Understand HTTP 429: A Flow-Control Signal, Not Necessarily a Failure
Developers often interpret HTTP 429 as a server failure. At the protocol level, however, 429—Too Many Requests—indicates that a request has exceeded the applicable rate or concurrency limit. It is a flow-control response, not necessarily evidence that the service is unhealthy.
Application-specific error codes such as code: 1305, accompanied by a message such as “This model is currently experiencing high traffic. Please try again later,” express the same condition through another layer. The gateway applies its rate-limiting policy and returns a structured error response to the client.
The important distinction is between error categories:
- 429 and 503: Generally retryable, but retries must use backoff. Immediate retries only increase congestion.
- 400, 401, and 403: Generally not retryable without correcting request parameters, authentication, or permissions.
- 500: Less specific. Inspect the error body; a small number of retries may resolve a transient problem.
In the example logs, three attempts failed at 0.37, 3.19, and 8.57 seconds, with waits of 2.2 and 4.8 seconds. This resembles exponential backoff, but lacks two important safeguards: jitter and an overall time budget, or deadline.
When many clients are rate-limited simultaneously, identical backoff schedules make them retry together. These synchronized bursts can create a retry storm, turning localized congestion into a much broader overload event.
2. Why LLM Inference Services Repeatedly Hit Capacity Limits
LLM inference differs substantially from a conventional stateless web service. Those differences make its overload behavior more abrupt.
GPU memory constrains capacity. Each concurrent request consumes memory for its KV cache. When available memory is exhausted, new requests must wait. If the queue exceeds its configured threshold, the gateway may return 429.
Long contexts amplify resource pressure. The example logs show a request containing 64 messages and approximately 43,303 tokens. Longer contexts increase prefill computation and cache usage, reducing the number of requests the service can support at a given concurrency level.
Traffic growth can outpace infrastructure expansion. A good product experience can rapidly increase users and API calls, while additional compute requires procurement and deployment time. Rate limiting is a predictable outcome during that supply-demand gap.
Traffic concentrates during peak periods. Demand during working hours and evening peaks can be several times higher than during quieter periods. Capacity planning based on averages cannot reliably cover those peaks.
The implication is straightforward: unlimited retries are not an availability strategy. Clients need to reduce the pressure created by individual requests while improving architectural redundancy.
3. Client-Side Retries: Backoff, Jitter, Server Guidance, and a Budget
A practical retry policy combines four elements:
- Exponential backoff
- Random jitter
- Respect for server retry guidance
- An overall retry time budget
The following example handles 429 responses:
import random, time, requestsdef call_with_backoff(session, url, payload,max_attempts=5,base=1.0, cap=30.0,deadline=60.0):start = time.monotonic()for attempt in range(max_attempts):resp = session.post(url, json=payload, timeout=30)if resp.status_code != 429:return resp# 1) Prefer the server's Retry-After guidanceretry_after = resp.headers.get("Retry-After")if retry_after and retry_after.isdigit():delay = float(retry_after)else:# 2) Exponential backoff with full jitter spreads out retriesdelay = random.uniform(0, min(cap, base * (2 ** attempt)))# 3) Check the retry budget before waitingif time.monotonic() - start + delay > deadline:raise TimeoutError("retry budget exhausted")time.sleep(delay)raise RuntimeError("rate limited after retries")
This example uses a numeric Retry-After value when available. Otherwise, it chooses a random delay between zero and the current exponential-backoff limit.
Supporting engineering rules are equally important:
- Classify errors before retrying. Retry 429, 503, and network timeouts as appropriate. Fail promptly and report parameter-related 4xx errors rather than repeating an invalid request. The example above implements only the 429 branch.
- Control retry amplification. If a call passes through three layers and each layer makes five attempts, the theoretical amplification can reach 125 calls. Centralize retry policy in the gateway or SDK rather than letting every layer retry independently.
- Make retries observable. Record
attempt,delay, and context token counts in structured logs so capacity problems can be traced to their causes.
4. Context Management: A Direct Way to Reduce Cost and Load
Long contexts are a major source of inference resource consumption. Reducing unnecessary context is therefore one of the most direct ways to relieve rate-limit pressure.
- Use a sliding window with layered summaries. Keep the most recent N conversation turns in their original form, and compress older history into structured summaries. This can reduce contexts from tens of thousands of tokens to a few thousand.
- Use retrieval-augmented generation (RAG). Retrieve the passages most relevant to the current question instead of putting all available material into the prompt.
- Reuse stable prefixes. Place stable system instructions and tool definitions at the beginning of the context to take advantage of prefix caching where supported.
- Stream responses. Streaming can improve perceived latency for long responses and help with response delivery, although it should not be treated as a substitute for reducing inference load.
- Combine and deduplicate requests. Use micro-batching for batch workloads and avoid frequent duplicate calls for the same content.
The following is an illustrative context-trimming routine:
def trim_messages(msgs, keep_recent=8, budget=8000):head, tail = msgs[:1], msgs[-keep_recent:]used = count_tokens(head + tail)summary = []for m in msgs[1:-keep_recent]:if used >= budget:breaksummary.append(m)used += count_tokens([m])return head + summary + tail
This sketch preserves the first message and a recent-message window, then includes older messages while checking the token budget. Despite the variable name summary, it selects messages rather than generating a compressed summary; it is an illustration of context selection, not a complete summarization implementation.
5. Platform and Architecture: Turn a Single Dependency into Routable Capacity
Client retries alone cannot solve persistent capacity shortages. Architecture-level controls make limited capacity easier to manage.
- Route across models or endpoints. When the primary route returns 429, switch to a backup endpoint or a smaller model according to a predefined priority. The goal is to keep the workflow available, even if the fallback does not deliver the preferred result.
- Use circuit breakers and graceful degradation. Repeated rate limiting should trigger a temporary pause in requests. Return cached results or simplified answers where appropriate, rather than continuing to send calls that are unlikely to succeed.
- Move non-real-time work to queues. Let consumers process queued tasks at a rate consistent with the quota. This trades additional delay for a higher success rate and smooths traffic spikes.
- Apply a local token bucket. Proactively limit client traffic to around 80% of the quota. This shifts rate-limit handling from reactive recovery toward prevention.
- Build monitoring and alerting. Track the rate-limit response rate, P95 latency, and token consumption in dashboards. Use threshold-based alerts to identify capacity bottlenecks early.
- Plan capacity and quotas around peaks. Estimate requirements from peak demand rather than average traffic. Reserve separate capacity or routes for batch workloads so they do not compete with interactive requests.
6. Implementation Checklist
- Do retries target only retryable errors, with jitter and an overall time budget?
- Does the client read and honor
Retry-After? - Is retry policy centralized to prevent amplification across multiple layers?
- Does context management combine recent-message windows, summaries, and retrieval?
- Are fallback routes, circuit breakers, graceful degradation, and queue-based traffic smoothing available?
- Are rate-limit responses and token consumption covered by monitoring and alerts?
- Are quotas planned for peak demand, with batch traffic isolated from interactive workloads?
HTTP 429 is not an obstacle to bypass. It is explicit feedback about a capacity boundary.
Keep retries restrained, contexts lean, and dependencies redundant. With those controls in place, rate limiting becomes less of an unpredictable incident and more of an observable, schedulable, and manageable operating condition.
