Reducing LLM API Costs: Billing, Caching, and Monitoring Best Practices
This article explains how to control the cost of LLM API usage in production. It covers how to calculate per-request cost from token usage and pricing, how to identify tasks that can be migrated to smaller models, how to design a prefix caching architecture with correct invalidation strategies, how to use asynchronous queues with retries and rate limiting, and how to build cost monitoring, alerts, and budget enforcement.
1. Start by Calculating the Cost of a Single Request
Before deciding whether an LLM-powered feature can run at scale, you need to know the cost of a single call. Most LLM APIs bill by token, the basic unit into which a model splits text. For English, one word is roughly one to one and a half tokens. For Chinese, there is no fixed conversion ratio—the same text can produce very different token counts under different tokenizers, so character count is not a reliable basis for cost estimation.
Billing is usually split into input and output. Input includes the system prompt, conversation history, and user content; output is the model’s generated response. Most providers charge a higher unit price for output than for input, so asking the model to produce long-form content will noticeably increase cost.
Some providers offer cached pricing. When the request prefix matches a recent request, the server can reuse previously processed content, and that portion is billed at a lower rate. Refer to the official pricing page for the discount level and cache lifetime.
The formula for estimating per-request cost is:
Per-request cost = (uncached input tokens × input price) + (cached input tokens × cache price) + (output tokens × output price)
How to obtain the three variables:
- Token usage: read the usage field in the API response, which typically contains input, output, and cached token counts. Do not substitute local estimates for the returned values.
- Cache hits: check the cache-related fields in usage. Field names vary by provider—follow their documentation.
- Unit prices: read them from the official pricing page and record the date you checked, since prices may change.
The table below uses hypothetical token counts purely to illustrate the calculation steps. Prices are represented by letters; replace them with official prices in practice.
| Item | Hypothetical Tokens | Unit Price | Subtotal |
|---|---|---|---|
| Uncached input | 2000 | Input price A | 2000A |
| Cached input | 1500 | Cache price B | 1500B |
| Output | 300 | Output price C | 300C |
The total is 2000A + 1500B + 300C. Looking only at prompt length ignores the impact of output. A recommended practice is to sample real usage from logs weekly and plug actual averages into the formula.
2. A Checklist for Migrating to Lightweight Models
Not every task requires the largest model. Lightweight models usually respond faster and cost less per call, making them suitable for tasks with short inputs, structured outputs, and well-defined decision boundaries.
Tasks suitable for migration include:
- High-frequency, short-output tasks such as tag generation, keyword extraction, and intent recognition.
- Classification and extraction, such as ticket categorization, field extraction, and preliminary screening of sensitive content.
- Summarization and rewriting, such as title generation, polishing short text, and compressing key points.
- Low-latency routing: first determining the request type, then deciding which model should handle it.
Tasks not recommended for migration include:
- Complex reasoning, including multi-step math or logical deduction.
- Long-context understanding, such as comprehensive analysis of an entire contract or a large codebase.
- Agent workflows that rely heavily on multi-step tool calls, where errors accumulate at each step.
- Content generation with high factual accuracy requirements and no verification step.
Before migrating, compare performance on your own evaluation set. You can sample a few hundred real production requests, judge results manually or with rules, and then compute accuracy and per-request cost for both models. Only switch when quality meets your business threshold.
3. Prefix Caching Architecture and Invalidation
Cost savings from caching depend on a stable request prefix. Place invariant content—system prompts, tool definitions, fixed examples—at the beginning of the request, and put user input at the end. A single character change in the prefix invalidates all cached content after it. Expect the hit rate to drop for a period after any prompt template change.
The cache key should include at least the following fields: model name, system prompt version, tenant or user permission identifier, and output format version. Without a tenant identifier, requests from different customers may hit each other’s cache, causing data leakage—this is the most critical mistake to avoid.
There are three categories of invalidation strategies:
- Time-based invalidation. Follow the server-side cache lifetime; the client should not assume the cache persists indefinitely.
- Version-based invalidation. Bump the version number when prompts or templates change, letting old cache entries expire naturally.
- Data-based invalidation. When the business knowledge base is updated, cache entries for related prefixes must be rebuilt.
Three common caching mistakes appear in code. First, using raw user input directly as the cache key without tenant information. Second, caching responses that contain random timestamps or request IDs, which drives the hit rate to zero. Third, reusing model output across all users when the output may contain personal information. Before going live, unit-test the caching layer to confirm that different tenants generate distinct keys.
4. Asynchronous Queues, Retries, and Rate Limiting
Non-real-time tasks such as batch labeling and offline summarization should go into an asynchronous queue instead of consuming synchronous API quota. Queues smooth out traffic spikes and let you concentrate cost in controllable time windows.
Retries must meet three requirements:
- Use exponential backoff, doubling the wait time with each attempt and adding random jitter to prevent large numbers of tasks from retrying simultaneously.
- Set a maximum retry count; tasks exceeding it go to a dead-letter queue for manual investigation.
- Retry only retryable errors, such as timeouts, rate limiting, and server-side 5xx errors. Parameter errors should be marked as failures immediately.
Idempotency is implemented through idempotency keys. Generate a unique ID for each task and check whether that ID has already completed before writing results. Otherwise, a single retry can cause the same task to be billed twice and duplicate data to be written.
Rate limiting has two layers. The outer layer limits request rates from business consumers, preventing one feature from suddenly exhausting the budget. The inner layer limits concurrency against the model API, aligned with the provider’s quota to avoid repeatedly triggering rate limits.
A degradation plan is equally important. When the LLM service is unavailable or the budget cap is reached, the system should fall back to a rules engine, cached results, or a lightweight model, and show users a clear status rather than failing silently.
5. Monitoring, Alerts, and Budgets
Without monitoring, cost reduction is impossible. Record at least the following metrics:
- Daily cost, broken down by feature, model, and tenant.
- Cache hit rate, observed over time. A sudden drop usually means the prompt structure was changed.
- Average output tokens; when the average rises abnormally, inspect the prompt or output format.
- Error rate, aggregated by error type.
- Queue backlog length and task wait time.
Recommended alerts: notify the owner when daily cost exceeds a certain percentage of budget; alert when the cache hit rate drops noticeably within an hour; alert when average output tokens deviate from the historical baseline; alert when the error rate exceeds its threshold; alert when the queue backlog keeps growing. Set thresholds based on historical data, not arbitrary guesses.
Budgets should be split by feature with hard caps. Once a hard cap is reached, the system automatically switches to the degradation plan, preventing a single feature from consuming the entire team’s quota.
