High Availability for LLM APIs: Backoff, Circuit Breaking, and Failover Practices
This article examines the engineering challenges of keeping large language model (LLM) APIs highly available when rate limits and capacity constraints cause 429 errors and timeouts. It explains why blind retries make congestion worse, then provides production-ready retry code with exponential backoff, jitter, and Retry-After handling. It also covers circuit breaker design, fallback strategies, multi-node failover with dynamic routing, and the observability metrics needed to tune parameters over time. Readers will learn how to combine retries, circuit breaking, degradation, and failover so that services remain stable even when compute resources are scarce.
Large language model APIs frequently return 429 rate-limit errors or timeouts during peak business hours. Many teams respond by increasing the retry count, which only makes requests pile up and extends cooling-off periods. This article takes an engineering perspective on rate limiting, provides retry code that can be deployed directly, and explains how circuit breaking, degradation, and multi-node failover work together to keep services stable when compute resources are tight.
1. Why Blind Retries Fail Under Rate Limiting
LLM inference depends on GPU and other compute resources, so it cannot simply be scaled horizontally like an ordinary web service to increase throughput immediately. To protect compute clusters, service providers typically set quotas based on RPM (requests per minute) and TPM (tokens per minute), and they control traffic using token bucket or leaky bucket algorithms. When a quota is exceeded, the server returns 429 Too Many Requests. Some services also include a Retry-After response header that tells the client how many seconds to wait before sending another request.
If the client ignores Retry-After and keeps sending requests during the cooling-off period, those requests will almost certainly fail again, consume quota, and in severe cases may trigger stricter blocking policies. Therefore, the first principle of retry is: the wait time must not be shorter than the value suggested by the server.
Different providers use inconsistent formats for rate-limit information. Some return only 429 without headers, while others return remaining RPM and TPM quotas. Clients should encapsulate these differences in an adapter layer rather than scattering them across business logic.
2. Retry Mechanism: Follow Server Guidance and Classify Errors
A simple while(true) loop makes congestion worse. A more reasonable approach has three parts.
First, use exponential backoff. After each failure, double the wait time—for example, 1 second, 2 seconds, 4 seconds—and set a per-attempt backoff cap to prevent unbounded waiting.
Second, add random jitter. If many instances are rate-limited at the same moment, they will all retry at the end of the same backoff period, creating a second wave of congestion known as the thundering herd effect. Adding a random offset to the backoff time spreads out these requests.
Third, classify errors. 429, 500, 502, 503, 504, timeouts, and connection interruptions are retryable errors. Problems such as 400, 401, and 403 originate in the request itself; retrying only wastes quota, so these should fail immediately.
The following code implements these three points.
import randomimport timefrom datetime import datetime, timezonefrom email.utils import parsedate_to_datetimeimport requestsRETRYABLE_STATUS = {429, 500, 502, 503, 504}BASE_DELAY = 1.0 # Initial backoff in secondsMAX_BACKOFF = 30.0 # Per-attempt backoff cap in secondsMAX_ATTEMPTS = 5 # Maximum attempts, including the first requestTOTAL_BUDGET = 60.0 # Total time budget for the entire call in secondsdef parse_retry_after(value):"""Support both Retry-After formats: integer seconds or HTTP-date. Return seconds."""if not value:return Nonetry:return float(value)except ValueError:passtry:target = parsedate_to_datetime(value)if target.tzinfo is None:target = target.replace(tzinfo=timezone.utc)return max(0.0, (target - datetime.now(timezone.utc)).total_seconds())except (TypeError, ValueError):return Nonedef backoff(attempt):"""Exponential backoff with random jitter in half of the interval (equal jitter)."""exp = min(MAX_BACKOFF, BASE_DELAY * (2 ** attempt))return exp / 2 + random.uniform(0, exp / 2)def call_llm_api(url, payload, headers=None):start = time.monotonic()last_error = Nonefor attempt in range(MAX_ATTEMPTS):try:resp = requests.post(url, json=payload, headers=headers, timeout=(3, 60))except requests.exceptions.RequestException as exc:# Network exceptions such as timeouts and connection interruptions can be retriedlast_error = excwait = backoff(attempt)else:if resp.status_code == 200:return resp.json()if resp.status_code not in RETRYABLE_STATUS:# Problems such as 400, 401, and 403 originate in the request itself; retrying is pointlessraise RuntimeError(f"Non-retryable status code: {resp.status_code}")last_error = f"HTTP {resp.status_code}"server_wait = parse_retry_after(resp.headers.get("Retry-After")) or 0.0# Wait time must not be shorter than the server's Retry-After, with a small jitter addedwait = max(server_wait + random.uniform(0, 1), backoff(attempt))is_last = attempt == MAX_ATTEMPTS - 1over_budget = time.monotonic() - start + wait > TOTAL_BUDGETif is_last or over_budget:breaktime.sleep(wait)raise RuntimeError(f"API call failed, last error: {last_error}")
Code notes: Retry-After can be either integer seconds or an HTTP-date format (e.g., Wed, 25 Nov 2026 05:30:00 GMT), and parse_retry_after handles both. The wait time takes the larger of the server-suggested value (plus a random offset of 0 to 1 second) and the backoff value, so it is never shorter than Retry-After. The timeout uses a tuple to limit connection time (3 seconds) and read time (60 seconds) separately, because LLM responses are inherently slow when generating long text. call_llm_api also sets a total time budget; if the next wait would exceed the budget, the function gives up immediately and returns control to the upper-layer fallback logic.
This code depends on the requests library, which can be installed with pip install requests. MAX_ATTEMPTS and TOTAL_BUDGET should be determined based on business SLAs. For example, if a user-facing synchronous interface has a maximum acceptable wait of 20 seconds, the budget should not be set to two minutes. User-facing synchronous requests usually keep retries to three or fewer; background batch processing can increase the count appropriately but should be used with a task queue.
3. Circuit Breaker: When to Stop Retrying
When retries reach the maximum and still fail, the server is likely unavailable as a whole for a period of time. Letting every request retry on its own is ineffective and slows down upstream business logic. A circuit breaker exists to fail fast in this situation and protect the system itself.
A circuit breaker has three states: closed, open, and half-open. In the closed state, requests are sent normally and results are recorded. When the failure rate exceeds a threshold, the breaker moves to the open state, where requests are rejected directly without calling the remote API. After a cooling-off period, it enters the half-open state and allows a small number of probe requests. If all probes succeed, it returns to closed; if any fails, it reopens.
The following thresholds can serve as a starting point and should be adjusted based on production data:
- Statistics window: 60 seconds.
- Minimum request count: 20. Below this number, the failure rate is not calculated, avoiding circuit breaking due to occasional failures at very low traffic.
- Failure rate threshold: 50%. Failure statistics include 429, 5xx, and timeouts.
- Open duration: 30 seconds.
- Half-open probe requests: 3, and the breaker closes if all succeed.
These numbers are not universal standards; they depend on request volume, quota size, and users’ tolerance for errors. Low-traffic services can increase the minimum request count, while high-traffic services can shorten the statistics window.
A key point in combining circuit breakers with retries is that the circuit breaker should count the final result of a complete call, not each internal retry. Otherwise, a single request that retries five times would be counted as five failures, causing the breaker to trip quickly and distorting the statistics. When the breaker is open, the caller should skip retries entirely and enter the fallback flow.
4. Fallback: What to Return to Users During Circuit Breaking
During circuit breaking, the system should not simply return a 500 error to users. There are three common fallback approaches.
Cache fallback: For common or template-based questions, return a previously cached answer. The cache key should include the user or tenant identifier, model version, and prompt template version; otherwise, one user’s answer could be returned to another user, causing a data leak. Content involving personal information or sensitive business data should not enter a shared cache.
Lightweight substitution: Route the request to a smaller, faster model, or hand it to a rules engine for fixed workflows such as checking order status or returning a standard form. Output quality will decrease, and the product should inform users in advance.
Friendly message: When none of the above is available, show a clear message such as “We are experiencing high traffic. Please try again later,” and preserve the user’s input so they can continue later.
5. Multi-Node Failover and Dynamic Routing
A single model node cannot achieve 100% availability, so a highly available architecture needs multiple substitutable inference sources. A common approach is to add a unified gateway between business code and model services, abstracting different vendors or deployments behind the same interface.
Primary-backup failover requires clear decision points.
Health checks: Periodically send lightweight probe requests while also tracking the 429 rate and timeout rate of real business calls. Relying only on heartbeat checks often fails to reflect rate-limit status, because a node may still be alive but have exhausted its quota.
Failover conditions: For example, if the 429 rate exceeds 20% for 30 consecutive seconds, or if P95 latency exceeds a configured threshold, shift part of the traffic to the backup node. Failover should be performed in batches to avoid overwhelming the backup node instantly.
Rollback strategy: After the primary node recovers, do not switch all traffic back immediately. Increase traffic gradually at 5%, 20%, 50%, and 100%, observing the error rate at each stage.
Data consistency: Different models differ in output style, format, and capability. If the business depends on structured output after failover, validation should be performed at the gateway or business layer. On validation failure, retry or fall back rather than returning malformed output directly to users.
6. Observability: Using Metrics to Decide When to Act
Without monitoring, all backoff and circuit breaker parameters are guesses. At a minimum, record the following metrics:
- 429 rate: calculated per minute. A sustained increase indicates insufficient quota or a sudden traffic spike.
- Retry count distribution: if the average retry count approaches the limit, the backoff strategy can no longer absorb traffic.
- P95 and P99 latency: tail latency often rises before the error rate does.
- Circuit breaker state: number of open events and duration.
- Fallback ratio: the share of requests served by cache or substitution.
Alert thresholds can start conservatively—for example, trigger an alert when the 429 rate exceeds 10% for five consecutive minutes, or when the circuit breaker has been open for more than two minutes. Thresholds should be set against historical baselines to avoid excessive alerts.
If deployed on a container or cloud platform, load metrics can also be used for auto-scaling. However, LLM inference nodes take a long time to start and load weights, so scaling should be predicted in advance rather than relying only on real-time metrics.
General capabilities such as rate limiting, routing, and monitoring are often available from cloud provider API gateways and container platforms. Whether to use them depends on team size, existing technology stack, and cost. A self-built gateway suits teams with special routing requirements, while managed services reduce operational overhead.
7. Summary
Stability issues with LLM APIs are essentially the combined result of quotas, compute capacity, and client behavior. The response can be summarized in three steps: respect Retry-After during retries and use exponential backoff with jitter to reduce congestion; use a circuit breaker to stop losses during sustained failures; and use fallback and multi-node failover to ensure users still receive a usable result. All parameters need to be continuously calibrated against production metrics; there is no one-time configuration that remains effective forever.
