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.

    1. import asyncio
    2. import itertools
    3. import random
    4. import time
    5. PRIORITY_HIGH = 0 # Lower number means higher priority
    6. PRIORITY_LOW = 10
    7. class TokenBucket:
    8. """Token bucket rate limiter: rate is tokens per second, capacity is burst size."""
    9. def __init__(self, rate, capacity):
    10. self.rate = rate
    11. self.capacity = capacity
    12. self.tokens = capacity
    13. self.updated = time.monotonic()
    14. self.lock = asyncio.Lock()
    15. async def acquire(self):
    16. while True:
    17. async with self.lock:
    18. now = time.monotonic()
    19. self.tokens = min(self.capacity,
    20. self.tokens + (now - self.updated) * self.rate)
    21. self.updated = now
    22. if self.tokens >= 1:
    23. self.tokens -= 1
    24. return
    25. wait = (1 - self.tokens) / self.rate
    26. await asyncio.sleep(wait)
    27. class LLMGateway:
    28. def __init__(self, bucket, max_retries=3):
    29. self.queue = asyncio.PriorityQueue()
    30. self.bucket = bucket
    31. self.max_retries = max_retries
    32. self.done = {} # Idempotency table: task_id -> result
    33. self.dead_letter = [] # Dead-letter list: task, error message
    34. self._seq = itertools.count()
    35. async def submit(self, task_id, prompt, priority=PRIORITY_LOW):
    36. if task_id in self.done: # Skip tasks that are already completed
    37. return
    38. await self.queue.put((priority, next(self._seq), task_id, prompt, 0))
    39. async def worker(self, call_model):
    40. while True:
    41. priority, _, task_id, prompt, attempt = await self.queue.get()
    42. try:
    43. await self.bucket.acquire()
    44. self.done[task_id] = await call_model(prompt)
    45. except Exception as err:
    46. if attempt + 1 >= self.max_retries:
    47. self.dead_letter.append((task_id, prompt, str(err)))
    48. else:
    49. await asyncio.sleep(2 ** attempt + random.random())
    50. await self.queue.put(
    51. (priority, next(self._seq), task_id, prompt, attempt + 1))
    52. finally:
    53. self.queue.task_done()
    54. async def fake_model(prompt):
    55. await asyncio.sleep(0.05)
    56. if random.random() < 0.2:
    57. raise RuntimeError("429 Too Many Requests")
    58. return f"Result: {prompt}"
    59. async def main():
    60. gateway = LLMGateway(TokenBucket(rate=10, capacity=10))
    61. for i in range(8):
    62. priority = PRIORITY_HIGH if i == 0 else PRIORITY_LOW
    63. await gateway.submit(f"t{i}", f"prompt {i}", priority)
    64. workers = [asyncio.create_task(gateway.worker(fake_model)) for _ in range(3)]
    65. await gateway.queue.join()
    66. for w in workers:
    67. w.cancel()
    68. print(f"Succeeded: {len(gateway.done)}, dead-letter: {len(gateway.dead_letter)}")
    69. asyncio.run(main())

    Code notes:

    1. The tuple in PriorityQueue is ordered by (priority, sequence number, …). The sequence number preserves first-in-first-out ordering within the same priority and avoids comparing task content.
    2. Retries keep their original priority. A failing task is not downgraded because it was retried.
    3. queue.join() only returns after every task (including tasks added during retries) has called task_done. A retried task is re-enqueued before task_done is called, so the counter does not reach zero prematurely.
    4. The done dict 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”.
    5. 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.

    1. 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.
    2. 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.
    3. 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.