Stop Burning Your LLM API Quota: Async Queues, Rate Limiting, and Budget Governance
LLM API quotas are budget, not leftover credits. This article explains why uncontrolled call patterns waste enterprise token budgets, compares sync calls with async task queues and semantic routing, and shows how to combine token-bucket rate limiting, idempotent task persistence, retry with backoff, and budget alerts. A complete, runnable Python example demonstrates the whole pipeline.
Why Quotas Get Wasted: Loss of Control Over Call Rhythm
When an annual subscription is about to expire, accounts often have unused credits or quota, so some users fire off a flood of requests just to “use them up.” For an individual, the loss is limited to the remainder of a subscription.
Enterprise scenarios are different. An enterprise quota is a budget: every call is a cost item and consumes the same account’s requests-per-second (QPS) and tokens-per-minute (TPM) allowances. If business teams call the API whenever someone remembers to, two problems appear at once: low-value chatty calls fill up the quota, while genuinely important long-running inference tasks can’t get scheduled at critical moments.
So the issue isn’t whether the quota gets used up—it’s that request volume is driven by usage habits rather than by how much compute a task actually needs. Governance comes down to three principles. First, calls should revolve around explicit tasks and deliverables. Second, callers should manage their own pacing, including queuing, rate limiting, retry on failure, and budget caps. Third, every dollar spent should be traceable to a specific task and owner.
This article includes no benchmarks of specific model versions and no comparison of provider pricing or performance. The code is illustrative; before integrating, adapt the endpoint, parameter structure, and billing rules according to your provider’s documentation.
Three Common Bottlenecks
In real production systems, an LLM API call is rarely a simple “input, output” exchange. As concurrency grows and tasks get more complex, three problems typically emerge.
- Long-running calls block threads: Long documents or complex reasoning can take tens of seconds. Synchronous HTTP calls hold service threads, and once the thread pool is exhausted, other endpoints start timing out too.
- Quota limits collide with traffic spikes: Providers usually enforce QPS or TPM limits. Bursty peak-hour traffic easily triggers 429 errors. Without retry and queuing, tasks simply fail.
- Inconsistent multimodal parsing: Real-world inputs are often documents mixing PDFs, spreadsheets, and images. Without a unified parsing layer, the text fed to the model varies wildly in quality, and output accuracy drops accordingly. Files that fail to parse should be flagged separately—don’t call the model with incomplete content.
The common approach for all three problems is to move from synchronous to asynchronous requests, control the sending rate with a token bucket, and add a parsing and routing layer in front of the model.
Comparing Approaches
The following two tables compare common architectural choices. The right trade-off depends on your latency requirements, team size, and budget.
| Dimension | Synchronous calls | Async task queue |
|---|---|---|
| User wait time | Waits until the model returns | Returns a task ID immediately; results fetched later |
| Thread usage | Each request holds a thread until completion | Workers pull tasks by concurrency level; usage is controllable |
| Failure handling | Usually returns an error directly | Automatic retry; failed tasks can be re-queued |
| Complexity | Low | Medium; requires state storage and a task-query API |
| Best for | Short text, low-latency interactive Q&A | Long document analysis, batch generation, offline reports |
| Dimension | Single large model | Semantic routing |
|---|---|---|
| Cost | Even simple tasks hit the expensive model, driving costs up | Simple tasks go to lightweight models; overall cost is lower |
| Maintenance | One call path | Requires maintaining classification rules and adapters for multiple models |
| Risk | A model outage affects all tasks | Can degrade per category; smaller blast radius |
Choosing an Async Queue
In-memory queues are the simplest, but every queued task is lost when the process restarts—fine for prototyping only. In production, pick one of the following:
- Database table with polling: Low implementation cost; task state lives alongside business data. Suits teams handling a few thousand to tens of thousands of tasks per day.
- Redis Stream: High throughput, mature consumer-group semantics, but persistence must be configured correctly or messages can be lost on node failure.
- RabbitMQ or Kafka: Good for cross-team, cross-system message delivery, but operational overhead is clearly higher than the first two.
The code sample below uses a SQLite table as the persistent queue and depends only on the standard library plus httpx, so you can run it locally. For multi-instance deployments, switch to PostgreSQL or Redis Stream.
Setting Token-Bucket Rate-Limiting Parameters
A token bucket refills tokens at a fixed rate; each outgoing request takes one token, and when the bucket is empty, requests wait. It has two parameters:
- Refill rate: Set to roughly 80% of the provider’s limit, leaving headroom for retries and other services. If the provider allows 10 requests per second, set it to 8.
- Bucket capacity: Determines how many requests can burst at once. Too large a capacity and you’ll still hit 429s at peak; too small and normal fluctuations get throttled.
TPM is measured in tokens, so controlling request count alone isn’t enough. Estimate each request’s token count from its input length, then use a second token bucket to throttle by token consumption. When estimates run low, correct them with actual usage reported in the API response.
Designing a Degradation Strategy
When queue wait times exceed a threshold, you have three options: reschedule non-urgent tasks to off-peak windows; route simple tasks to a lightweight model; or return “will be processed later” to newly submitted low-priority tasks instead of queueing them. Degradation rules should live in configuration, and every switch should be logged for post-incident review.
The Qualitative Cost-Latency Trade-off
- Synchronous calls have the lowest latency but are the easiest to bring down under peak load.
- An async queue adds one result-polling step, so perceived wait time grows, but the system is far more stable.
- Semantic routing lowers average cost at the price of maintaining a classification rule set. Misclassification can send complex tasks to underpowered models.
- Stricter rate limiting means fewer failures but slower task completion. Set thresholds separately by business priority.
Offline batch processing and online urgent requests should also be designed separately. Run offline tasks off-peak at lower concurrency. Urgent tasks get their own queue with higher priority so batch jobs can’t crowd them out.
Boundaries for Agent Workflows
An agent workflow is one where the model autonomously plans steps, calls tools, and decides the next move based on results. It handles multi-step tasks well, but it also amplifies cost and risk: the model may loop endlessly on tool calls, or perform write operations without confirmation.
When deploying, enforce these boundaries:
- Step limits: Set a maximum number of steps and tool calls per workflow; force-stop beyond that and save current state.
- Tool allowlist: Agents may only call pre-registered tools, with validation on parameter types and value ranges.
- Human review: Sending email, modifying databases, initiating payments—these must go through human confirmation, never executed directly by the model.
- Full audit trail: Log every step’s input, output, tool calls, and duration. Redact sensitive data before logging; never persist raw sensitive data.
- Budget ownership: Bind each workflow to a project or owner so overspend can be traced to a specific task.
Every agent step should be an independent task in the system, entering the same queue. That way rate limiting, retries, and budget alerts apply to agents too.
Runnable Code: Persistent Queue, Rate Limiting, and Budget Alerts
Requirements: Python 3.10+, plus pip install httpx. SQLite ships with the standard library.
The code does the following: saves tasks to SQLite with idempotent enqueueing via idem_key; redacts phone numbers, ID numbers, and emails before submission; throttles sending with a token bucket; retries with exponential backoff only on 429, 5xx, and network timeouts; moves tasks past the retry limit to a dead-letter state; and alerts at 80% of the monthly token budget, pausing calls at 100%.
# Dependencies: Python 3.10+, pip install httpx# Run: export LLM_API_KEY=your_key && python task_agent.py# Notes: Tasks are stored in a SQLite file; unfinished tasks resume after restart.# The API structure follows the OpenAI-compatible format; adapt it to your# provider's documentation before integrating.import asyncioimport loggingimport osimport randomimport reimport sqlite3import timeimport uuidimport httpxAPI_URL = os.environ.get("LLM_API_URL", "https://api.example.com/v1/chat/completions")API_KEY = os.environ["LLM_API_KEY"] # Key is read only from env vars, never hardcoded or loggedMODEL = os.environ.get("LLM_MODEL", "your-model-name")DB_PATH = os.environ.get("TASK_DB", "tasks.db")REQUEST_TIMEOUT = 60.0 # Per-request timeout in secondsMAX_RETRIES = 4 # Max attempts for transient errors before dead-letteringBASE_BACKOFF = 2.0 # Exponential backoff base in secondsWORKER_COUNT = 3 # Number of concurrent workersRATE_PER_SEC = 2.0 # Token bucket refill rate; ~80% of provider limitBURST = 4 # Token bucket capacity; allowed instantaneous burstMONTHLY_TOKEN_BUDGET = 5_000_000 # Monthly token budget cap; set to your team's actual budgetALERT_RATIO = 0.8 # Alert when usage hits 80% of budgetPAUSE_SECONDS = 60 # Worker pause duration after budget circuit-breaklogging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")log = logging.getLogger("task_agent")PHONE_RE = re.compile(r"1[3-9]\d{9}")ID_CARD_RE = re.compile(r"\d{17}[\dXx]")EMAIL_RE = re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+")class TransientError(Exception):"""Retryable error, e.g. 429 or 5xx."""def desensitize(text: str) -> str:text = PHONE_RE.sub("[phone number]", text)text = ID_CARD_RE.sub("[ID number]", text)text = EMAIL_RE.sub("[email]", text)return textdef get_db() -> sqlite3.Connection:conn = sqlite3.connect(DB_PATH)conn.row_factory = sqlite3.Rowconn.executescript("""CREATE TABLE IF NOT EXISTS tasks (id TEXT PRIMARY KEY,idem_key TEXT UNIQUE NOT NULL,prompt TEXT NOT NULL,status TEXT NOT NULL, -- pending / running / done / failed / deadattempts INTEGER NOT NULL DEFAULT 0,next_run_at REAL NOT NULL,result TEXT,error TEXT,created_at REAL NOT NULL);CREATE TABLE IF NOT EXISTS usage (month TEXT PRIMARY KEY,tokens INTEGER NOT NULL DEFAULT 0);""")conn.commit()return conndef submit_task(conn: sqlite3.Connection, prompt: str, idem_key: str) -> str:"""Each idem_key is enqueued only once; duplicate submissions return the existing task ID."""now = time.time()task_id = str(uuid.uuid4())try:conn.execute("INSERT INTO tasks (id, idem_key, prompt, status, next_run_at, created_at) ""VALUES (?, ?, ?, 'pending', ?, ?)",(task_id, idem_key, desensitize(prompt), now, now),)conn.commit()return task_idexcept sqlite3.IntegrityError:row = conn.execute("SELECT id FROM tasks WHERE idem_key = ?", (idem_key,)).fetchone()return row["id"]def recover_running(conn: sqlite3.Connection) -> None:"""After an abnormal exit, put leftover running tasks back to pending."""conn.execute("UPDATE tasks SET status = 'pending' WHERE status = 'running'")conn.commit()def claim_next(conn: sqlite3.Connection):now = time.time()row = conn.execute("SELECT id FROM tasks WHERE status = 'pending' AND next_run_at <= ? ""ORDER BY created_at LIMIT 1",(now,),).fetchone()if row is None:return Nonecur = conn.execute("UPDATE tasks SET status = 'running' WHERE id = ? AND status = 'pending'",(row["id"],),)conn.commit()if cur.rowcount == 0:return Nonereturn conn.execute("SELECT * FROM tasks WHERE id = ?", (row["id"],)).fetchone()def current_usage(conn: sqlite3.Connection) -> int:month = time.strftime("%Y-%m")row = conn.execute("SELECT tokens FROM usage WHERE month = ?", (month,)).fetchone()return row["tokens"] if row else 0def add_usage(conn: sqlite3.Connection, tokens: int) -> None:month = time.strftime("%Y-%m")conn.execute("INSERT INTO usage (month, tokens) VALUES (?, ?) ""ON CONFLICT(month) DO UPDATE SET tokens = tokens + excluded.tokens",(month, tokens),)conn.commit()def budget_ok(conn: sqlite3.Connection) -> bool:used = current_usage(conn)if used >= MONTHLY_TOKEN_BUDGET:log.error("Monthly usage %s has hit the budget cap; calls paused", used)return Falseif used >= MONTHLY_TOKEN_BUDGET * ALERT_RATIO:log.warning("Monthly usage %s has exceeded %d%% of the budget", used, int(ALERT_RATIO * 100))return Trueclass TokenBucket:def __init__(self, rate: float, capacity: int):self.rate = rateself.capacity = capacityself.tokens = float(capacity)self.updated = time.monotonic()self.lock = asyncio.Lock()async def acquire(self) -> None:async with self.lock:while True:now = time.monotonic()self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)self.updated = nowif self.tokens >= 1:self.tokens -= 1returnawait asyncio.sleep((1 - self.tokens) / self.rate)async def call_llm(client: httpx.AsyncClient, prompt: str) -> tuple[str, int]:try:resp = await client.post(API_URL,headers={"Authorization": f"Bearer {API_KEY}"},json={"model": MODEL, "messages": [{"role": "user", "content": prompt}]},timeout=REQUEST_TIMEOUT,)except httpx.TransportError as exc:raise TransientError(f"network or timeout error: {type(exc).__name__}") from excif resp.status_code in (429, 500, 502, 503, 504):raise TransientError(f"HTTP {resp.status_code}")resp.raise_for_status() # Other 4xx errors are permanent; do not retrydata = resp.json()text = data["choices"][0]["message"]["content"]tokens = data.get("usage", {}).get("total_tokens", 0)return text, tokensasync def process(conn: sqlite3.Connection, bucket: TokenBucket,client: httpx.AsyncClient, task: sqlite3.Row) -> None:attempts = task["attempts"] + 1try:await bucket.acquire()text, tokens = await call_llm(client, task["prompt"])add_usage(conn, tokens)conn.execute("UPDATE tasks SET status = 'done', result = ?, attempts = ? WHERE id = ?",(text, attempts, task["id"]),)conn.commit()except TransientError as exc:if attempts >= MAX_RETRIES:conn.execute("UPDATE tasks SET status = 'dead', attempts = ?, error = ? WHERE id = ?",(attempts, str(exc), task["id"]),)else:delay = BASE_BACKOFF * (2 ** (attempts - 1)) * random.uniform(0.5, 1.0)conn.execute("UPDATE tasks SET status = 'pending', attempts = ?, error = ?, ""next_run_at = ? WHERE id = ?",(attempts, str(exc), time.time() + delay, task["id"]),)conn.commit()except Exception as exc: # Permanent error, e.g. 400, 401, or unexpected response structureconn.execute("UPDATE tasks SET status = 'failed', attempts = ?, error = ? WHERE id = ?",(attempts, repr(exc)[:500], task["id"]),)conn.commit()async def worker(conn: sqlite3.Connection, bucket: TokenBucket,client: httpx.AsyncClient, name: int) -> None:while True:if not budget_ok(conn):await asyncio.sleep(PAUSE_SECONDS)continuetask = claim_next(conn)if task is None:await asyncio.sleep(1)continuelog.info("worker %d processing task %s", name, task["id"])await process(conn, bucket, client, task)def unfinished(conn: sqlite3.Connection) -> int:return conn.execute("SELECT COUNT(*) FROM tasks WHERE status IN ('pending', 'running')").fetchone()[0]async def main() -> None:conn = get_db()recover_running(conn)# Example: submitting the same report twice with the same idem_key executes it only oncesubmit_task(conn, "Please summarize the following quarterly report: ... contact 13800138000", idem_key="report-2026-q3")submit_task(conn, "Please summarize the following quarterly report: ... contact 13800138000", idem_key="report-2026-q3")bucket = TokenBucket(RATE_PER_SEC, BURST)async with httpx.AsyncClient() as client:workers = [asyncio.create_task(worker(conn, bucket, client, i))for i in range(WORKER_COUNT)]while unfinished(conn) > 0: # Waits indefinitely during budget circuit-break; needs manual interventionawait asyncio.sleep(1)for w in workers:w.cancel()for row in conn.execute("SELECT id, status, error FROM tasks"):print(row["id"], row["status"], row["error"])if __name__ == "__main__":asyncio.run(main())
How to run:
export LLM_API_KEY=your_keyexport LLM_API_URL=your_providers_endpointpython task_agent.py
A few design decisions deserve explanation. Idempotency is enforced by the database’s UNIQUE constraint rather than application logic, so it holds even under concurrent submissions. Only transient errors are retried; permanent errors like 400 or 401 (bad parameters or permissions) are marked failed immediately—retrying them just burns quota. Backoff delays include random jitter to prevent multiple workers from retrying at the same instant and creating a new traffic spike. If the process crashes, leftover running tasks are put back to pending on the next startup. This assumes a single consumer process; for multi-instance deployments, switch to a queue with lease-based claiming.
The code assumes an OpenAI-compatible API returning choices and usage fields. When integrating with other providers, replace the request structure and parsing logic in call_llm.
Pre-Launch Checklist
- Idempotency: Every business request has a stable
idem_key; duplicate submissions never trigger duplicate billing. - Redaction: Phone numbers, ID numbers, emails, and other sensitive fields are handled before enqueueing; logs and result storage follow the same rules.
- Budget alerts: Two thresholds—alert at 80% and circuit-break at 100%. Alerts go to the responsible owner, and there is a documented manual recovery process after a circuit-break.
- Persistence: The task table is backed up; unfinished tasks resume after a process restart.
- Retry limits: A concrete maximum attempt count for transient errors; permanent errors are never retried.
- Dead-letter handling: Dead-letter tasks have an assigned owner who reviews them periodically; retention and cleanup rules are documented in the ops runbook.
- Timeouts: Set for individual requests, entire workflows, and queue waits.
- Monitoring: Track queue length, wait time, failure rate, 429 counts, and daily token usage.
- Key management: API keys are read only from environment variables or a secret manager—never from code, logs, or tickets.
- Degradation plan: When rate limiting or a circuit-break triggers, there is a defined fallback path and notification channel.
