LLM API Cost Optimization: A Practical Guide to Token Billing and Caching
Large language model (LLM) API bills often far exceed expectations, especially for research articles and long-report generation. This guide explains how to read and reduce those bills through disciplined token and cache management. It breaks down a per-request cost formula covering input, output, cache-hit, and cache-write tokens; compares common caching implementations and four caching scenarios; and explains why long-context, multi-turn workloads drive costs up. It then provides a prioritized optimization checklist (from stabilizing the prompt prefix and setting budget alerts to context trimming and long-TTL caching), a set of tracking metrics, vendor-neutral pseudocode, usage-tracking patterns, an FAQ, and security and compliance notes. It emphasizes that specific prices, cache thresholds, and TTL tiers vary by vendor and should always be verified against the official documentation.
Why can a two-hour session burn through hundreds of yuan? Start with how the numbers are calculated
Many teams see bills far higher than expected the first time they integrate an LLM API to produce research articles or long reports. But this needs to be stated clearly: “hundreds of yuan in two hours” only holds under specific conditions — it is not a universal conclusion.
This outcome usually requires all of the following conditions at once:
- Using a model with a high output unit price, where the generation task produces a large share of output tokens;
- Very long single-turn context (long documents and reference material injected repeatedly);
- In multi-turn generation, every turn carries the full history, so input tokens accumulate linearly with each round;
- An unstable context prefix — cache misses or an expired TTL — so all input is billed at the standard rate.
If you switch to short prompts, a smaller model, or high-frequency cache hits, the same two hours could cost an order of magnitude less. So the right way to diagnose a cost problem is not to memorize a figure, but to break down the structure of the bill.
How are tokens billed? One cost formula that explains the bill
Mainstream APIs meter usage by token. A single request typically involves four kinds of tokens:
- Input tokens: the full input content, including prompts, system instructions, and historical context;
- Output tokens: the content the model generates and returns, usually priced significantly higher than input tokens (across most providers, roughly 2–4x input, though the spread is wide);
- Cached tokens (cache-hit portion): input that hits the context cache, billed at a price well below the standard input rate;
- Cache-write tokens: a one-time charge for writing context into the cache, with tiers that depend on how long the cache stays alive.
The cost of a single request can be approximated as:
cost per request ≈ uncached input tokens × input unit price+ cached input tokens × cache unit price+ output tokens × output unit price+ cache-write tokens × cache-write unit price
Two direct implications:
- Output tokens are usually the most expensive, so compressing output length and avoiding verbose restatement often pays off more than trimming input;
- Writing to the cache is a one-time cost that must be amortized over many subsequent hits. If there are not enough reuse rounds, writing to the cache actually raises total spend.
Specific unit prices, the minimum number of tokens that can be cached, cache discount ratios, and TTL tiers vary significantly by provider, so always rely on the official billing documentation of the provider you use.
What forms does caching take?
“Context caching” is not a single unified parameter. Implementations differ across providers, but three common forms exist:
| Implementation form | Typical approach | Notes |
|---|---|---|
| Explicit-marker type | Insert cache-control markers into message content | The developer explicitly declares the cache location and TTL tier |
| Independent-parameter type | Use a separate cache switch or a cache-object reference | Create a cache first, then reference it in subsequent requests |
| Automatic prefix caching | The server automatically detects and caches repeated prefixes | No extra parameters, but demands a more stable prefix |
This means there is no universal use_cache=True parameter. When migrating between providers, you must re-adapt the calling convention, the cache-invalidation conditions, and the usage fields in the response.
Cost comparison of four caching scenarios
| Scenario | Cost structure | When it fits | Main risk |
|---|---|---|---|
| No cache | All input at standard price | One-off tasks, contexts that barely repeat | Long contexts billed repeatedly |
| Automatic prefix cache hit | Cached portion at cache price | Frequent reuse of the same prefix within a short window | Any prefix change invalidates everything |
| Short-TTL cache | Hit price + one cache write | Continuous multi-turn interaction within a session | Gaps that are too long cause expiry and rewriting |
| Long-TTL cache | Hit price + higher cache-write price | Sharing long documents across sessions with a long reuse cycle | Insufficient reuse leaves the cache-write cost unamortized |
The decision rule is simple: expected number of reuses × savings per request > cache-write cost — only then does caching pay off.
Why do costs stack up in high-consumption scenarios?
Research articles and long reports tend to cost more because four factors compound:
- Long context: reference material is injected repeatedly, so input tokens are naturally high;
- Multi-turn history: long documents are generated in segments, and every turn carries the entire history;
- Large output volume: generation tasks produce many output tokens to begin with;
- Poor cache utilization: prompts are reassembled each round, the prefix is unstable, and everything is billed again at the standard rate.
What to do: an optimization priority checklist
Ordered by return on effort, here is a suggested sequence:
- P0 Stabilize the prefix and move it to the front: keep system instructions, reference material, and formatting conventions fixed at the very top of the prompt, and place dynamic content at the tail;
- P0 Set budget caps and alerts: define daily/hourly budgets and alert thresholds so you do not discover overspending after the fact;
- P1 Trim context: use summaries and retrieval-augmented generation (RAG) to keep only the necessary snippets, removing irrelevant, verbose content;
- P1 Separate input from output: distinguish core questions that must be reasoned about from facts that can be reused directly, reducing wasted input;
- P2 Batch calls to raise the hit rate: for long documents referenced repeatedly, complete multiple rounds within the same session or the same short time window;
- P3 Evaluate long-TTL caching: enable it only when the reuse cycle really is long and the number of hits can be estimated;
- P4 Add your own result-caching and request batching: cache results for repeated questions and merge similar requests into batches.
Accompanying acceptance metrics:
| Metric | Meaning | Reference direction |
|---|---|---|
| Cache hit rate | Cached tokens / total input tokens | Higher is better; long-document scenarios should show clear improvement |
| Cache-write count | Number of cache writes per unit time | Should stabilize and converge, not keep growing rapidly |
| Average cost per request | Total cost / number of requests | Should decline with ongoing optimization |
| Blended cost per 1K tokens | Total cost / total tokens | Reflects the combined effect of unit price and hit rate |
| Output ratio | Output tokens / total tokens | When high, prioritize compressing output |
Illustrative pseudocode (not any vendor’s SDK)
The code below is structural illustration only and cannot be run as-is. It shows how to organize a “stable prefix + dynamic query” structure:
# Pseudocode: illustrates a cache-friendly message structure; not any vendor's real API.# Real implementations must follow the vendor SDK, e.g., explicit cache markers,# independent cache-object references, or relying on automatic prefix caching.system_prompt = "You are a senior research analyst. Generate a structured report based on the following material." # stable partreference_doc = load_large_reference() # long document, caching candidatedef build_messages(user_query, history=None):# Key: stable content stays in a fixed position and is byte-for-byte identicalmessages = [{"role": "system", "content": system_prompt + "\n" + reference_doc}]if history:messages.extend(history)messages.append({"role": "user", "content": user_query}) # dynamic content goes at the tailreturn messagesdef call_model(user_query, history=None, cache_option=None):messages = build_messages(user_query, history)# cache_option varies by vendor: cache marker, cache ID, or no explicit configreturn llm_api_call(messages, **cache_option)
Keeping system_prompt and reference_doc byte-for-byte identical is a prerequisite for a high hit rate. Even inserting a single timestamp or username into the prefix will invalidate the entire cache.
How do you monitor budget and usage?
It is recommended to maintain a call ledger at the application layer, with fields mapped directly from the usage object in the vendor response:
# Pseudocode: field names follow the vendor's usage response and need compatibility handlingclass UsageTracker:def __init__(self):self.input_tokens = 0 # non-cached inputself.output_tokens = 0self.cached_tokens = 0 # cache-hit input, usually already included in total inputself.cache_write_tokens = 0 # returned by only some vendors; treat as 0 when missingdef record(self, usage):self.input_tokens += get_int(usage, "input_tokens")self.output_tokens += get_int(usage, "output_tokens")self.cached_tokens += get_int(usage, "cached_tokens", 0)self.cache_write_tokens += get_int(usage, "cache_write_tokens", 0)def hit_rate(self):total_input = self.input_tokens + self.cached_tokensreturn self.cached_tokens / total_input if total_input else 0.0
Practical points:
- Use tolerant field access to handle missing fields, since field names may differ across providers and versions;
- Failed retries cause duplicate billing, so retry requests should be idempotent and log the retry count to avoid distorting the ledger;
- Set cost and hit-rate thresholds at hourly/daily granularity, and alert on both conditions (watch for either an abnormal cost spike or a sudden drop in hit rate);
- A hit rate of 0 usually means the prefix changed, the TTL expired, or the context fell below the minimum cacheable length.
FAQ: a few frequent questions
What if the cache does not hit?
Check item by item: is the prefix byte-for-byte identical; is a minimum cacheable-token threshold not being met; is the interval between calls exceeding the TTL; did history messages inject volatile content such as timestamps or random IDs.
How do I choose a TTL?
Choose by reuse window, not by “longer is always better.” Use a short tier for continuous multi-turn interactions within a session; use a long tier for static long documents shared across sessions, but only if you can estimate the number of hits — otherwise the cache-write cost is hard to amortize.
Why didn’t cost drop after enabling the cache?
Three possibilities: the number of cache writes is nearly equal to the number of hits (insufficient reuse); the cached portion is a small share and the main cost is in output tokens; or the model or calling convention means the cache is not actually taking effect. Look at the hit rate and cache-write count first, then draw a conclusion.
What should long-report tasks do first?
Trim the context and stabilize the prefix first, then enable caching. Trimming reduces both input and output redundancy with a reliable payoff; cache benefits depend on the hit rate, so caching is a second-layer optimization.
Security and compliance notes
- Cached content may be retained by the server during the TTL, so do not cache context containing secrets, personal privacy, or un-desensitized sensitive data;
- Desensitize user input and internal documents written to the cache and to logs, replacing sensitive fields with placeholders;
- Shared-cache scenarios need tenant isolation and permission checks to prevent cross-user reuse;
- Define data retention periods and regularly purge the local call ledger and result caches;
- Review the provider’s data usage and retention terms to confirm the caching mechanism meets internal compliance requirements.
Conclusion
LLM API cost can be reduced significantly for repeated input through caching and disciplined context management, but the actual effect must be validated against the model’s unit price, context length, and hit rate. The path to adoption is clear: first work out the cost formula, then move stable content to the front, trim redundant context, and batch the call window to raise the hit rate, and finally use budget alerts and hit-rate metrics to keep calibrating. Always treat the provider’s official documentation as the final source of truth for parameters and billing details.
