Compliant Use of Expiring LLM API Credits and Concurrent Request Scheduling

    This guide explains how to use expiring large language model API credits responsibly and efficiently. It covers compliance checks, suitable workloads, token-based cost accounting, concurrency control, rate limiting, retry and idempotency strategies, quota alerts, circuit breakers, multi-provider gateways, troubleshooting, and an operational checklist. The goal is to spend legitimate credits on valuable, reusable work—not to generate meaningless traffic simply to exhaust a balance.

    Confirm That the Credits May Be Used

    Before starting, verify three things.

    First, check whether the provider’s terms allow batch requests and whether they impose fair-use or rate limits. Many platforms cap concurrency, requests per minute, and tokens per minute. Exceeding those limits can cause throttling or even account suspension.

    Second, confirm ownership and scope. Credits may be restricted to a specific model, project, or department. They may also have an expiration date or be non-transferable. Record the total balance, remaining balance, expiration date, and permitted scope in an internal ledger before use.

    Third, verify that the data may be sent to a third-party model. Documents containing customer information, employee data, or unpublished source code should be redacted first, or processed only by a provider covered by a signed Data Processing Agreement (DPA). Before sending data, confirm the following:

    • Do the redaction rules cover names, phone numbers, government ID numbers, internal domains, API keys, and other sensitive fields?
    • How long does the provider retain logs, and how are deletion requests submitted?
    • Have the data owner and the security or legal team approved the batch before it goes live?

    Use only credits that your organization legitimately owns. Sending large numbers of meaningless requests to inflate usage may violate provider rules. The methods in this article are intended to apply expiring credits to useful work, not to consume them for their own sake.

    Which Workloads Are Suitable

    The objective of credit management is compliant, valuable, and reusable output. Suitable workloads generally have three characteristics: they process a substantial amount of input, produce genuinely useful output, and generate results that can be reused.

    • Long-document summarization and information extraction: Split technical specifications, historical logs, and product manuals into segments, then generate summaries or structured data for each segment. The results can be stored in an internal knowledge base for later retrieval.
    • Synthetic data generation: Create question-and-answer pairs for fine-tuning models in a specialized domain. Human reviewers should sample the generated data and remove inaccurate or duplicate examples.
    • Code comments and documentation: Add function descriptions and documentation to legacy code. Generated comments must pass code review before they are merged into the main branch.

    Unsuitable workloads include requests submitted only to consume credits, repeated submissions of identical content, tasks whose results nobody will use, tasks involving sensitive data without approval, and any attempt to bypass rate limits.

    Each batch should satisfy the following boundaries:

    • It has a clearly defined deliverable, owner, and deadline.
    • Inputs are split using a fixed segment length. Each segment remains below the model’s context limit while reserving space for the output.
    • Estimated cost stays within the batch budget.
    • Results undergo human sampling before being written to a knowledge base or code repository.

    Token Accounting

    A request’s cost depends on both input and output tokens:

    1. Request cost = (input tokens × input price + output tokens × output price) / 1,000,000

    Providers commonly quote prices per million tokens, which is why the formula divides by 1,000,000. The total cost of a batch is the sum of all request costs. Output tokens are often more expensive than input tokens, and the output count is also constrained by max_tokens.

    Use the following accounting rules:

    • usage fields: Use the usage object returned by the provider instead of estimating from character counts. In OpenAI-compatible formats, input and output usage usually appear as prompt_tokens and completion_tokens.
    • Streaming responses: Usage commonly appears only in the final data chunk and may require an option that enables usage reporting. If the connection drops before the final chunk, usage may be missing even though the provider may already have charged for the request. Reconcile usage against the provider’s billing records.
    • Truncated output: A finish_reason of length means the output reached the max_tokens limit. The truncated response is still billable, should be marked incomplete, and should not be inserted directly into a knowledge base.
    • Cached input: Input tokens served from a prompt cache may have a different price. Field names vary by provider, so track cached and uncached tokens separately.
    • Retries: A request may have completed and been billed even if the client received a timeout or network error. Retrying can therefore create a second charge. Account by task ID rather than by raw HTTP request count.

    The following ledger records usage by task ID. Multiple retries of the same task are counted only once locally:

    1. class UsageLedger:
    2. """Track usage by task ID; count retries only once locally."""
    3. def __init__(self, in_price_per_m: float, out_price_per_m: float):
    4. self.in_price = in_price_per_m
    5. self.out_price = out_price_per_m
    6. self._seen: set[str] = set()
    7. self.prompt_tokens = 0
    8. self.completion_tokens = 0
    9. def record(self, task_id: str, usage: dict | None) -> bool:
    10. if not usage or task_id in self._seen:
    11. return False
    12. self._seen.add(task_id)
    13. self.prompt_tokens += usage.get("prompt_tokens", 0)
    14. self.completion_tokens += usage.get("completion_tokens", 0)
    15. return True
    16. @property
    17. def cost(self) -> float:
    18. return (self.prompt_tokens * self.in_price
    19. + self.completion_tokens * self.out_price) / 1_000_000

    Deduplication only prevents duplicate local accounting. It cannot detect whether the provider charged twice for the same task. Reconcile the local ledger with the provider’s invoice or usage report once a week.

    Concurrency Scheduling and Backoff Retries

    Before scheduling requests, obtain the following values from the provider’s documentation or console:

    • Requests per second (QPS)
    • Maximum concurrency
    • Tokens per minute (TPM)
    • Credit units and expiration time

    The defaults in the example below are placeholders and must be replaced with the actual limits.

    Use two layers of scheduling. A semaphore limits concurrency, while a token bucket limits request rate. When both are used, keep a fixed acquisition order: obtain a token first, then acquire a concurrency slot. Release the concurrency slot immediately after the request completes. During backoff, the task must hold neither resource.

    This design avoids a common deadlock pattern in which Task A holds a concurrency slot while waiting for a token and Task B holds a token while waiting for a concurrency slot. A fixed order, combined with releasing resources before waiting, breaks the circular wait.

    Recommended retry rules:

    • 429 (rate limited): Prefer the Retry-After response header. If it is absent, use exponential backoff.
    • 500, 502, 503, and 504: Retry with exponential backoff.
    • 400, 401, 403, and 404: Do not retry. A 401 or 403 usually indicates an invalid key, missing permission, or unavailable model. A 400 generally indicates an invalid request body or parameter.
    • Timeouts: Treat them as retryable errors while preserving the same task ID.
    • Exponential backoff with full jitter: Select a random delay in [0, min(cap, base × 2^attempt)]. Random jitter prevents many tasks from retrying simultaneously and creating another traffic spike.
    • Retry budget: If retries during the most recent hour exceed 10% of total requests, pause the batch and raise an alert.

    Use a fixed task ID to provide idempotency. Every task should receive one ID, and all retries should reuse it. If the provider supports the Idempotency-Key header, place the task ID in that header. If it does not, rely on local deduplication. When storing results, use the task ID as the primary key and perform an upsert so that the same result cannot be inserted twice.

    The complete example follows:

    1. import asyncio
    2. import os
    3. import random
    4. import time
    5. import httpx
    6. BASE_URL = "https://api.example.com/v1/chat/completions" # Replace with provider URL
    7. MODEL = "your-model-name"
    8. API_KEY = os.environ["LLM_API_KEY"] # Read the key only from an environment variable
    9. MAX_CONCURRENCY = 8 # Maximum concurrency
    10. RATE_PER_SECOND = 5.0 # Rate limit (QPS)
    11. MAX_RETRIES = 5
    12. TIMEOUT_SECONDS = 60.0
    13. RETRYABLE = {429, 500, 502, 503, 504}
    14. class TokenBucket:
    15. """Token bucket: replenish tokens at a fixed rate and wait when empty."""
    16. def __init__(self, rate: float, capacity: float):
    17. self.rate = rate
    18. self.capacity = capacity
    19. self.tokens = capacity
    20. self.updated = time.monotonic()
    21. self.lock = asyncio.Lock()
    22. async def acquire(self) -> None:
    23. async with self.lock:
    24. while True:
    25. now = time.monotonic()
    26. self.tokens = min(self.capacity,
    27. self.tokens + (now - self.updated) * self.rate)
    28. self.updated = now
    29. if self.tokens >= 1:
    30. self.tokens -= 1
    31. return
    32. await asyncio.sleep((1 - self.tokens) / self.rate)
    33. def backoff_delay(attempt: int, base: float = 1.0, cap: float = 30.0) -> float:
    34. """Full jitter: random delay in [0, min(cap, base * 2^attempt)]."""
    35. return random.uniform(0, min(cap, base * (2 ** attempt)))
    36. async def call_llm(client, sem, bucket, ledger, task_id, messages):
    37. payload = {"model": MODEL, "messages": messages, "max_tokens": 1024}
    38. headers = {"Authorization": f"Bearer {API_KEY}", "Idempotency-Key": task_id}
    39. for attempt in range(MAX_RETRIES + 1):
    40. await bucket.acquire() # Fixed order: acquire a token first
    41. resp = None
    42. async with sem: # Then acquire a concurrency slot
    43. try:
    44. resp = await client.post(BASE_URL, json=payload,
    45. headers=headers, timeout=TIMEOUT_SECONDS)
    46. except (httpx.TimeoutException, httpx.TransportError):
    47. resp = None
    48. # The slot is released after leaving async with; backoff holds no resources
    49. if resp is not None and resp.status_code == 200:
    50. body = resp.json()
    51. ledger.record(task_id, body.get("usage"))
    52. choice = body["choices"][0]
    53. status = "truncated" if choice.get("finish_reason") == "length" else "ok"
    54. return {"task_id": task_id, "status": status,
    55. "content": choice["message"]["content"]}
    56. if resp is not None and resp.status_code not in RETRYABLE:
    57. return {"task_id": task_id, "status": "failed",
    58. "code": resp.status_code}
    59. if attempt == MAX_RETRIES:
    60. break
    61. retry_after = resp.headers.get("Retry-After") if resp is not None else None
    62. if retry_after and retry_after.isdigit():
    63. delay = float(retry_after)
    64. else:
    65. delay = backoff_delay(attempt)
    66. await asyncio.sleep(delay)
    67. return {"task_id": task_id, "status": "failed", "code": "retries_exhausted"}
    68. async def run_batch(tasks, in_price, out_price):
    69. sem = asyncio.Semaphore(MAX_CONCURRENCY)
    70. bucket = TokenBucket(rate=RATE_PER_SECOND, capacity=RATE_PER_SECOND)
    71. ledger = UsageLedger(in_price, out_price)
    72. async with httpx.AsyncClient() as client:
    73. results = await asyncio.gather(*(
    74. call_llm(client, sem, bucket, ledger, task_id, messages)
    75. for task_id, messages in tasks
    76. ))
    77. return results, ledger
    78. if __name__ == "__main__":
    79. demo = [("doc-0001", [{"role": "user", "content": "Summarize the following: ..."}])]
    80. results, ledger = asyncio.run(run_batch(demo, in_price=2.0, out_price=8.0))
    81. print(results)
    82. print(f"Input tokens: {ledger.prompt_tokens}, output tokens: {ledger.completion_tokens}")
    83. print(f"Estimated cost: {ledger.cost:.4f}")

    Price units must match the provider’s pricing scheme and should be expressed per million tokens. The prices in the example are placeholders.

    Quota Alerts and Circuit Breaking

    Quota alerts should be triggered before credits are exhausted or expire. Consider setting two thresholds:

    • Remaining credits fall below 20% of the original balance.
    • Less than seven days remain before expiration.

    When either condition is met, notify the owner through a designated channel, such as email or an internal messaging system.

    A circuit breaker stops consumption when abnormal conditions occur. Automatically pause the batch when any of the following is observed:

    • The 429 rate exceeds 20% during the most recent five minutes.
    • Retries exceed 10% of total requests.
    • More than 10 requests fail consecutively.

    The following functions implement these checks. Adjust the thresholds to match the workload:

    1. def check_quota(remaining: float, total: float, days_left: float) -> list[str]:
    2. alerts = []
    3. if total > 0 and remaining / total < 0.2:
    4. alerts.append("Remaining credits are below 20% of the total")
    5. if days_left < 7:
    6. alerts.append("Less than seven days remain before expiration")
    7. return alerts
    8. def should_trip_breaker(requests: int, retries: int,
    9. status_429: int, errors: int) -> bool:
    10. if requests == 0:
    11. return False
    12. return (retries / requests > 0.10
    13. or status_429 / requests > 0.20
    14. or errors / requests > 0.20)

    After a circuit breaker trips, keep the batch paused until an owner confirms the cause and manually resumes it. Automatic recovery can trigger another large wave of requests before the underlying problem is resolved.

    Record every circuit-breaker event, alert, and recovery in an audit log, including the timestamp, batch ID, trigger condition, and operator. Audit records support post-incident reviews and demonstrate that credit usage followed internal controls.

    Multi-Provider Gateways

    When multiple providers are used, place a gateway between the application and the providers. The gateway exposes a unified interface while handling routing, metering, and failover internally.

    A gateway typically needs the following capabilities:

    • Unified request and response formats: Implement an adapter for each provider so that application code calls only the gateway.
    • Routing rules: Select a provider based on remaining credits, price, model capabilities, and data-compliance tags. Tasks containing sensitive data may be routed only to providers covered by an approved DPA.
    • Failover: Switch providers only for retryable errors such as 429 responses, 5xx responses, and timeouts. Before switching, confirm that the target provider supports the required model capabilities and satisfies the applicable data requirements.
    • Usage metering: Record the provider, model, task ID, and usage for every request to support reconciliation by provider.

    A gateway must not be used to bypass restrictions. Distributing requests across multiple accounts to evade per-account rate limits violates most providers’ terms. Gateway routing must be based on legitimate credits and concurrency limits permitted by each provider.

    Common Troubleshooting Cases

    Troubleshoot in the following order, eliminating configuration problems before investigating traffic behavior.

    1. 401 or 403: Check whether the key is valid and unexpired, whether it has access to the model, and whether the credits belong to the current project.
    2. 400: Check the request body, model name, and whether max_tokens exceeds the provider’s limit.
    3. 429: Check whether QPS or TPM limits have been exceeded. Reduce concurrency or request rate, and verify that retries honor Retry-After.
    4. Timeouts: Confirm that the request timeout is not shorter than the model’s actual generation time. For long documents, increase the timeout or reduce segment size.
    5. Partial failures: Rerun only failed task IDs. Do not resubmit tasks that already succeeded.
    6. Duplicate charges: Compare the local ledger with the provider’s billing records. If the invoice contains extra charges, check whether the retry logic resent a request that had already completed.
    7. Truncated output: When finish_reason is length, increase max_tokens or shorten the input segment. Do not insert truncated results directly into a knowledge base.

    Risk Review Checklist

    Before starting each batch, confirm the following:

    • The provider’s terms have been reviewed, including permission for batch requests and applicable rate limits.
    • Credit ownership, supported models, scope, and expiration date have been confirmed and recorded.
    • Input data has been redacted, or the provider is approved to process the data.
    • A DPA is in place where required, and log retention and deletion procedures are documented.
    • The data owner or security team has approved the batch.
    • Concurrency, rate, and per-request timeout limits are configured.
    • Backoff parameters, maximum retries, and the retry budget are configured.
    • Quota alert thresholds and recipients are configured.
    • Circuit-breaker conditions and recovery owners are defined.
    • Audit logging is enabled for calls, alerts, and circuit-breaker events.
    • Provider terms have not changed during the task; if they have, the review has been repeated.
    • A small sample batch has validated the cost estimate and has been reconciled against provider usage records.