Calling LLM APIs in Production: Handling Rate Limits and Controlling Credit Costs
This guide covers how to keep LLM API calls stable and affordable in production. It explains how to evaluate stability, pricing, and model fit. It also shows how to handle rate limits and timeouts with asynchronous tasks, exponential backoff, and failover routing, and how to manage prepaid credits through task prioritization, semantic caching, and monitoring.
Calling LLM Services in Production: Handling Rate Limits and Controlling Credit Costs
Introduction
Once a large language model moves from prototype to production, the questions change. Developers stop asking whether the model produces good output. They start asking whether the service can be called reliably and whether costs stay under control. In real projects, two problems come up most often. The first is that requests during peak hours get queued or rate-limited, which slows responses and sometimes causes failures. The second is that prepaid credits are close to expiring, and the team has to use them even though it does not have enough real workload to consume them.
These two problems look separate, but they share one root cause: the service’s stability, its billing rules, and the business requirements are not aligned. This article covers three areas: evaluation criteria, engineering practices, and cost strategies. Each section includes steps you can check or reuse directly. The code in this article is illustrative. Adapt it to the SDK and business scenario you use.
1. Core Dimensions for Evaluating LLM Services
When choosing an LLM API, look beyond model capability, such as reasoning level and context window length. Evaluate the following three dimensions from an engineering perspective.
1.1 Stability and Concurrency
Services that share compute across many users usually set limits on concurrent requests and requests per minute. When demand exceeds the available capacity, new requests wait in a queue. During evaluation, confirm the following:
- The account-level concurrency limit and the requests-per-minute limit.
- The average and P95 response times under full load, not only during idle periods.
- The behavior when limits are exceeded: whether the service returns HTTP 429 immediately or queues the request, and whether the wait time has an upper bound.
Before you commit to a provider, run a load test with your real peak request volume. Record the failure rate and the latency distribution.
1.2 Billing Models and Resource Lifecycle
There are two common billing models. Pay-as-you-go bills by actual token usage. It has no upfront commitment, but the unit price is usually higher. Prepaid credits are usually discounted, but they come with an expiration date. The table below compares the two.
| Item | Pay-as-you-go | Prepaid Credits |
|---|---|---|
| Unit price | Standard price | Usually discounted |
| Validity period | None | Commonly several months to one year, subject to the provider’s terms |
| Expiration handling | Not applicable | Unused credits may expire. Confirm refund rules in advance. |
| Concurrency and rate limits | Set by account tier | Some plans are tied to credit quota. Confirm whether limits differ. |
| Best for | Projects with volatile usage or unstable business needs | Projects with predictable, steady usage |
Estimate your monthly usage before deciding how much to buy. When credits exceed real needs, teams often make unnecessary calls just to avoid wasting them. These calls add hidden cost.
1.3 Matching Tasks to Models
Not every task needs the most capable model. Text classification, keyword extraction, and format conversion usually work well with a lightweight model, and the cost is a fraction of what a large model costs. Running high-value and low-value tasks on the same model wastes credits and makes peak-hour queuing worse.
Build a small evaluation set for each task type. Include dozens to hundreds of real samples. Test each candidate model for accuracy, latency, and cost per call. Use the results to decide which model handles which task.
2. Engineering Practices for Rate Limits and High Latency
2.1 Asynchronous Task Processing
The main purpose of an asynchronous API is to keep clients from waiting on a synchronous response for a long time, which reduces connection timeouts. Asynchronous processing suits background tasks that do not need an immediate response, such as daily report generation and data cleaning:
- The client submits a task and receives a task ID.
- The client gets the result by polling or through a callback. When polling, set an interval, starting at around 5 seconds and increasing gradually. This prevents polling itself from creating new request pressure.
- Set a task timeout and a maximum retry count. When a task times out, log the failure reason and trigger an alert.
Asynchronous processing does not guarantee shorter queue times on the server. Queue times depend mainly on the provider’s compute scheduling and your account’s rate-limit quota. The benefit of async is that clients no longer depend on waiting synchronously. Server-side pressure still needs to be controlled through rate limits.
2.2 Retries and Exponential Backoff
When the API returns HTTP 429, retrying immediately usually does not help. It also adds load on the server. Use exponential backoff, and follow these rules:
- Retry only temporary errors, such as 429 (rate limit), timeouts, and 503. Errors such as 400, 401, and 403 mean the request or its permissions are wrong. Retrying will not fix them, so fail immediately.
- Prefer the wait time specified in the
Retry-Afterresponse header. - Set a maximum backoff per retry and a maximum number of retries to avoid waiting indefinitely.
- Add random jitter so that many clients do not retry at the same moment.
- Retry only when the request is idempotent, or when your system can detect duplicate requests. Otherwise, a retry can produce duplicate output, charge the account twice, or write duplicate data.
The code below is pseudocode. The caller must map the SDK’s exception types to RateLimitError and TransientError, and replace make_api_request with the actual SDK call.
import randomimport timeclass RateLimitError(Exception):"""Defined by the caller: map the HTTP 429 returned by the SDK to this exception."""class TransientError(Exception):"""Defined by the caller: map timeouts, 503 errors, and other retryable errors to this exception."""MAX_RETRIES = 5 # Maximum number of attemptsBASE_DELAY = 1.0 # Base backoff time in secondsMAX_DELAY = 30.0 # Maximum backoff per retry in secondsJITTER_MAX = 1.0 # Maximum random jitter in secondsdef call_llm_with_retry(prompt, make_api_request, retry_after=None):"""make_api_request: The actual request function supplied by the caller (pseudocode placeholder).retry_after: If the response includes a Retry-After header, use that value first."""for attempt in range(MAX_RETRIES):try:return make_api_request(prompt)except (RateLimitError, TransientError) as err:if attempt == MAX_RETRIES - 1:raiseif retry_after is not None:delay = retry_afterelse:delay = min(BASE_DELAY * (2 ** attempt), MAX_DELAY)delay += random.uniform(0, JITTER_MAX)time.sleep(delay)# This line should be unreachable. It is kept so static analysis passes.raise RuntimeError("Retry attempts exhausted")
The example does not handle non-retryable errors such as 400 or 401. It raises them directly, which matches the principle described above.
2.3 Multi-Endpoint Routing and Failover
A single model endpoint is a clear point of risk. An API gateway or a self-hosted proxy layer can distribute requests across multiple endpoints or backup models. General-purpose cloud platforms and self-built gateways typically support load-balancing strategies based on weight, latency, or health checks.
When you implement this, keep the following in mind:
- Health checks: Probe each endpoint regularly for availability and latency. After a set number of consecutive failures, mark the endpoint as unavailable.
- Circuit breaking: When an endpoint’s error rate exceeds a threshold, stop sending requests to it. After a cooldown period, send a small amount of traffic to test whether it has recovered.
- Output consistency across models: After switching to a backup model, the output format, language style, and capabilities may change. Validate critical outputs, for example by checking JSON structure. Log every switch so you can investigate problems later.
- Plan for the cost and quota of backup models too. Otherwise, switching over could trigger new overage charges.
2.4 Troubleshooting Checklist for Rate Limits and Timeouts
When you encounter an error, use the table below to check each possible cause.
| Symptom | Likely Cause | Recommended Action |
|---|---|---|
| HTTP 429 | Concurrency or requests-per-minute limit exceeded | Enable exponential backoff, reduce concurrency, and check whether batch jobs are running at the same time |
| Request timeout | Heavy server-side queuing or network issues | Check timeout settings, switch to the asynchronous API, or fail over to a backup endpoint |
| Full queue or HTTP 503 | Limited server-side compute | Pause low-priority tasks, enable circuit breaking, and wait for recovery |
| 401 or 403 | Invalid key, insufficient permissions, or exhausted credits | Check the key, account status, and remaining quota. Do not retry. |
| Abnormal output format | Model switch or prompt template change | Add format validation and roll back to the last stable version |
3. Optimizing Compute Costs and Credit Usage
3.1 Dispatching Tasks by Priority
Build a unified scheduling module on the business side and sort tasks into priority tiers. Real-time, user-facing requests get the highest priority. Offline tasks, such as log summarization and data cleaning, get lower priority. They can run during periods of spare capacity.
When credits are close to expiring, the scheduler can dispatch a batch of low-priority tasks. This is acceptable only if those tasks have real business value, such as scheduled weekly report generation or pending historical data labeling. Never create invalid requests, duplicate calls, or large batches of test traffic just to use up quota. This wastes resources and may violate the provider’s terms of service.
3.2 Semantic Caching
In many business scenarios, users ask very similar questions. Examples include common questions about the same product documentation. Semantic caching works like this: convert each request into a vector, compare it with the vectors of cached requests, and return the cached result directly when similarity exceeds a threshold. The model is not called in that case.
Define the following parameters when you implement this:
- Embedding model and comparison method: Usually a text embedding model, with cosine similarity to compare vectors.
- Similarity threshold: No single value works for every case. Common starting points fall between 0.92 and 0.95. Test with a manually labeled sample set. A threshold that is too low returns wrong answers. A threshold that is too high produces a very low hit rate.
- Hit rate: Measure it with real traffic. Do not estimate it from intuition. If the hit rate is lower than expected, your requests are diverse, and the cache will provide limited benefit.
- Time to live (TTL): Static knowledge questions can use a longer TTL, such as several days. Content involving real-time data or prices should use a shorter TTL, such as a few hours or less.
- Invalidation: When the model version, prompt template, or knowledge base changes, clear the affected cache entries. Otherwise, the cache returns outdated answers.
Semantic caching has several risks. First, cached content can go stale and no longer match the current state of the business. Second, cache keys and values may contain private user data. Isolate caches by tenant, and do not cache sensitive personal information. Third, if the model’s output has high randomness, a cached answer to the same question may not be suitable for reuse. In these cases, cache only intermediate results, such as retrieved document snippets, instead of the final generated output.
3.3 Monitoring Metrics and Alerts
Set up a monitoring dashboard to track the following metrics continuously:
- Credit balance, and the number of days the balance will last at the current consumption rate.
- Daily call volume and token consumption, broken down by task type.
- P95 latency, to show whether queuing is getting worse.
- Cache hit rate, to measure the benefit of caching.
- Failure rate, counted separately for each error type (429, timeouts, 5xx, and so on).
You can use the following rules as alert thresholds. Send a reminder when the remaining days fall below half of the planning period. Raise an alert when the daily consumption rate exceeds 1.5 times the seven-day average. Trigger a circuit-breaker review when the failure rate stays above 5% for ten consecutive minutes. Adjust these values to fit your scale.
4. Common Mistakes
The following mistakes are common in real projects. Avoid them where possible.
- Blind retries: Retrying 401 or 400 errors repeatedly. These requests will not succeed, and the retries add noise to your logs.
- Using high-end models for everything: Running simple tasks such as classification and extraction on the largest model. The cost is far higher than necessary.
- Caching without a TTL: Keeping cache entries forever. Expired answers keep getting returned.
- Depending on a single endpoint: Sending all requests to one endpoint. If that endpoint queues or fails, the entire business stops.
- Unbounded concurrency: Running batch jobs at very high concurrency. This triggers 429 errors directly and slows down live services.
Conclusion
Running LLM services in production is a long-term effort in stability and cost management. Rate limiting and credit expiration are only the visible symptoms. The underlying issue is whether the caller can choose a billing model that fits its workload, control its request pace, and fall back to a working alternative when something fails.
Start with three steps. Use a load test at your real peak volume to confirm the service’s capacity. Set clear limits for retries, timeouts, and circuit breaking. Set up monitoring and alerts for credit balance and failure rate. After that, add asynchronous tasks, semantic caching, and multi-endpoint routing as your needs grow. Verify each measure with real data so you can confirm it actually lowers costs and improves stability.
