How to Handle LLM Inference Rate Limits: Capacity, Failures, and Fault Tolerance

    This article explains why LLM inference services are constrained by GPU capacity, how KV cache makes long sessions expensive, and how idle sessions can be reclaimed. It then covers common rate limiting and quota forms, classifies retryable and non-retryable failures, and presents practical client-side patterns such as truncation, backoff retry, and session recovery.

    I. Background: Inference Service Resources Are Limited

    The main cost of an LLM chat service is GPU capacity. Every online session must keep its KV cache in GPU memory, and each newly generated token repeatedly reads that cache. As concurrent users increase, or as a few long sessions consume most of the memory, the service provider will enable rate limiting, length limits, and feature degradation to preserve overall availability.

    Clients typically encounter four types of symptoms: long conversations cannot be continued, a single input is truncated, the daily call quota is exhausted, or responses become slower and occasionally fail. Before handling these symptoms, three questions need to be answered: what is consuming resources, which sessions can be reclaimed, and how the client can remain reliable in a constrained environment.

    II. KV Cache: Why Long Sessions Are Expensive

    During autoregressive generation, every time the model outputs a new token, it performs attention over all previous tokens. To avoid repeated computation, the inference framework caches the Key and Value vectors already computed for each layer. This data is called the KV cache.

    The memory footprint of the KV cache is proportional to sequence length and can be roughly estimated with the following formula:

    Memory ≈ 2 × layers × KV heads × head dimension × sequence length × batch size × bytes per element

    The coefficient 2 means that K and V are stored separately. The number of KV heads corresponds to num_key_value_heads in the model configuration. Models using GQA or MQA have fewer KV heads than attention heads, so their caches are smaller. The formula estimates only the KV cache and does not include model weights, activations, memory fragmentation, or framework-reserved space.

    Consider a set of hypothetical parameters: 32 layers, 8 KV heads, head dimension 128, sequence length 32768, batch size 1, and half precision (2 bytes per element). The KV cache for a single session is about 4 GiB. This is a theoretical value; production environments need to calibrate it against the actual dtype, page size, and concurrent batch size.

    1. def kv_cache_bytes(layers, kv_heads, head_dim, seq_len, batch=1, dtype_bytes=2):
    2. """Estimate KV cache bytes and return a theoretical lower bound (illustrative)."""
    3. for name, value in [("layers", layers), ("kv_heads", kv_heads),
    4. ("head_dim", head_dim), ("seq_len", seq_len),
    5. ("batch", batch), ("dtype_bytes", dtype_bytes)]:
    6. if value <= 0:
    7. raise ValueError(f"{name} must be a positive integer, got {value}")
    8. # K and V are stored separately, so the coefficient is 2
    9. return 2 * layers * kv_heads * head_dim * seq_len * batch * dtype_bytes
    10. size = kv_cache_bytes(layers=32, kv_heads=8, head_dim=128, seq_len=32768)
    11. print(f"{size / 1024**3:.1f} GiB") # Output: 4.0 GiB

    Even if a long session no longer produces output, it continues to occupy capacity as long as it remains in GPU memory. This explains why service providers reclaim sessions that have been idle for a long time.

    III. Reclaiming Idle Sessions

    Reclamation strategies usually combine three methods:

    1. Idle-time expiration (TTL): release a session’s cache when it has no interaction for a configured period.
    2. Capacity-pressure eviction (LRU): when memory is tight, release the sessions that have not been accessed for the longest time first.
    3. Priority protection: reserve quota for requests with strict latency requirements or higher service tiers so they are not crowded out by lower-priority tasks.

    The following example shows a reclamation flow with locking. Before deleting a session, it calls the underlying release interface to prevent concurrent requests from reading an already released cache.

    1. import threading
    2. import time
    3. class SessionStore:
    4. def __init__(self, ttl_seconds: float):
    5. self._lock = threading.Lock()
    6. self._sessions: dict[str, dict] = {}
    7. self._ttl = ttl_seconds
    8. def touch(self, sid: str, now: float | None = None) -> None:
    9. """Record an interaction and update the last active time."""
    10. now = time.time() if now is None else now
    11. with self._lock:
    12. s = self._sessions.setdefault(sid, {"last_active": now, "state": "active"})
    13. s["last_active"] = now
    14. def evict_expired(self, release_fn, now: float | None = None) -> int:
    15. """Release sessions exceeding the idle threshold and return the number released. release_fn calls the inference framework's release interface."""
    16. now = time.time() if now is None else now
    17. released = 0
    18. with self._lock:
    19. expired = [sid for sid, s in self._sessions.items()
    20. if now - s["last_active"] > self._ttl]
    21. for sid in expired:
    22. self._sessions[sid]["state"] = "evicting"
    23. release_fn(sid) # If the underlying release fails, it raises an exception; the session remains in "evicting" state for retry
    24. del self._sessions[sid]
    25. released += 1
    26. return released

    Production environments also need to pay attention to three points. First, write session metadata to persistent storage before deletion so users can restore the session later. Second, if release fails, do not discard the record immediately; keep the state and retry. Third, expose clear status codes so clients know that a session has been reclaimed, rather than returning a vague context error.

    Reclamation has a clear side effect: when a user switches back to an old session, the server-side cache no longer exists, and the context cannot be continued directly. The client needs to rebuild the context from locally stored history or a summary.

    IV. Common Forms of Rate Limiting and Quotas

    1. Input length limits

    The service provider limits a single input by token count. A lowered limit usually means the provider is tightening capacity. There is no fixed conversion between character count and token count; the token count of Chinese text varies with the tokenization method. Clients should rely on the count or error message returned by the server, not on character count alone.

    When the limit is exceeded, truncation can follow this order: keep the system prompt, keep the most recent turns, and compress earlier history into a summary. After truncation, record what content was omitted so the model does not give incorrect answers without knowing that information is missing.

    2. Daily or sliding-window quotas

    The service provider counts calls by calendar day or by a rolling time window. When the quota is exhausted, continuing to retry is pointless. The client should show the remaining wait time or switch to another model if the product allows it.

    3. Concurrency and rate limits

    When the same account sends too many requests in a short period, the service provider returns a rate-limit response. These limits are usually temporary and are suitable for recovery through backoff retries. If the response includes a wait hint such as Retry-After, it should be followed first.

    V. Classifying Rate Limits and Failures

    The table below distinguishes errors by symptom and gives the client-side handling approach. Specific status codes and error fields are subject to the provider’s documentation.

    Symptom Common cause Retryable? Client action
    Input over limit Single input exceeds the limit No, shorten the input first Split, summarize, or truncate, then resubmit
    Quota exhausted Calls used up for the day or window No, wait for the window to reset Show wait time, queue, or switch models
    Rate limit Too many requests in a short period Yes, follow the wait hint Exponential backoff, delay according to the hint
    Overload or timeout Long queue, increased inference time Yes, limited number of times Backoff retry, circuit break after repeated failures
    Session reclaimed TTL expired or capacity eviction No, the original cache is invalid Rebuild context from local history or a summary
    KV OOM Long sessions or large batches fill GPU memory Depends on the situation Shorten context, reduce concurrency, retry later
    Authentication or parameter error Invalid key, malformed field No Fix the configuration, do not retry

    Retry only applies to transient errors. Retrying authentication or parameter errors only wastes quota and may trigger account risk controls.

    VI. Exponential Backoff and Circuit Breaker Implementation

    Recommended parameters for exponential backoff are:

    • Maximum retries: 3 to 5.
    • Base: 0.5 seconds, doubling each time.
    • Backoff cap: 20 seconds.
    • Jitter: use full jitter, choosing a random value between 0 and the current backoff time to avoid many clients retrying at the same time.
    • Retry only 429, 500, 502, 503, 504, and timeouts.
    1. import random
    2. import time
    3. RETRYABLE_STATUS = {429, 500, 502, 503, 504}
    4. def call_with_backoff(send, max_retries=4, base=0.5, cap=20.0):
    5. """send() returns a response object with status_code, and raises TimeoutError on timeout.
    6. Non-retryable responses (such as 400 and 401) are returned directly for the caller to handle."""