Handling LLM API Queueing: Quota Alerts and Retry Design

    This article explains why LLM API calls can queue or fail with 429 and 503 errors even when credits remain. It covers how to build a local quota ledger with alerts, retries with exponential backoff, circuit breaking, and tiered endpoint fallback. The audience is backend engineers and tech leads who already use LLM APIs. The article also explains why burning leftover credits with test calls makes queueing worse. The numbers are starting points that you should calibrate against your platform's limits and your own traffic.

    Many engineers have run into this situation. Your API subscription is close to expiring, your account still has a sizable quota left, but when you make real calls, requests queue for a long time or you keep receiving 429 and 503 errors. To avoid wasting quota, some people send a large number of test calls before expiry, and this makes queueing worse.

    This article is for backend engineers and tech leads who have already integrated an LLM API and have some backend development experience. It assumes that each call returns token usage and that you can access application logs. It does not cover offline training or capacity planning for self-hosted GPU inference clusters. The numbers in this article are starting points. Recalibrate them against your platform’s limits and your own traffic.

    1. Distinguish Three Kinds of Slow Calls

    From the client side, slow responses and failures look the same, but the causes differ, and so do the fixes.

    Symptom Common cause Recommended handling
    429 returned even though the balance is high Hit the requests-per-minute (RPM) or tokens-per-minute (TPM) limit Retry after the Retry-After delay or with exponential backoff, and reduce concurrency
    503 returned, or responses become noticeably slow Overall platform load is high, and requests enter the backend queue Retry with backoff, set timeouts, and switch to another endpoint if needed
    Insufficient-quota error, or the local ledger shows the quota is used up Total credits or tokens are exhausted Pause non-critical submissions and wait for the billing period to reset, or request a quota increase

    RPM and TPM are rate limits. They are separate from the total credit balance. You can still be rate limited when plenty of quota remains, so check the error codes and response headers instead of only the balance.

    Wasted credits usually come from two causes. First, the quota is not planned across the billing period. Usage is too slow early on, then calls pile up near expiry and run into rate limits. Second, there is no fault-tolerance strategy. Requests fail on timeout, or they are retried blindly. Either way, the task does not finish, and the requests still occupy connections and consume quota.

    2. Build a Local Quota Ledger

    Platform consoles often show data with a delay, so the application needs to keep its own ledger. After each successful call, add the total_tokens value from the usage field in the response. If the response headers include remaining quota, use that value to calibrate the ledger.

    The following implementation works within a single process. It uses a lock for thread safety, writes to a temporary file and then calls os.replace so an interrupted write does not corrupt the state file, and batches disk writes so that not every call writes to disk.

    1. import json
    2. import logging
    3. import os
    4. import threading
    5. import time
    6. logger = logging.getLogger("quota")
    7. class QuotaLedger:
    8. def __init__(self, total_quota, alert_ratio=0.2, state_path="quota_state.json",
    9. flush_every=20, flush_interval=5.0):
    10. if total_quota <= 0:
    11. raise ValueError("total_quota must be greater than 0")
    12. self._lock = threading.Lock()
    13. self.total_quota = total_quota
    14. self.alert_threshold = total_quota * alert_ratio
    15. self.state_path = state_path
    16. self.flush_every = flush_every
    17. self.flush_interval = flush_interval
    18. self._pending = 0
    19. self._last_flush = time.monotonic()
    20. self.used = self._load()
    21. def _load(self):
    22. try:
    23. with open(self.state_path, "r", encoding="utf-8") as f:
    24. return int(json.load(f)["used"])
    25. except (FileNotFoundError, KeyError, ValueError, TypeError):
    26. return 0
    27. def _persist_locked(self):
    28. tmp = self.state_path + ".tmp"
    29. with open(tmp, "w", encoding="utf-8") as f:
    30. json.dump({"used": self.used}, f)
    31. f.flush()
    32. os.fsync(f.fileno())
    33. os.replace(tmp, self.state_path)
    34. self._pending = 0
    35. self._last_flush = time.monotonic()
    36. def record_usage(self, used_tokens):
    37. with self._lock:
    38. self.used += used_tokens
    39. self._pending += 1
    40. due = (self._pending >= self.flush_every
    41. or time.monotonic() - self._last_flush >= self.flush_interval)
    42. if due:
    43. self._persist_locked()
    44. remaining = self.total_quota - self.used
    45. if remaining <= self.alert_threshold:
    46. logger.warning("quota alert remaining=%s threshold=%s", remaining, self.alert_threshold)
    47. def calibrate(self, remaining_from_platform):
    48. with self._lock:
    49. self.used = self.total_quota - remaining_from_platform
    50. self._persist_locked()
    51. def remaining(self):
    52. with self._lock:
    53. return self.total_quota - self.used
    54. def flush(self):
    55. with self._lock:
    56. self._persist_locked()

    Keep the following points in mind when you use this code.

    • Risk of data loss: Batched writes mean that if the process crashes, you can lose the counts from up to the last flush_every calls. Call flush() before shutting down the service, and log the usage of each call so you can reconstruct the totals later.
    • Multiple processes or machines: A lock inside one process does not work across processes, and the file-based approach will overwrite changes from other processes. On a single machine with multiple processes, use an atomic UPDATE in SQLite. Across machines, use the equivalent operation in PostgreSQL or Redis. In Redis, use INCRBY.
    1. import sqlite3
    2. class SharedQuota:
    3. def __init__(self, db_path, quota_id, total_quota):
    4. self.db_path = db_path
    5. self.quota_id = quota_id
    6. conn = sqlite3.connect(db_path, timeout=10)
    7. try:
    8. with conn:
    9. conn.execute(
    10. "CREATE TABLE IF NOT EXISTS quota "
    11. "(id TEXT PRIMARY KEY, total INTEGER NOT NULL, used INTEGER NOT NULL DEFAULT 0)")
    12. conn.execute(
    13. "INSERT OR IGNORE INTO quota (id, total, used) VALUES (?, ?, 0)",
    14. (quota_id, total_quota))
    15. finally:
    16. conn.close()
    17. def consume(self, tokens):
    18. conn = sqlite3.connect(self.db_path, timeout=10)
    19. try:
    20. with conn:
    21. conn.execute(
    22. "UPDATE quota SET used = used + ? WHERE id = ?",
    23. (tokens, self.quota_id))
    24. total, used = conn.execute(
    25. "SELECT total, used FROM quota WHERE id = ?",
    26. (self.quota_id,)).fetchone()
    27. return total - used
    28. finally:
    29. conn.close()

    SQLite locks the database for writes within a transaction, so the UPDATE and the following SELECT read the state at the same point in time.

    • Calibration frequency: If every response includes the remaining balance, calibrate on each response. If responses do not include a balance field, calibrate periodically, for example once an hour, using console data or the platform’s API.
    • Billing period rollover: When a new billing period starts, reset both used and total, and record a period identifier. This prevents usage from the old and new periods from being added together.
    • Unit differences: Credits, tokens, and request counts may use different units on the platform. Use only one unit in the ledger, store the conversion ratio in configuration, and do not mix units.
    • Fallback when calibration fails: If a response header is missing or cannot be parsed, keep the local count, log a warning, and mark the state as “uncalibrated.” If calibration fails several times in a row, allow only P0 tasks to be submitted until calibration recovers.
    • Alerts: The example writes structured logs with logging. In production, report remaining as a metric to your monitoring system, and set alert rules for when it falls below the alert threshold.

    3. Retry 429 and 503 Errors with Backoff, and Add Timeouts and Circuit Breaking

    The goal of retrying with backoff is to let requests step out of the competition during congestion, rather than continuing to hit the platform.

    • 429: If the response includes a Retry-After header, wait for that duration first. If it does not, use exponential backoff with random jitter.
    • 503: Also use exponential backoff. If failures continue, the endpoint may be unhealthy, so hand the problem to a circuit breaker.
    • Timeouts: Do not retry by default. A timed-out request may still have run on the server and been billed, so retrying blindly consumes quota twice. Consider one retry only for P0 tasks where idempotency is clearly guaranteed.
    • Other 4xx errors: Do not retry errors such as 400, 401, or 403. Raise them directly and send an alert, because retrying will not change the result.

    These starting values set the boundaries for the retry logic. Tune them through load testing and log analysis.

    • Base backoff base is 1 second, and the single-wait cap cap is 20 seconds.
    • Total time limit for one task deadline is 60 seconds. After that, give up so that the task does not hold connections for a long time.
    • Circuit breaker: Open the breaker after 5 consecutive failures, and keep it open for 30 seconds. During recovery, allow only one probe request. Close the breaker only if the probe succeeds.
    1. import random
    2. import threading
    3. import time
    4. class RetryableError(Exception):
    5. def __init__(self, status, retry_after=None):
    6. super().__init__(f"HTTP {status}")
    7. self.status = status
    8. self.retry_after = retry_after
    9. class CircuitOpen(Exception):
    10. pass
    11. class CircuitBreaker:
    12. def __init__(self, failure_threshold=5, open_seconds=30.0):
    13. self.failure_threshold = failure_threshold
    14. self.open_seconds = open_seconds
    15. self._failures = 0
    16. self._opened_at = None
    17. self._probing = False
    18. self._lock = threading.Lock()
    19. def allow(self):
    20. with self._lock:
    21. if self._opened_at is None:
    22. return True
    23. ready = time.monotonic() - self._opened_at >= self.open_seconds
    24. if ready and not self._probing:
    25. self._probing = True
    26. return True
    27. return False
    28. def record_success(self):
    29. with self._lock:
    30. self._failures = 0
    31. self._opened_at = None
    32. self._probing = False
    33. def record_failure(self):
    34. with self._lock:
    35. self._failures += 1
    36. self._probing = False
    37. if self._failures >= self.failure_threshold:
    38. self._opened_at = time.monotonic()
    39. def call_with_retry(send, breaker, max_retries, base=1.0, cap=20.0, deadline_s=60.0):
    40. start = time.monotonic()
    41. attempt = 0
    42. while True:
    43. if not breaker.allow():
    44. raise CircuitOpen()
    45. try:
    46. result = send()
    47. except RetryableError as e:
    48. breaker.record_failure()
    49. attempt += 1
    50. if attempt > max_retries:
    51. raise
    52. if e.retry_after is not None:
    53. wait = e.retry_after
    54. else:
    55. wait = random.uniform(0, min(cap, base * 2 ** (attempt - 1)))
    56. if time.monotonic() - start + wait > deadline_s:
    57. raise
    58. time.sleep(wait)
    59. except TimeoutError:
    60. breaker.record_failure()
    61. raise
    62. else:
    63. breaker.record_success()
    64. return result

    Keep these points in mind when handling failures.

    • Count only 429, 503, and timeouts toward the circuit breaker. 400-class errors indicate a problem with the request itself, so they should not open the breaker.
    • When the breaker is open, the caller should degrade immediately, for example by queuing the task for later or switching to another endpoint, instead of waiting.
    • A failed or timed-out request may still have been billed. Use the usage data returned by the platform to record the cost if you can. If you cannot get it, estimate conservatively from the request length, and log the estimate.

    4. Fall Back Across Endpoints and Assign Task Tiers

    Task tiers determine which requests can use the remaining quota and which requests should yield.

    Tier Typical tasks Timeout Max retries Reserve threshold Endpoint fallback allowed
    P0 Core production workloads and requests that users wait on directly 60 seconds 3 0%, can use all remaining quota Yes
    P1 Important but deferrable tasks, such as summary generation 90 seconds 2 Stop when remaining quota falls below 20% Yes
    P2 Batch processing, reporting, offline evaluation 180 seconds 0 Stop when remaining quota falls below 50% No

    The reserve threshold means that before submitting a task, you check the remaining quota ratio. If the ratio is at or below the threshold, pause submission. This keeps a buffer for P0 tasks even when the quota is nearly exhausted.

    When you switch endpoints, consider two things. First, different endpoints may map to different model versions or rate limits, so output quality and billing may change after a switch. Verify this in advance. Second, only endpoints in the same model family work well as backups for each other. Otherwise, the application may behave inconsistently.

    1. from dataclasses import dataclass
    2. class QuotaReserved(Exception):
    3. pass
    4. @dataclass(frozen=True)
    5. class TierPolicy:
    6. timeout_s: float
    7. max_retries: int
    8. reserve_ratio: float
    9. allow_fallback: bool
    10. TIERS = {
    11. "P0": TierPolicy(timeout_s=60, max_retries=3, reserve_ratio=0.0, allow_fallback=True),
    12. "P1": TierPolicy(timeout_s=90, max_retries=2, reserve_ratio=0.2, allow_fallback=True),
    13. "P2": TierPolicy(timeout_s=180, max_retries=0, reserve_ratio=0.5, allow_fallback=False),
    14. }
    15. class Endpoint:
    16. def __init__(self, name, send):
    17. self.name = name
    18. self.send = send # send(request, timeout_s) -> (response, used_tokens)
    19. self.breaker = CircuitBreaker()
    20. def run_task(tier, request, endpoints, ledger, total_quota):
    21. policy = TIERS[tier]
    22. if ledger.remaining() / total_quota <= policy.reserve_ratio:
    23. raise QuotaReserved(f"{tier} task is at or below its reserve threshold; submission is paused")
    24. last_error = None
    25. for ep in endpoints: # already sorted by priority
    26. try:
    27. response, used = call_with_retry(
    28. lambda: ep.send(request, policy.timeout_s), # synchronous call, so the closure is safe
    29. ep.breaker,
    30. policy.max_retries,
    31. )
    32. except (RetryableError, TimeoutError, CircuitOpen) as e:
    33. last_error = e
    34. if not policy.allow_fallback:
    35. break
    36. continue
    37. ledger.record_usage(used)
    38. return response
    39. raise last_error

    run_task catches only errors that can fall back to another endpoint. Other errors propagate to the caller, which should log them and send an alert.

    5. Do Not Spend Quota on Test Calls

    Many people send a large number of test calls before a subscription expires, trying to use up the remaining quota. This approach has three problems. First, meaningless requests take up RPM and TPM, which makes real workloads queue longer. Second, a large volume of automated requests may trigger the platform’s abuse detection, which can violate the terms of service and lead to account restrictions. The remaining quota may then become unusable. Third, the credits spent on testing could have gone to critical workloads.

    A better approach is as follows.

    • Plan usage by business priority. Check your consumption progress midway through the billing period. If you are clearly behind, schedule P2 tasks over the remaining time instead of submitting everything near expiry.
    • Run load tests in an isolated environment with a separate, small budget. Use them only to verify that the retry, circuit breaker, and ledger logic behave correctly.
    • If the platform offers a batch interface or a lower-cost asynchronous interface, move offline tasks there.
    • If the quota is truly insufficient, request a quota incre