Optimizing LLM API Costs and Handling Request Queues in Production
This article provides practical strategies for reducing wasted LLM API spending and preventing request failures during peak traffic. It covers quota-based concurrency planning, lifecycle scheduling for prepaid credits, asynchronous queue design for traffic smoothing, token bucket rate limiting, retry policies with exponential backoff, idempotency checks, dead-letter handling, and key operational metrics for monitoring. The included Python example uses only the standard library and demonstrates a priority queue combined with a token bucket limiter, making the approach easy to validate before integrating a full message broker.
Start with Quota Math Before Setting Concurrency
Many queuing problems come from not understanding your quota. Providers usually limit calls by RPM (requests per minute) or TPM (tokens per minute). If your quota is 600 RPM, that equals 10 requests per second. If one call takes 2 seconds on average, you will have about 20 requests in flight. Setting more than 20 workers will only add wait time, not throughput.
A good rule is to target 80% of your quota, leaving a 20% buffer for retries and network jitter. If both RPM and TPM limits apply, calculate them separately and honor whichever limit is hit first.
Lifecycle Scheduling for Prepaid Credits
Prepaid credits are essentially compute you have purchased in advance. Traffic has peaks and valleys, so it is common to carry a large unused balance toward the end of a billing cycle. Manually looking for tasks to consume credits is inefficient and often produces low-value work.
A more reliable approach is to define a scheduling policy that periodically reads the remaining balance and expiry date, then triggers action based on thresholds:
| Remaining Credit Ratio | Time to Expiry | Scheduling Action |
|---|---|---|
| Above 50% | More than 30 days | Normal scheduling, no extra consumption |
| 20% to 50% | 7 to 30 days | Enable low-priority offline queue with daily quota |
| Below 20% | Less than 7 days | Pause low-priority tasks, reserve capacity for real-time business |
These thresholds are a starting point. Adjust them based on your historical usage curve. Offline tasks are well suited for low-priority queues, such as historical ticket sentiment analysis, document vectorization, or periodic log summarization. Before using such data, make sure it has been anonymized and complies with data regulations and internal authorization policies. Personal information should not be sent to third-party models without proper processing.
Use a Message Queue to Smooth Traffic Peaks
Synchronous LLM calls degrade quickly under high concurrency and often get rejected by rate limiting. A safer design is asynchronous: the client writes a request to a message queue and immediately returns a task ID. The consumer pulls tasks from the queue at a rate controlled by the quota, and the result is returned via polling or a webhook callback.
Queue selection considerations:
- Kafka: High throughput, suitable for log and batch tasks. Ordering is guaranteed within a partition. It does not natively support message-level priority or dead-letter queues, so those are typically implemented with multiple topics and agreed retry topics.
- RocketMQ: Provides built-in delayed messages, retry queues, and dead-letter queues. A good fit when you need a full message lifecycle.
General-purpose message queues do not normally support message-level priority. A common workaround is to create separate topics for high, medium, and low priority, with the consumer always draining the high-priority topic first.
A token bucket is a solid approach for consumer-side rate limiting. Tokens are refilled at a fixed rate, and the bucket capacity determines the allowed burst size. Set the bucket capacity to roughly one second of quota to avoid exhausting the entire rate limit in a single burst.
Example Code
The following code demonstrates a priority queue, token bucket rate limiting, exponential backoff retry, idempotency checks, and dead-letter collection. It depends only on the Python 3.8+ standard library and can be run directly. The simulated model call randomly returns 429 errors so you can observe the retry behavior.
import asyncioimport itertoolsimport randomimport timePRIORITY_HIGH = 0 # Lower number means higher priorityPRIORITY_LOW = 10class TokenBucket:"""Token bucket rate limiter: rate is tokens per second, capacity is burst size."""def __init__(self, rate, capacity):self.rate = rateself.capacity = capacityself.tokens = capacityself.updated = time.monotonic()self.lock = asyncio.Lock()async def acquire(self):while True:async with self.lock:now = time.monotonic()self.tokens = min(self.capacity,self.tokens + (now - self.updated) * self.rate)self.updated = nowif self.tokens >= 1:self.tokens -= 1returnwait = (1 - self.tokens) / self.rateawait asyncio.sleep(wait)class LLMGateway:def __init__(self, bucket, max_retries=3):self.queue = asyncio.PriorityQueue()self.bucket = bucketself.max_retries = max_retriesself.done = {} # Idempotency table: task_id -> resultself.dead_letter = [] # Dead-letter list: task, error messageself._seq = itertools.count()async def submit(self, task_id, prompt, priority=PRIORITY_LOW):if task_id in self.done: # Skip tasks that are already completedreturnawait self.queue.put((priority, next(self._seq), task_id, prompt, 0))async def worker(self, call_model):while True:priority, _, task_id, prompt, attempt = await self.queue.get()try:await self.bucket.acquire()self.done[task_id] = await call_model(prompt)except Exception as err:if attempt + 1 >= self.max_retries:self.dead_letter.append((task_id, prompt, str(err)))else:await asyncio.sleep(2 ** attempt + random.random())await self.queue.put((priority, next(self._seq), task_id, prompt, attempt + 1))finally:self.queue.task_done()async def fake_model(prompt):await asyncio.sleep(0.05)if random.random() < 0.2:raise RuntimeError("429 Too Many Requests")return f"Result: {prompt}"async def main():gateway = LLMGateway(TokenBucket(rate=10, capacity=10))for i in range(8):priority = PRIORITY_HIGH if i == 0 else PRIORITY_LOWawait gateway.submit(f"t{i}", f"prompt {i}", priority)workers = [asyncio.create_task(gateway.worker(fake_model)) for _ in range(3)]await gateway.queue.join()for w in workers:w.cancel()print(f"Succeeded: {len(gateway.done)}, dead-letter: {len(gateway.dead_letter)}")asyncio.run(main())
Code notes:
- The tuple in
PriorityQueueis ordered by (priority, sequence number, …). The sequence number preserves first-in-first-out ordering within the same priority and avoids comparing task content. - Retries keep their original priority. A failing task is not downgraded because it was retried.
queue.join()only returns after every task (including tasks added during retries) has calledtask_done. A retried task is re-enqueued beforetask_doneis called, so the counter does not reach zero prematurely.- The
donedict in this example is an in-memory table for demonstration purposes only. In production, use Redis or a database, keyed by “business ID + task type”. - Workers in this example are occupied during sleep. In production, delegate delayed retries to the message queue’s delayed message feature.
In the output, the number of successful tasks plus dead-letter tasks should equal the number submitted, which is 8. When connecting to a real Kafka or RocketMQ deployment, replace the in-memory queue with the corresponding client; the consumption logic stays essentially the same.
Retry, Idempotency, and Dead-Letter Handling
Retries are the most error-prone part of the design. If every failed request retries immediately, a 429 spike quickly amplifies into a retry storm. Follow these rules:
- Only retry 429, 5xx, and timeout errors. Parameter errors and other 4xx responses should go straight to the dead-letter queue.
- Use exponential backoff with random jitter, e.g., wait 2^n seconds plus a random value between 0 and 1 second.
- Limit total retries to 3 to 5.
- Make the operation idempotent. The same task must only be executed once even if it is delivered multiple times. Check the idempotency table before consuming, and write the result after successful execution.
- Keep the full task content, error message, and retry count in the dead-letter queue, and set up alerting. Dead-letter tasks require manual review or a scheduled script to re-process; they should not be silently discarded.
Monitoring and Alerting
A queue without monitoring is hard to maintain. At a minimum, track the metrics below. The thresholds shown are examples and should be tuned to your business.
- Queue backlog age: alert if it exceeds 5 minutes.
- Rate-limit (429) ratio: alert if it stays above 5% for 5 consecutive minutes.
- Dead-letter growth rate: alert if more than 50 new entries appear per hour.
- Remaining credits and expiry: alert when they reach the thresholds in the table in section 2.
- Average task latency and token consumption: use these to calibrate quotas and cost forecasts.
Deployment on Common Cloud Infrastructure
A typical production setup can combine managed services as follows. Specific versions, permission settings, and billing rules may vary; check the console and the official documentation before configuring anything, and confirm your quota covers the expected load.
- Run consumer workers on a container service. Default autoscaling usually relies on CPU and memory usage. To scale based on queue backlog length, you will need custom metrics or a tool like KEDA.
- Use object storage for large inputs such as long text or images. Pass only the file reference in the queue message. This keeps message sizes small and makes re-reading the input easy after a failure.
- Record the latency, token count, credit consumption, and status code for every call in a log service. This provides the basis for cost auditing and troubleshooting.
Summary
The cost and stability of LLM API calls mainly depend on three things: rate limiting according to quota, absorbing traffic peaks with a queue, and monitoring to detect abnormal credit usage or errors early. Credit scheduling, asynchronous queues, and strict retry policies reduce resource waste and queue waiting time. With reasonable quota planning and queue configuration, this approach relieves congestion during peak periods and puts unused credits to work on high-value offline tasks.
