What to Do When LLM APIs Get Queued: Async Processing and Retry Practices
LLM API requests often time out due to heavy queuing. This article explains the root causes of API queuing from a developer's perspective, its impact on quotas and business logic, and provides practical solutions including asynchronous task architectures, retry with exponential backoff, quota management, and multi-model fallback strategies. Complete runnable Python code examples are included.
What can you do when LLM API requests time out due to queuing? This article breaks down the causes of queuing from a developer’s perspective, explains how it affects quotas and business operations, and presents implementation approaches for async tasks, retry with backoff, quota management, and multi-model fallback.
1. Causes of Queuing
Queuing typically results from several overlapping factors.
1. Imbalance between compute supply and demand. Inference depends on GPU memory and compute power. During peak hours, cluster resources are limited and requests enter a waiting queue. Models with larger parameter counts take longer per inference and occupy resources longer, making queuing more pronounced.
2. Platform rate-limiting dimensions. Providers usually restrict API calls across multiple dimensions. Common ones include:
- RPM (requests per minute): limits the number of requests per unit of time.
- TPM (tokens per minute): limits the total input plus output tokens; long-text requests hit this limit first.
- Concurrency: the maximum number of requests being processed simultaneously.
- Queue length: the maximum number of queued requests; anything beyond this is rejected outright.
Different pricing tiers have different limits. Lower-priority users are the first to be queued or rejected during peak hours.
3. Metric definitions. Assessing whether queuing is severe requires consistent metrics. It is recommended to record per-request queue time, time-to-first-token latency, P95 values for total latency, and the proportion of 429 and 503 errors. Looking only at averages will hide long-tail problems.
2. Specific Problems Caused by Queuing
1. Conflicts between quota expiry and queuing. On many platforms, credits or quotas have expiration dates. When queuing is severe, quota may not be consumed before it expires. Some developers fire off requests unrelated to actual business just to burn through quota—this adds cost and occupies compute time that others genuinely need. A more reasonable approach is to adjust call pacing and task priorities, and to set up early warnings when quota runs low.
2. Cascading failures from synchronous blocking. If business threads synchronously wait for the model’s response, prolonged queuing leads to HTTP connection timeouts and unresponsive front ends. Once the thread pool is exhausted, other endpoints of the same service are affected as well.
3. Mitigation Practices
3.1 Building an Asynchronous Task Architecture
Decouple model calls from the user request path. The upstream service submits a task and immediately returns a task ID. Background worker nodes consume tasks from a message queue, call the model, and write results to a database or object storage. The front end obtains results by polling task status or receiving callbacks. Key considerations when implementing this include:
- Idempotency key: each task carries a business-unique key, such as a hash of the business ID plus request type. Duplicate submissions return the existing task directly, avoiding duplicate billing.
- State machine: tasks transition among pending, running, succeeded, failed, and cancelled. Every state change is written to the database with a timestamp for easier troubleshooting.
- Dead-letter queue: tasks that exhaust retries or have malformed messages are moved to a dead-letter queue, handled by an alerting process or manually—never consumed in an infinite loop.
- Timeout and cancellation: set an overall timeout for each task. On timeout, mark the task as failed or cancelled and notify the caller. When cancelling a task, confirm whether the platform has already billed for it.
- Error classification: distinguish retryable errors (429, 503, timeouts) from non-retryable errors (400 parameter errors, authentication failures). Non-retryable errors fail immediately and do not enter the retry flow.
3.2 Exponential Backoff Retries
When rate-limited or when the queue is full, retrying immediately only worsens congestion. The recommended approach is exponential backoff with random jitter: after each failure, the wait time doubles, plus an additional random value to prevent large numbers of clients from retrying at the same moment.
The following code runs as-is, requires Python 3.8 or later, and has no third-party dependencies. mock_llm_api_call simulates an SDK call. In a real project, replace it with your SDK’s call method and map the SDK’s raised errors to RateLimitError or QueueFullError.
import loggingimport randomimport timelogger = logging.getLogger("llm_client")class RateLimitError(Exception):"""The platform returned a rate-limit error, e.g., HTTP 429."""class QueueFullError(Exception):"""The platform queue is full, e.g., HTTP 503 with a queue-full error code."""class MaxRetriesExceededError(Exception):"""Max retry count or deadline reached without success."""def mock_llm_api_call(prompt: str) -> str:"""Simulates an SDK call. Replace with your SDK's call method in real projects."""if random.random() < 0.6:raise RateLimitError("429 Too Many Requests")return f"Simulated reply: {prompt[:20]}"def call_llm_with_retry(prompt: str,max_retries: int = 5,base_delay: float = 1.0,max_delay: float = 30.0,deadline_seconds: float = 120.0,) -> str:start = time.monotonic()for attempt in range(1, max_retries + 1):try:return mock_llm_api_call(prompt)except (RateLimitError, QueueFullError) as e:if attempt == max_retries:breakdelay = min(max_delay, base_delay * 2 ** (attempt - 1))delay += random.uniform(0, 1)elapsed = time.monotonic() - startif elapsed + delay > deadline_seconds:breaklogger.warning("Queued or rate-limited, attempt %d failed, retrying in %.2f seconds: %s",attempt, delay, e,)time.sleep(delay)raise MaxRetriesExceededError(f"No success within {deadline_seconds} seconds or {max_retries} retries")if __name__ == "__main__":logging.basicConfig(level=logging.INFO)try:print(call_llm_with_retry("Summarize the key points of this article"))except MaxRetriesExceededError as e:print(f"Task failed, moving to dead-letter queue: {e}")
Key design points of this code:
- It only catches retryable exceptions. Other exceptions propagate directly, avoiding masking parameter or authentication issues.
- Wait time is capped by
max_delay, preventing excessively long waits after exponential growth. deadline_secondslimits total elapsed time. If the next wait would exceed the deadline, the call gives up immediately, freeing the worker thread.- After retries are exhausted,
MaxRetriesExceededErroris raised, and the caller uses this signal to write the task to the dead-letter queue.
3.3 Quota Alerting and Batch Processing Scheduling
Monitoring remaining quota and its expiry is necessary, but automatically consuming quota requires careful handling. Recommended design principles:
- Off by default. Automated batch processing must be explicitly enabled by the user or an administrator.
- Limited scope. Only process task types registered by the user in advance, such as historical log summarization or offline data labeling. User-facing real-time requests are excluded.
- Cost caps. Set maximum consumption quotas and spending limits per day or per month, and stop automatically when the cap is reached.
- Sensitive data filtering. Mask phone numbers, ID numbers, keys, and similar information before sending, and record the version of the masking rules applied.
- Audit logging. Every batch job’s source, submission time, token consumption, and result status must be traceable.
- One-click kill switch. When anomalies are detected, administrators must be able to immediately pause all batch jobs.
In most scenarios, the safer approach is alerting only: when quota is about to expire with a large amount remaining, notify the responsible person and let them decide whether to schedule offline tasks.
4. Architecture Upgrade: Building a Highly Available LLM Application Layer
4.1 Multi-Model Routing and Fallback
Do not bind all requests to a single model. An API gateway can be configured with multi-model routing so that when the primary model is heavily queued, new requests are switched to a fallback model. The thresholds below are examples only and should be adjusted based on your business latency requirements.
- Trigger conditions: the primary model’s P95 queue time exceeds 10 seconds for 5 consecutive minutes, or the proportion of 429 errors exceeds 5%.
- Quality assurance: use a fixed evaluation set to periodically compare results between the primary and fallback models. If the fallback model scores below the preset threshold on critical tasks, do not fall back—queue the request and raise an alert instead.
- Result labeling: mark which model produced each response, so downstream consumers and evaluation pipelines can distinguish them and quality issues can be traced back to the specific model used.
