Why LLM APIs Keep Returning "Service Busy": Throttling Causes and Mitigation Strategies

    This article examines why large model API calls frequently return 429 or 503 "busy" errors. It explains the three layers where failures occur, breaks down bottlenecks in GPU memory (KV cache), compute scheduling and queuing, and gateway rate limiting, then provides practical mitigation strategies: exponential backoff with jitter, a bounded message queue for traffic smoothing, and multi-model fallback with hysteresis to avoid oscillation, all illustrated with Python examples.

    This article is adapted from an industry report. The report claimed that the LLM API called by an AI coding tool consumed roughly 8 trillion tokens in a single day, during which developers frequently received “service busy” errors. That figure comes from the tool vendor’s public statement; the original source provided no link and no methodology details, such as whether input and output tokens were counted separately, whether cache hits were included, or what time window was used. We treat it only as background, not as a verified fact. If you intend to cite it, locate the original publication and verify the methodology first.

    1. Where Do the Errors Come From?

    A single model call passes through three layers: the client sends a request, the API gateway checks quota and concurrency, the request enters an inference queue, and the GPU generates the response. An error can surface at any layer, so the first step in troubleshooting is to identify where it occurred.

    • Gateway layer: returns 429, indicating rate limiting or exceeded quota.
    • Inference layer: queue wait time exceeds the server-side threshold, returning 503 or a “busy” message.
    • GPU layer: insufficient memory forces new requests to wait or be rejected.

    2. Three Bottlenecks and How to Diagnose Them

    2.1 GPU Memory and the KV Cache

    During autoregressive generation, the model keeps a key-value (KV) cache for every in-flight request so that generating a new token does not require recomputing attention over all historical tokens. The memory footprint of the KV cache can be estimated as:

    KV cache bytes ≈ 2 × number of layers × number of KV heads × head dimension × context length × concurrent requests × bytes per element

    The factor of 2 exists because K and V are each stored once. Bytes per element are 2 for FP16 and 1 for INT8. Models using Grouped-Query Attention (GQA) or Multi-Query Attention (MQA) have fewer KV heads than attention heads, which significantly reduces memory usage. Use the KV head count, not the attention head count, in your estimate.

    Consider a hypothetical configuration: 32 layers, 8 KV heads, head dimension 128, an 8,192-token context, 16 concurrent requests, FP16 precision. Plugging into the formula yields roughly 17.2 GB (16 GiB). This is only an example and does not represent any specific model.

    The formula has two boundaries. First, it is approximately linear under a fixed configuration: doubling concurrency roughly doubles the cache. Second, it does not account for memory fragmentation, model weights, or activations. Paged KV cache management reduces fragmentation waste but does not change the formula itself. Once memory nears its limit, new requests can only queue or be rejected, and latency spikes sharply. This behavior is easily misread as exponential growth.

    Observable metrics: KV cache memory utilization, number of waiting requests, and the inference engine’s memory eviction or OOM logs.

    2.2 Compute Scheduling and Queuing

    When the request arrival rate exceeds the cluster’s processing capacity, requests enter a queue. Once queue wait time exceeds the server-side threshold, the gateway returns an error directly. These errors are usually transient and recover once traffic subsides.

    429 and 503 mean different things:

    • 429 Too Many Requests: typically means the client exceeded a rate or quota limit; the problem is usually on the caller’s side. The response may include a Retry-After header suggesting how many seconds to wait.
    • 503 Service Unavailable: typically means the service is overloaded, under maintenance, or an upstream dependency is unavailable; the problem is usually on the server side.

    Also note the relationship between three timeouts. The client timeout should be greater than the server-side queue timeout. If the client gives up first, the server keeps generating, wasting GPU compute on a result nobody will receive. The server-side queue timeout should be slightly shorter than the client timeout, so the server can return a definitive error instead of letting the client wait until the connection drops.

    Observable metrics: queue depth, P95 and P99 queue wait times, and the ratio of 429 to 503 responses.

    2.3 Gateway Rate Limiting and Concurrency

    API gateways commonly use token bucket or leaky bucket algorithms to limit request rates. Their differences:

    Dimension Token Bucket Leaky Bucket
    Burst traffic Allowed; accumulated tokens can be consumed at once Not allowed; output at a fixed rate
    When limit exceeded Rejected immediately Queued; dropped once the queue is full
    Key parameters Token refill rate, bucket capacity Output rate, queue capacity
    Typical use case Interactive APIs that tolerate short bursts Downstream services requiring smooth output

    In addition, gateways usually limit the number of concurrent connections per account. Long-context requests hold connections longer, so you can hit the concurrency ceiling even with a modest request count.

    Observable metrics: the gateway’s 429 ratio, per-account concurrency, and average connection hold time per request.

    3. Retries: Backoff, Caps, and Jitter

    Retrying immediately after a 429 or 503 adds pressure to the server. The correct approach has five points: only retry retryable errors; increase wait time exponentially; add random jitter so large numbers of clients don’t retry simultaneously; set a maximum retry count; and set both a per-attempt delay cap and a total time budget.

    The code below uses Python. Replace the timeout exception type with the one used by your HTTP library.

    1. import random
    2. import time
    3. RETRYABLE_STATUS = {429, 503}
    4. MAX_RETRIES = 4 # Maximum retries, excluding the initial request
    5. BASE_DELAY = 0.5 # Backoff base, seconds
    6. MAX_DELAY = 20.0 # Per-attempt delay cap, seconds
    7. TOTAL_BUDGET = 60.0 # Total time budget from the first request, seconds
    8. REQUEST_TIMEOUT = 30.0 # Per-request HTTP timeout, seconds
    9. def parse_retry_after(value):
    10. """Retry-After can be seconds or an HTTP date. Only seconds are handled here."""
    11. try:
    12. return float(value)
    13. except (TypeError, ValueError):
    14. return None
    15. def backoff_delay(attempt, retry_after=None):
    16. """Exponential backoff with full jitter: random value between 0 and min(cap, base * 2^attempt)."""
    17. ceiling = min(MAX_DELAY, BASE_DELAY * (2 ** attempt))
    18. delay = random.uniform(0, ceiling)
    19. if retry_after is not None:
    20. delay = max(delay, min(retry_after, MAX_DELAY))
    21. return delay
    22. def call_with_retry(send_request, request_id, retry_safe, log):
    23. """
    24. send_request(timeout) makes one request and returns a response with status_code, headers, json.
    25. Requests with retry_safe=False (e.g., tool calls that write to a database) are sent only once.
    26. """
    27. if not retry_safe:
    28. return send_request(timeout=REQUEST_TIMEOUT)
    29. start = time.monotonic()
    30. for attempt in range(MAX_RETRIES + 1):
    31. try:
    32. resp = send_request(timeout=REQUEST_TIMEOUT)
    33. if resp.status_code == 200:
    34. return resp
    35. if resp.status_code not in RETRYABLE_STATUS:
    36. raise RuntimeError(f"Non-retryable status code: {resp.status_code}")
    37. reason = f"http_{resp.status_code}"
    38. retry_after = parse_retry_after(resp.headers.get("Retry-After"))
    39. except TimeoutError:
    40. reason = "timeout"
    41. retry_after = None
    42. if attempt == MAX_RETRIES:
    43. break
    44. elapsed = time.monotonic() - start
    45. delay = backoff_delay(attempt, retry_after)
    46. if elapsed + delay > TOTAL_BUDGET:
    47. break
    48. log.warning({
    49. "request_id": request_id,
    50. "attempt": attempt + 1,
    51. "reason": reason,
    52. "delay_s": round(delay, 2),
    53. "elapsed_s": round(elapsed, 2),
    54. })
    55. time.sleep(delay)
    56. log.error({"request_id": request_id, "final_reason": reason, "attempts": attempt + 1})
    57. raise RuntimeError("Retries exhausted; fall back to queuing or a degraded path")

    When using this code, keep the following in mind:

    • Logs should include at least request_id, model name, attempt count, failure reason, delay, and cumulative elapsed time, so each request can be traced.
    • Errors like 400, 401, and 403 are unrelated to load; retrying them is pointless. Return them directly.
    • Retrying generation requests may result in duplicate billing. Check the provider’s billing rules and record every attempt locally.
    • Only requests that do not write to external systems are safe to retry. Tool calls that write to a database or send messages need an idempotency key to be retried safely.

    4. Smoothing Traffic with a Message Queue

    Retries only postpone pressure. When traffic persistently exceeds processing capacity, the application needs a buffer layer. A message queue is the standard approach: requests are enqueued first, and workers consume them at the rate the provider allows. Three points matter in practice.

    • Cap the queue. When the queue is full, return a clear error immediately instead of letting it grow unboundedly; otherwise memory usage and wait times spiral out of control.
    • Give every task a deadline. Workers should drop tasks whose clients have already given up, without calling the model.
    • Size the worker count and consumption rate according to the provider’s quota, leaving headroom rather than exhausting the quota.
    1. import queue
    2. import time
    3. task_q = queue.Queue(maxsize=200) # Queue capacity; set based on load test results
    4. def submit(payload, timeout_s=30):
    5. task = {"payload": payload, "deadline": time.time() + timeout_s}
    6. try:
    7. task_q.put_nowait(task)
    8. return {"status": "queued"}
    9. except queue.Full:
    10. return {"status": "rejected", "error": "busy", "retry_after": 5}
    11. def worker(call_model):
    12. while True:
    13. task = task_q.get()
    14. try:
    15. if time.time() > task["deadline"]:
    16. continue # Client already timed out; skip the model call
    17. call_model(task["payload"])
    18. finally:
    19. task_q.task_done()

    The queue needs alerting. The following thresholds are only starting points; adjust them based on your business and load test results: queue depth exceeds half the capacity for 5 consecutive minutes; queue wait P95 exceeds half the client timeout; rejection rate for any task type exceeds 1%.

    5. Multi-Model Fallback

    When the primary model is unavailable, you can switch to a backup model. A candidate model must satisfy four conditions simultaneously.

    • Capability meets the task. Code generation, summarization, and classification have different capability requirements; you cannot uniformly degrade everything to the smallest model.
    • Cost stays within budget.
    • Latency stays within the task’s latency budget.
    • Data compliance. If the data is not permitted to be sent to a particular provider, that model cannot serve as a fallback even if it is available.

    Switching conditions should avoid oscillation. The rules below require 3 consecutive unhealthy windows before switching and 10 consecutive healthy windows before switching back. The switch threshold (5% error rate) differs from the recovery threshold (1% error rate), which prevents the model from flapping between the two states.

    ```python
    MODELS = [ # Ordered by priority; models that fail compliance review are not included
    {“name”: “primary-large”},
    {“name”: “backup-mid”},
    {“name”: “fallback-small”},
    ]

    SWITCH_ERROR_RATE = 0.05 # Error rate above 5% counts as unhealthy
    RECOVER_ERROR_RATE = 0.01 # Error rate below 1% counts as recovered
    SWITCH_WINDOWS = 3 # Switch only after 3 consecutive unhealthy windows
    RECOVER_WINDOWS = 10 # Switch back only after 10 consecutive healthy windows

    def update_state(h, error_rate, p95_s, latency_budget_s):
    “””Called once per statistics window (e.g., 1 minute). h starts as {“state”: “healthy”, “bad_windows”: 0, “good_windows”: 0}.”””
    if h[“state”] == “healthy”:
    bad = error_rate > SWITCH_ERROR_RATE or p95_s > latency_budget_s
    h[“bad_windows”] = h[“bad_windows”] + 1 if bad else 0
    if h[“bad_windows”] >= SWITCH_WINDOWS:
    h[“state”] = “degraded”
    h[“good_windows”] = 0
    else:
    good = error_rate < RECOVER_ERROR_RATE and p95_s <= latency_budget_s
    h[“good_windows”] = h[“good_windows”] + 1 if good else 0
    if h[“good_windows”] >= RECOVER_WINDOWS:
    h[“state”] = “healthy”
    h[“bad_windows”] = 0

    def pick_model(task, health):
    “””health[name] is maintained by update_state. Returns None if all models are unavailable.”””
    for model in MODELS:
    name = model[“name”