Engineering Postmortem of LLM Service Outages and Resilience Design

    Large language models have become a core dependency for many products, so service interruptions now propagate quickly along the business chain. This article analyzes a typical outage scenario using hypothetical data, traces the failure chain from traffic spikes to cascading collapse, and presents engineering practices for capacity planning, rate limiting, circuit breaking, degradation, multi-backend fallback, client-side retry control, cost-performance trade-offs, and observability. All figures are illustrative and do not correspond to any real service.

    1. Background and Problem Definition

    Over the past year or two, large language models have evolved from experimental features into core dependencies of many products. Users call model services daily for conversation, code generation, and document processing. Once the service goes down, the impact spreads rapidly along the business chain. Public incident reports of this kind usually share similar characteristics: multiple service anomalies within a period of time, sometimes continuous interruptions, with users reporting long periods of no response, “server busy” messages, conversation pages failing to return results, and abnormal API responses.

    Such incidents are rarely caused by a single factor. To make the analysis concrete, consider a set of hypothetical data: suppose a service’s active users grew by about 60% in one quarter, while available compute capacity grew by only about 10%. When demand grows far faster than supply, queuing, timeouts, and resource contention during peak hours are inevitable. This is a classic supply-demand imbalance.

    Note that the numbers below are used only to illustrate the mechanism and do not correspond to any real service.

    The essence of the problem can be summarized in three points:

    1. Capacity planning lags behind business growth, and peak load exceeds the design limit.
    2. The system lacks protection mechanisms, so failures propagate upstream and downstream under overload.
    3. Critical paths have single points of dependency, so one component failure can bring down the entire service.

    Understanding these three points is the starting point for all the design decisions that follow.

    2. Failure Chain Analysis

    Large-scale service interruptions rarely happen instantly. They usually follow a traceable chain:

    1. Traffic spike: Request volume in a given period exceeds the average by several times, for example due to a promotional campaign, a new feature launch, or concentrated access triggered by a trending event.
    2. Queue buildup: Once inference resources are fully occupied, new requests enter a queue and wait times keep growing.
    3. Timeout and retry amplification: Clients automatically retry after timeouts. Each failed request becomes two, three, or more requests, multiplying the load.
    4. Resource exhaustion: GPU memory, connections, threads, or memory on inference instances are exhausted one after another, and even healthy instances start failing.
    5. Avalanche: Upstream services keep waiting for downstream responses, threads and connections are fully occupied, and the failure spreads from a local area to the entire system.

    Retry amplification is the most easily underestimated link. A minor jitter, combined with a client retry strategy that uses fixed intervals and no upper limit, can push a system from “elevated pressure” to “completely unavailable.”

    Another common error is “session length exceeds the limit.” It is related to capacity, but its root cause is state management. In multi-turn conversations, historical context keeps accumulating, and the input length and compute cost of each request grow accordingly. If the server does not manage session length transparently — for example through automatic truncation, summary compression, or prompting the user to start a new session — users only see an incomprehensible error.

    Therefore, failure analysis should cover three dimensions simultaneously: the source of load, the way resources are consumed, and the way state grows.

    3. Capacity Planning: Deriving Resources from Peak Demand

    The goal of capacity planning is to ensure that the system maintains acceptable latency and success rates under reasonable peak traffic. A common approach is to estimate peak request volume, combine it with the average resource consumption per request, derive the required compute capacity, and reserve a safety margin.

    A simplified estimation model:

    Required capacity = peak requests per second × average consumption per request ÷ throughput per resource unit × safety factor

    For LLM services, per-request consumption is usually measured in generated tokens or total input plus output tokens. The safety factor is typically 1.2 to 1.5, depending on business volatility and scaling speed.

    1. def required_capacity(peak_qps: float,
    2. avg_tokens_per_request: float,
    3. tokens_per_sec_per_unit: float,
    4. safety_factor: float = 1.3) -> float:
    5. """Estimate the number of compute units needed at peak load."""
    6. if tokens_per_sec_per_unit <= 0:
    7. raise ValueError("Throughput per unit must be greater than 0")
    8. demand_tokens_per_sec = peak_qps * avg_tokens_per_request
    9. return demand_tokens_per_sec / tokens_per_sec_per_unit * safety_factor
    10. # Example: peak 200 QPS, 800 tokens per request on average,
    11. # a single compute unit processes 5000 tokens per second
    12. units = required_capacity(200, 800, 5000)
    13. print(f"Recommended compute units: {units:.1f}")

    Key considerations for capacity planning:

    • Peaks should be measured at minute or even second granularity, not just daily averages. Daily averages hide bursts.
    • Growth forecasts should consider both user count and per-user usage frequency. Growing users with declining per-user usage affects resources very differently from rising per-user usage with a flat user base.
    • Scaling has a delivery lead time. The forecast window must cover the entire period from decision to resource readiness; otherwise, even an accurate forecast arrives too late.
    • Cost and capacity should be evaluated together. Changes in per-token cost directly affect the economics of scaling and should be factored into planning.

    4. Architecture Design: Keeping the System Controllable Under Overload

    Capacity planning only reduces the probability of overload; it cannot eliminate it. The system must therefore remain controllable when overload occurs. Common techniques include rate limiting, queuing for load smoothing, circuit breaking, degradation, and multi-backend fallback.

    4.1 Layered Rate Limiting

    The purpose of rate limiting is to reject requests that exceed carrying capacity at the entry point, preventing them from reaching inference resources. The token bucket is a common algorithm: it allows short bursts while limiting the long-term average rate.

    1. import threading
    2. import time
    3. class TokenBucket:
    4. """Token bucket rate limiter. rate is tokens refilled per second,
    5. capacity is the bucket size."""
    6. def __init__(self, rate: float, capacity: float):
    7. self.rate = rate
    8. self.capacity = capacity
    9. self.tokens = capacity
    10. self.updated_at = time.monotonic()
    11. self.lock = threading.Lock()
    12. def acquire(self, cost: float = 1.0) -> bool:
    13. with self.lock:
    14. now = time.monotonic()
    15. elapsed = now - self.updated_at
    16. self.tokens = min(self.capacity, self.tokens + elapsed * self.rate)
    17. self.updated_at = now
    18. if self.tokens >= cost:
    19. self.tokens -= cost
    20. return True
    21. return False

    Rate limits can be set along multiple dimensions: global total, per tenant, per user, and per endpoint. The benefit of layering is that abnormal traffic from one tenant does not consume other tenants’ quotas. For LLM services, request count and token count can also be limited separately, because a long request may consume dozens of times the resources of a short one.

    When a request is rate-limited, the service should return a clear status code and a retry-after interval rather than simply dropping the connection, so that clients can react correctly.

    4.2 Circuit Breaking and Degradation

    A circuit breaker temporarily stops sending requests when the downstream keeps failing, giving it time to recover. It has three states: closed (requests pass normally), open (requests are rejected immediately), and half-open (a small number of probe requests are allowed through, and the results decide whether to recover).

    1. import time
    2. class CircuitBreaker:
    3. """Simplified circuit breaker. In production, the half-open state
    4. usually limits the number of probe requests."""
    5. def __init__(self, failure_threshold: int = 5, reset_timeout: float = 30.0):
    6. self.failure_threshold = failure_threshold
    7. self.reset_timeout = reset_timeout
    8. self.failures = 0
    9. self.opened_at = None
    10. def allow(self) -> bool:
    11. if self.opened_at is None:
    12. return True
    13. # After the cooldown, enter half-open state and allow one probe request
    14. return time.monotonic() - self.opened_at >= self.reset_timeout
    15. def record_success(self) -> None:
    16. self.failures = 0
    17. self.opened_at = None
    18. def record_failure(self) -> None:
    19. self.failures += 1
    20. if self.failures >= self.failure_threshold:
    21. self.opened_at = time.monotonic()

    Degradation means deliberately giving up part of the capability under overload in exchange for keeping core functions available. For LLM services, common degradation strategies include:

    • Switching to a smaller, faster model to keep basic Q&A available.
    • Returning cached results for repeated or high-frequency requests.
    • Disabling non-core features such as long-document analysis or complex tool calling.
    • Clearly informing users in the UI that the service is degraded, with an estimated recovery time.

    Degradation plans should be designed in advance and rehearsed regularly. If the first time a degradation path is executed is during a real incident, teams often discover that the fallback path itself has problems.

    4.3 Multi-Backend Fallback and Eliminating Single Points

    Single points of dependency appear repeatedly in outage incidents. Even if the primary backend works fine, the whole system becomes unavailable if its network entry, authentication service, or configuration center fails. Ways to remove single points include:

    • Deploying inference services across multiple availability zones, with automatic failover when one zone fails.
    • Deploying critical configuration, authentication, and routing components redundantly, avoiding a shared failure domain.
    • Where the business allows, integrating multiple model backends and switching to a standby backend when the primary one is unavailable, while accounting for differences in output format and capability between backends.

    The following example shows how circuit breaking and degradation work together:

    1. def answer(prompt: str, primary, fallback, breaker: CircuitBreaker):
    2. """Prefer the primary backend; fall back to the degraded path
    3. when the breaker is open or the primary call fails."""
    4. if breaker.allow():
    5. try:
    6. result = primary(prompt)
    7. breaker.record_success()
    8. return result, "primary"
    9. except Exception:
    10. breaker.record_failure()
    11. return fallback(prompt), "degraded"

    The return value carries a source marker, which helps upper-layer services track the degradation ratio and lets the UI display appropriate notices.

    5. Client Resilience: Avoiding Retry Amplification

    Clients are the source of traffic, and client behavior determines whether a failure is absorbed or amplified. Good client practices include the following.

    5.1 Exponential Backoff with Jitter

    Retries should have an upper limit, intervals should grow with the number of failures, and random jitter should be added to prevent large numbers of clients from retrying at the same moment.

    1. import random
    2. import time
    3. class TransientError(Exception):
    4. """A retryable transient error, such as a timeout or HTTP 503."""
    5. def call_with_retry(fn, max_attempts: int = 4,
    6. base_delay: float = 0.5, max_delay: float = 8.0):
    7. for attempt in range(1, max_attempts + 1):
    8. try:
    9. return fn()
    10. except TransientError:
    11. if attempt == max_attempts:
    12. raise
    13. # Full jitter: wait a random time in [0, exponential backoff cap]
    14. backoff = min(max_delay, base_delay * (2 ** (attempt - 1)))
    15. time.sleep(random.uniform(0, backoff))

    Note that only idempotent or safely retryable requests should be retried automatically. Operations with side effects, such as billing or data writes, should use idempotency keys to avoid duplicate execution.

    5.2 Timeouts and Cancellation

    Every request should have a timeout. Requests without timeouts occupy connections and threads indefinitely until resources are exhausted. Timeout values should be based on the real latency distribution of the business — typically a reasonable multiple of P99 latency — rather than an arbitrarily large number.

    For streaming output, time-to-first-byte timeout and overall timeout should be distinguished. The former reflects queuing and scheduling problems; the latter reflects the generation time itself. Monitoring them separately is the only way to tell which stage the problem is in.

    5.3 Session Management

    Multi-turn conversation clients should actively manage context length. Common practices include:

    • Setting a maximum number of turns or tokens for history messages and trimming the oldest content once exceeded.
    • Summarizing earlier conversation turns and replacing raw records with the summary.
    • Prompting the user as the limit approaches and offering an entry point to start a new session.

    This turns an incomprehensible “length exceeded” error into a normal interaction that users can understand and handle.

    6. Cost-Performance Trade-offs

    The cost of LLM services is directly tied to load, and changes in cost structure in turn affect stability. If a model upgrade raises the per-token cost, the same budget supports fewer requests, and capacity planning must be redone.

    It is recommended to track the following metrics and review them regularly:

    • Cost per request: the average compute resources and expense consumed per request.
    • Cost per token: tracked by model version and by endpoint, making it easy to compare the cost-effectiveness of different models or configurations.
    • Resource utilization: average and peak utilization of compute units. Persistently high utilization means insufficient headroom; persistently low utilization means wasted resources.
    • Share of high-cost requests: a small number of very long requests may consume most of the resources and need to be identified and limited separately.

    Performance optimization should follow the principle of “measure first, optimize second.” Common optimization directions include batching, cache reuse, request coalescing, and output length control. Each optimization should be validated with real traffic or in a load-testing environment rather than by intuition.

    7. Observability and Alerting

    Without observability, teams can only respond passively after users complain. A complete monitoring system typically includes three types of data: metrics, logs, and distributed tracing.

    Key metrics include:

    • Request success rate and error rate, broken down by error type, distinguishing timeouts, rate limiting, server-side errors, and client-side errors.
    • Latency distribution, with particular attention to tail latencies such as P95 and P99 rather than averages alone.