Designing Highly Available Large Language Model API Services: Fault Tolerance Practices
This article explores strategies for building highly available LLM API services and mitigating the impact of service disruptions. It covers fault characteristics, business impact paths, and core design principles such as timeout budgets, bounded retries with exponential backoff, circuit breakers, and multi-provider routing. Additionally, it provides a pseudo-code implementation, observability metrics, disaster recovery drills, and a comprehensive checklist to ensure system resilience.
1. Incident Background and Fault Characteristics
According to public reports, a large language model service experienced an anomaly on a weekday afternoon. When users initiated conversations on the web interface, they were prompted with “Server is busy, please try again later.” During the same period, both the web interface and the API of the service were affected. The service provider’s status page recorded an outage of about 1 hour and 49 minutes, after which it showed the service was restored.
This incident has three characteristics that developers should pay attention to:
- Both Web and API Affected Simultaneously: This usually indicates that they share the access layer, authentication layer, or backend inference cluster. Callers cannot assume “if the web interface is available, the API must be available,” nor can they assume their failures are independent.
- “Server Busy” Prompts Usually Indicate Capacity or Rate Limiting Issues: Such errors often manifest as request queuing, timeouts, or rate-limiting status codes, rather than direct connection refusals.
- Partial Outages Are Harder to Detect Than Complete Downtime: Not all requests fail; only a portion times out or returns errors. If health checks only probe a lightweight interface, they may miss the real business impact.
It should be noted that public information did not specify the root cause. This article does not speculate on the specific cause, but only discusses the designs and response strategies that callers can control.
2. Business Impact Path of the Outage
An external service outage typically amplifies its impact along the following path, where each layer requires individual protection design.
User Side: Conversations or generation tasks fail, causing users to manually retry repeatedly, which further increases pressure on the service.
System Side: The caller’s worker threads or connection pools are occupied by slow requests, slowing down the system even if other functions are unrelated to the service. More seriously, a large number of clients retrying simultaneously can form a “retry storm,” overloading the recovering service again.
Business Side: Processes relying on model outputs, such as content moderation, customer service responses, document generation, and code assistance, will stall entirely. If the process lacks a degradation plan, the cost of manual intervention rises rapidly.
Therefore, the focus of high availability design is not to ensure that external services never fail, but to confine failures within a controllable range and recover as quickly as possible.
3. Core Principles of High Availability Design
3.1 Assume External Dependencies Will Fail
Callers should treat external model services as unstable dependencies. Every call must anticipate a possible timeout, rate limit, or returned error. During design, you need to answer three questions: what to do on failure, when to give up, and what result to give the user after giving up.
3.2 Set a Clear Timeout Budget
Timeouts are divided into connection timeouts and read timeouts. Model generation takes a long time, so the read timeout needs to be set specifically according to the business scenario and cannot follow the default values of general interfaces. At the same time, a total timeout budget should be set for the entire business request and distributed across multiple retries to prevent a single user request from occupying too much time.
3.3 Bounded Retries with Exponential Backoff and Jitter
Retries are only suitable for temporary errors, such as timeouts, rate-limiting status codes, and server-side internal errors. Retrying permanent errors like parameter errors or authentication failures is meaningless and should return directly.
Retries should meet the following requirements:
- Set a maximum number of retries, usually 2 to 3 times.
- Backoff time should grow exponentially, with random jitter added to prevent a large number of clients from retrying at the same moment.
- Be cautious with non-idempotent operations. If generation requests have already been billed or results written on the server side, retries may cause duplicate charges or data. Deduplication must be handled via request identifiers.
3.4 Circuit Breaking and Degradation
The role of a circuit breaker is to pause calls when a dependency continuously fails, giving the service time to recover while preventing the caller’s resources from being exhausted. Its states are generally divided into three:
- Closed State: Requests pass normally, and failures are counted.
- Open State: When failures exceed the threshold, requests are directly rejected and degraded logic is applied.
- Half-Open State: After a cooldown period, a small number of probe requests are allowed. If probes succeed, the circuit closes; if they fail, it remains open.
Degradation is the specific behavior after the circuit breaker opens. Common practices include: returning cached historical results, putting tasks into a queue for later processing, giving users clear prompts and retaining drafts, or switching to rule-based fallback logic.
3.5 Multi-Provider and Multi-Model Routing
A single dependency always carries a single point of failure risk. A more prudent approach is to build a unified model invocation abstraction layer that hides specific provider interface differences from the upper-layer business. The routing layer can distribute requests to different model services based on health, latency, and cost.
When implementing, note the following:
- Different models may vary in output format, length limits, and prompt performance. Regression testing with real business samples is required before switching.
- Backup services should undergo periodic low-traffic validation; otherwise, discovering they are unavailable only during a failure renders routing meaningless.
- Confirm the data processing terms and compliance requirements of each service to avoid unintentionally changing data flow during a switch.
4. Illustrative Implementation: Combining Timeout, Retry, and Circuit Breaking
Below is a piece of pseudo-code demonstrating how the three mechanisms work together. send, fallback, TransientError, and PermanentError need to be implemented according to your specific project.
import randomimport timeclass CircuitBreaker:def __init__(self, failure_threshold=5, reset_timeout=30.0):self.failure_threshold = failure_thresholdself.reset_timeout = reset_timeoutself.failures = 0self.opened_at = Nonedef allow(self, now):if self.opened_at is None:return True# Enter half-open state after cooldown to allow a probe requestreturn now - self.opened_at >= self.reset_timeoutdef record_success(self):self.failures = 0self.opened_at = Nonedef record_failure(self, now):self.failures += 1if self.failures >= self.failure_threshold:self.opened_at = nowdef call_with_resilience(send, payload, breaker,max_retries=3, base_delay=0.5, timeout_s=10.0):if not breaker.allow(time.monotonic()):return fallback(payload) # Circuit breaker open, fallback directlyfor attempt in range(max_retries + 1):try:response = send(payload, timeout=timeout_s)breaker.record_success()return responseexcept TransientError:# Timeout, rate limit, or server error: record failure and retry with backoffbreaker.record_failure(time.monotonic())if attempt == max_retries:breakdelay = base_delay * (2 ** attempt) + random.uniform(0, base_delay)time.sleep(delay)except PermanentError:# Parameter or auth error: retry is meaningless, raise directlyraisereturn fallback(payload) # Retries exhausted, take fallback path
When implementing, also note the following points:
- If the circuit breaker state is not shared across multiple processes or instances, each instance will judge independently, and behaviors may be inconsistent. Whether a centralized state is needed depends on the deployment scale.
- The sum of retries and timeouts must be less than the user’s acceptable waiting time. For example, with a single timeout of 10 seconds and 3 retries, the user might wait over 40 seconds, which usually exceeds the tolerance for interactive scenarios.
- Degraded results must be clearly marked at the business layer to avoid presenting cached content or fallback results as real-time generation results.
5. Observability: Detecting Outages Early
The premise of high availability design is the ability to see anomalies promptly. It is recommended to monitor at least the following metrics:
- Success Rate: Statistics broken down by interface, model, and business scenario, not just overall averages.
- Latency Percentiles: Focus on P95 and P99, as average latency may mask prolonged waits for some requests.
- Error Code Distribution: Differentiate between timeouts, rate limits, server errors, and client errors, as their response strategies differ.
- Retry Ratio and Circuit Break Counts: A sudden spike in retry ratio is often an early signal of a failure.
- Degradation Ratio: When degraded requests increase, business owners should be notified simultaneously.
Alert thresholds should be set based on historical baselines, distinguishing between “persistent alerts” and “spike alerts.” Meanwhile, it is recommended to subscribe to dependency service status notifications and cross-check the external status page information with internal monitoring to determine whether the problem lies on your end or the other end.
6. Drills and Runbooks
No matter how complete the design, it is difficult to take effect in a real outage without drills. It is recommended to regularly perform the following:
- Fault Injection Drills: Simulate timeouts, rate limits, and connection interruptions in a test environment to verify that circuit breaking and degradation trigger as expected.
- Degradation Path Drills: Confirm that fallback pages, caches, and queuing logic work without throwing errors due to missing dependencies.
- Runbook Maintenance: Document alert meanings, troubleshooting steps, switch locations, and operators to ensure on-call staff can execute quickly under pressure.
- Post-Mortems: After each outage, record the impact scope, time to detect, time to recover, and improvement items, and track their implementation.
7. Checklist
- All external model calls have connection and read timeouts set.
- Business requests have a total timeout budget, including retry time.
- Retries are only applied to transient errors, using bounded exponential backoff with jitter.
- Non-idempotent generation requests have deduplication identifiers.
- The circuit breaker has clear thresholds, cooldown times, and half-open probe logic.
- Every core function has a corresponding degradation plan, validated in testing.
- Model invocations go through a unified abstraction layer, keeping the cost of switching backup services controllable.
- Backup services undergo periodic low-traffic validation, and data compliance requirements are confirmed.
- Monitoring covers success rate, latency percentiles, error codes, retry, and degradation ratios.
- Runbooks and fault drills are institutionalized and updated regularly.
High availability is not a one-time configuration, but a continuous combination of dependency assumptions, timeout strategies, fault tolerance mechanisms, and observation methods. Incorporating the uncertainty of external services into your design ensures that the impact is controlled within an acceptable range the next time an outage occurs.
