Troubleshooting and High Availability Design for LLM Inference Service Anomalies

    This article explores common causes of sudden anomalies in LLM inference services and outlines a systematic approach for troubleshooting. It covers key monitoring metrics, root cause analysis across multiple architectural layers, and high availability design principles such as tiered rate limiting, circuit breaking, and exponential backoff. Readers will learn how to maintain core service functionality during peak loads and ensure a fair, reliable user experience.

    1. Problem Background: Typical Symptoms from User Feedback

    Service anomalies usually manifest first on the user side. Common symptoms include prolonged page loading, noticeably slower time-to-first-token (TTFT), interruptions in streaming output, truncated long conversations, and rate limiting (429) or server-side errors (5xx). The shared characteristic of these issues is that a single user cannot easily determine whether the problem lies with their local network, client version, or the server.

    In public discussion forums, users often speculate about the cause, asking if someone is spamming the service or if computing power is exhausted. While these speculations provide some reference, they lack data support. Engineering teams should rely on monitoring metrics and tracing logs to make judgments, treating user feedback as clues rather than conclusions.

    2. Common Root Cause Analysis

    The root causes of service anomalies are often multi-factorial. The following five categories are the most common sources.

    2.1 Traffic Spikes and Retry Amplification

    During hot events, feature releases, or after rate limit removals and dependency recoveries, request volume can double within minutes. More problematically, automatic client retries can amplify the original request volume several times. If a large number of clients retry at the same time, a “retry storm” forms, further overloading already strained resources.

    2.2 Inference Compute Bottlenecks

    LLM inference simultaneously consumes compute resources and GPU memory. Long-context requests consume more KV cache space, reducing the number of concurrent requests a single instance can handle. Once the batching queue accumulates, queuing time quickly exceeds generation time, manifesting as a spike in TTFT.

    2.3 Decline in Cache Hit Rate

    Session context and prefix caching can significantly reduce redundant computation. When cache capacity is insufficient, expiration policies are too aggressive, or routing strategies scatter the same session, the hit rate drops. The same computations are executed repeatedly, lowering overall throughput.

    2.4 Abnormal Requests and Abuse

    Automated scripts, batch generation tasks, and malicious probing all consume extra resources. Identifying this type of traffic requires multi-dimensional metrics such as request frequency, session length distribution, and source characteristics. However, if the identification rules are too coarse, they may harm normal users. Therefore, channels for appeal and manual review must be provided.

    2.5 Dependency Chain Failures

    Authentication services, gateways, message queues, and databases can all become bottlenecks. Even if the inference instances themselves are running normally, external service unavailability may manifest due to authentication timeouts.

    3. Troubleshooting Methodology: Layer-by-Layer Tracing

    When facing anomalies, it is recommended to troubleshoot layer by layer in the order of “client, access layer, gateway, scheduling layer, inference instance, and external dependencies.” For each layer, answer two questions: Are the error rate and latency abnormal at this layer? Is the upstream of this layer normal?

    3.1 Core Metrics

    The following metrics should be included in standard monitoring dashboards:

    • Request volume (QPS) and its breakdown by API, region, and tenant
    • Latency percentiles, especially P99 and Time To First Token (TTFT)
    • Error rate distribution, distinguishing between 429, 5xx, and timeouts, as they require different handling methods
    • Scheduling queue length and average queuing time
    • GPU utilization, memory usage, and KV cache usage rate
    • Cache hit rate and session routing consistency

    3.2 Sample Code: Calculating Latency Percentiles

    The following code demonstrates how to calculate P50 and P99 from sampled data, making it easier to use percentiles rather than averages in alerts. Averages can mask long-tail issues.

    1. def percentile(samples, p):
    2. if not samples:
    3. return None
    4. data = sorted(samples)
    5. k = int(round((len(data) - 1) * p / 100))
    6. return data[k]
    7. latencies_ms = [120, 135, 150, 180, 220, 640, 1500, 98, 110, 4200]
    8. print("P50:", percentile(latencies_ms, 50))
    9. print("P99:", percentile(latencies_ms, 99))

    In the example, the average is about 730 ms, which seems acceptable, but the P99 reaches 4200 ms, indicating that some users are experiencing noticeable lag.

    4. High Availability Design Principles

    Troubleshooting explains the problem, but reducing risk relies on architectural design. The following five measures work together to ensure the system degrades gracefully under overload rather than crashing entirely.

    4.1 Tiered Rate Limiting

    Rate limiting should be configured separately for tenants, APIs, and user tiers. The token bucket algorithm is a common choice as it allows short-term bursts while limiting the long-term rate.

    1. import time
    2. class TokenBucket:
    3. def __init__(self, rate, capacity):
    4. self.rate = rate # Tokens added per second
    5. self.capacity = capacity # Bucket capacity, determines the allowed burst request count
    6. self.tokens = capacity
    7. self.updated = time.monotonic()
    8. def allow(self):
    9. # Note: Locking is required in a multi-threaded environment; this only demonstrates the core logic
    10. now = time.monotonic()
    11. elapsed = now - self.updated
    12. self.tokens = min(self.capacity, self.tokens + elapsed * self.rate)
    13. self.updated = now
    14. if self.tokens >= 1:
    15. self.tokens -= 1
    16. return True
    17. return False

    Rate-limited requests should return a clear status code and a retry-wait time. For example, use the Retry-After response header to inform the client, preventing blind retries.

    4.2 Circuit Breaking and Degradation

    When downstream failures consecutively reach a threshold, the circuit breaker enters the “open” state, rejecting new requests directly to give the downstream time to recover. After a cooldown period, the circuit breaker enters the “half-open” state, allowing a small number of probe requests. If the probes succeed, the service recovers; if they fail, it remains open.

    Degradation strategies must be designed in advance. For example, under high load, route non-critical requests to lighter models, or return cached results directly for cacheable queries. The goal of degradation is to ensure core functionality remains available and to clearly inform users that the system is currently in a degraded state.

    4.3 Exponential Backoff with Jitter

    Retries should have an upper limit, and the wait time should increase with the number of attempts. Adding random jitter can scatter retry requests that occur at the same moment, avoiding synchronous impacts.

    1. import random
    2. import time
    3. def call_with_retry(fn, max_retries=3, base=0.5, cap=8.0):
    4. # RetryableError is a retryable exception defined by the caller, e.g., timeout or 429
    5. for attempt in range(max_retries + 1):
    6. try:
    7. return fn()
    8. except RetryableError:
    9. if attempt == max_retries:
    10. raise
    11. delay = min(cap, base * (2 ** attempt))
    12. time.sleep(random.uniform(0, delay))

    Only retry idempotent operations. For requests with side effects, deduplication should be performed using request identifiers first; otherwise, retries may lead to duplicate billing or generation.

    4.4 Queuing and Prioritization

    Placing requests into priority queues ensures that critical business and paid traffic receive resources first. The queue length must have an upper limit; when exceeded, fail fast rather than letting requests wait indefinitely. Infinite waiting will fill up the connection pool and eventually drag down the entire entry layer.

    4.5 Capacity Planning and Stress Testing

    Capacity planning should be based on historical peaks and growth trends, reserving a certain margin. A common practice is to keep the daily peak at 60% to 70% of the rated capacity. Conduct stress tests before each release, recording the inflection points of throughput, latency, and resource usage as a basis for scaling decisions. Stress tests should cover extreme scenarios such as long contexts and high-concurrency streaming output, not just average requests.

    5. User-Side Experience and Communication

    Beyond technical measures, communication equally affects users’ perception of the incident.

    • The status page should be updated as soon as possible after a failure occurs, explaining the scope of impact, current progress, and estimated time of recovery.
    • Error prompts should distinguish between “please try again later,” “request too long,” “function temporarily degraded,” etc., avoiding a generic “service unavailable” message.
    • After a streaming output interruption, the client should save the generated content and support resuming from the breakpoint or resubmitting.
    • Drafts and input content should be temporarily stored locally to prevent users from losing long texts during a failure.

    6. Balancing Security and Fairness

    When identifying abnormal traffic, normal users should be protected simultaneously. The following practices are recommended:

    • Determine risk based on behavioral characteristics rather than a single metric, such as comprehensively considering request frequency, session patterns, and account history.
    • Provide an appeal channel for accounts that trigger risk control, and handle edge cases through manual review.
    • Use consistent rules across different user groups to avoid unfair treatment caused by subjective judgments.
    • Record the basis for risk control decisions to facilitate post-event auditing and rule tuning.

    7. Practical Checklist

    1. Establish a monitoring dashboard layered by link, with latency percentiles and error rate types as core metrics.
    2. Configure rate limiting rules for each entry point, with rate limit responses containing clear retry wait information.
    3. Set up circuit breakers for critical downstreams and design degradation paths in advance.
    4. Unify retry strategies, limit attempts, add jitter, and ensure retries are only applied to idempotent operations.
    5. Set limits on queues and fail fast when limits are exceeded.
    6. Complete stress tests before each release and formulate scaling plans based on peak values.
    7. Synchronously update the status page during failures and differentiate the prompt text for different errors.

    8. Conclusion

    Service anomalies are often jointly triggered by factors such as traffic, compute, cache, and dependencies. Relying on user speculation cannot yield accurate conclusions. Only by combining layered monitoring, tiered rate limiting, circuit breaking, degradation, and capacity planning can we quickly locate issues during anomalies and maintain core functionality under overload.