LLM Cost Optimization: A Practical Guide to Context Caching
As LLM bills outpace business growth, input tokens often dominate spending because the same context is transmitted and recomputed on every request. This guide breaks down the four components of per-call cost, compares three context caching approaches (explicit, automatic, and persistent), and shows how to turn cache hit rate into a monitored metric. It includes a cost model explaining when caching pays off, engineering practices for keeping prompt prefixes byte-stable, and a governance checklist for avoiding common pitfalls. Readers will learn how to cut input-side costs to roughly 10%–30% of the original by measuring first, stabilizing prefixes, and choosing a caching strategy based on reuse frequency.
1. The Root of Cost Anxiety: You Are Not Only Paying for Generation
Many teams discover after launching an LLM application that their bills grow faster than their business. The reason is straightforward: in token-based model services, the input side (context) often accounts for the bulk of total consumption, yet only a small portion of that context actually changes from request to request. System prompts, tool definitions, domain knowledge, few-shot examples, and long documents are transmitted and recomputed over and over across thousands of requests.
The first step in optimization is to break the bill apart. The cost of a single call roughly consists of four parts: writing context for the first time, reading context repeatedly, adding new conversation content, and generating output. The first two determine the upper bound of optimization; the latter two determine the lower bound. Understanding this structure matters more than memorizing any single technique.
2. Mechanism Overview: Three Approaches to Context Caching
Industry implementations of “don’t charge full price for repeated context” fall into three technical routes, each with trade-offs.
The first is the explicit caching approach. Developers actively mark a segment of context as cacheable, and the server persists its computed result for reuse in subsequent requests. The advantage is that the discount after a hit is usually the largest, commonly around one-tenth of the original price; the cost is an extra write fee on first creation (commonly 1.25x the original price) and a retention limit (commonly minutes, such as 5 minutes). This approach suits scenarios where the same context is reused at high frequency over a short period, such as customer service sessions, multi-turn code assistant completions, and batch document extraction.
The second is the automatic caching approach. The server automatically identifies and reuses repeated prefixes, so developers do not need to change their code; the hit rate depends on how stable the request prefix is. The advantage is low integration cost; the drawback is the lack of observable metrics for hits, plus opaque capacity and eviction policies, which makes fine-grained cost attribution difficult.
The third is the persistent caching approach. The computed result of the context is stored in a controllable storage medium, with retention measured in hours or even days. It buys a longer reuse window but requires additional engineering complexity for storage, invalidation management, and consistency maintenance. It is better suited to workloads with low frequency but long-cycle reuse, such as knowledge base Q&A and repeated follow-up questions over long documents.
The selection criterion can be summarized in one sentence: look at whether the “reuse interval for the same context” is on the order of seconds, minutes, or hours.
3. Observability: Turn Hit Rate into a Metric First
The most commendable aspect of the explicit caching route is transparency: the response separately returns the number of tokens consumed to create the cache this time and the number of tokens read from the cache this time. These two fields are the dashboard for cost optimization; without them, any optimization is blind tuning.
It is recommended to include the following metrics in your monitoring and alerting system:
- Cache hit rate = read tokens / (read tokens + missed input tokens)
- Write amplification ratio = cache creation tokens / cache read tokens; a long-term value greater than 1 means the caching strategy is losing money
- Average input cost per request, drilled down by business line, model version, and prompt template
Illustrative statistics logic:
def record_usage(resp, tags):read = resp.usage.get("cache_read_input_tokens", 0)write = resp.usage.get("cache_creation_input_tokens", 0)hit_rate = read / max(read + write, 1)metrics.timing("llm.cache.hit_rate", hit_rate, tags=tags)metrics.count("llm.cache.write_tokens", write, tags=tags)
4. Cost Model: When Does Caching Actually Save Money
Let the unit price of missed input be 1, the hit discount be 0.1, and the write premium be 1.25. If the cache is reused N times within the retention window after one creation, the total cost is 1.25 + 0.1×(N-1), while the cost without caching is N. Setting the former less than the latter gives N greater than about 1.28, meaning it breaks even after at least two reuses; when N reaches 10, the cost is about 35% of the no-caching approach; as N grows, it approaches the theoretical lower bound of 10%. This is the real source of “save up to 90%”—it is not the discount itself, but the discount multiplied by a sufficiently high number of reuses.
The counter-example is equally important: if the context changes every time, or the reuse interval exceeds the retention duration, then the cache must be recreated every time. You not only fail to get the discount but also pay an extra 25% write fee, so the cost actually rises.
5. Engineering Implementation: Make the Prefix Stable
The prerequisite for cache reuse is that the prefix is byte-for-byte identical. Common factors that break hits in practice include: putting timestamps, random IDs, or user nicknames at the beginning of the prompt; using non-deterministic dictionary traversal order in templates; tool definition list order changing with the registration process; and system prompts being dynamically concatenated by middleware.
The corresponding refactoring principle is to split the context into a “stable segment + variable segment,” with the stable segment first and as long as possible:
[System role and constraints] ← stable, cacheable[Tool/parameter definitions] ← stable, cacheable[Domain knowledge and examples] ← stable, cacheable[Conversation history summary] ← semi-stable[Current user input, timestamp] ← variable, not cached
Combine the following measures to further amplify gains: structurally split long documents and reuse fixed blocks; compress multi-turn history into a summary before input; solidify high-frequency fixed prefixes into versioned templates and include them in code review; use batch APIs for non-real-time tasks to get a lower unit price; route classification, extraction, and rewriting requests that small models can handle, sending only complex reasoning to large models.
6. Common Pitfalls and a Governance Checklist
First, the “caching is a panacea” fallacy ignores the write premium and retention window; second, looking only at the total bill without the hit rate makes it impossible to locate problems; third, putting variable fields first leads to a long-term zero hit rate; fourth, conflicts between caching and knowledge updates cause stale answers, so explicit invalidation and version numbers must be designed for the cache; fifth, the lack of a fallback path means the system should be able to revert to full context when the cache service fails.
Implementation checklist: label the cacheable proportion for each request type; build a dashboard for hit rate and write amplification; set a reuse-count threshold (do not enable caching below the threshold); put prompt templates under version control; review unit prices and usage structure quarterly.
7. Conclusion
Optimizing LLM call costs is essentially converting “repeated computation” into “compute once, reuse many times.” Measure first, then refactor the prefix, and finally choose a caching strategy based on reuse frequency; most high-frequency conversation and batch processing scenarios can compress input-side costs to 10%–30% of the original. If you already use the relevant model services from Baidu AI Cloud, it is recommended to likewise start from observable metrics and drive optimization decisions with data rather than intuition.
