LLM Caching Guide: How to Cut API Costs by Up to 90%
This guide explains why LLM API bills grow faster than revenue and how prompt caching fixes the problem. It covers the three caching models (automatic, explicit, and semantic), how to structure requests so stable prefixes stay cacheable, how to design semantic cache keys and similarity thresholds, which observability metrics to track, and how to handle invalidation, tenant isolation, and fallback. A four-step rollout path and realistic expectations for cost savings are included.
1. Where the Problem Starts: A Growing Bill Is Not Growing Profit
Many teams run into an awkward situation after wiring LLM capabilities into their products: the call-volume curve looks great, but the gross-margin curve stays flat. The cause is usually not unit price but repeated computation. Most business requests are not independent of one another; they share large identical prefixes: system prompts, role definitions, tool descriptions, business documents, knowledge base snippets, and summaries of prior conversation. All of that content is billed again and re-processed by attention on every single request. It is textbook reusable overhead.
There is only one criterion that matters when deciding what to optimize: what fraction of this request’s input duplicates recent requests. The higher the overlap, the larger the opportunity. So the first step toward lower cost is not finding a cheaper model, but decomposing requests structurally and measuring the share of the “stable prefix” versus the “changing suffix.” In practice, customer support, document Q&A, coding assistants, and batch extraction workloads tend to have stable prefixes that make up the vast majority of total input, which is exactly why caching approaches can deliver order-of-magnitude savings.
2. An Abstract Model of the Three Caching Types
Setting aside vendor-specific differences, the LLM caching capabilities on the market fall into three categories, each with a different level of automation, control, and payoff.
2.1 Automatic caching: zero code changes, short lifetime
The first type happens entirely on the server side, with no code changes required from developers. The matching logic is typically exact prefix equality: if the beginning of the current request (system prompt plus fixed documents) matches a recent request, the cache is hit and the matched portion is billed at a discount. Discounts in the industry commonly range from 50% to 75% off.
The advantage is that integration cost is zero. The drawback is an extremely short lifetime, usually only a few minutes up to a dozen or so. For low-frequency, long-tail business where users “come once and leave,” the cache expires almost as soon as it is created, so hit rates stay very low. On top of that, any single character difference (a space, a line break, a timestamp, a random ID concatenated into the prefix) makes the prefix unequal and causes a miss.
2.2 Explicit caching: controllable lifetime, requires changes
The second type lets developers actively create, reference, refresh, and release cache entries, registering the stable prefix explicitly as a reusable resource. It stretches the window from “a few minutes” to hours or even days, at the cost of introducing lifecycle management: who creates entries, who renews them, how they are invalidated when context changes, and how concurrent creation is handled. This approach suits scenarios with a relatively fixed knowledge base and steady access frequency, and it delivers the highest cost-reduction ratio of the three.
2.3 Semantic caching: cross-request reuse, requires threshold governance
The third type does not require literal equality. It vectorizes requests and returns historical answers based on similarity. It captures duplication where users “ask the same thing in different words,” offering a high upside but also higher risk: too loose a threshold returns wrong answers, while too tight a threshold degrades to no caching at all. It fits scenarios with converging intent and a limited answer space, such as fixed FAQs, enumerated classification, and parameter extraction.
3. What Really Drives Hit Rate: Request Structure Engineering
Caching is not a switch you flip; it is a design outcome. How you construct requests usually affects the bill more than which model you choose.
First, the prefix must be stable and placed first. Push all volatile content to the tail of the request:
[Stable] Role definition + output format constraints + tool definitions + domain knowledge[Semi-stable] Conversation summary (updated at a fixed granularity)[Volatile] Current user turn + timestamp + request trace ID
Second, remove dynamic variables from the prefix. Common killers include the current time, a random trace ID, the user’s nickname, and pagination cursors. They must be moved to the end or out of the prompt entirely.
Third, control how often the prefix updates. Changing content that “varies every second” into content that is batch-updated “every N minutes or every N messages” can significantly widen the reuse window.
Fourth, keep serialization consistent. Key order, whitespace, Unicode normalization form, and template rendering whitespace should all be fixed, so invisible differences do not cause misses.
4. Semantic Cache Key Design and Threshold Governance
Semantic caching needs three things: an embedding model, a similarity threshold, and an invalidation strategy. Set thresholds in tiers by business risk rather than using one global number:
| Scenario | Fault tolerance | Threshold strategy | Extra validation |
|---|---|---|---|
| Enumerated classification, format conversion | High | Looser | Structure validation |
| General Q&A | Medium | Moderate | Key entity comparison |
| Data queries, monetary calculations | Low | Tighter or disabled outright | Exact parameter matching |
The more robust engineering practice is “semantic recall plus exact validation“: first use vector similarity to find candidates, then strictly compare normalized key slots (numbers, dates, IDs, units), and reuse the answer only if they match. This preserves cross-phrasing reuse while avoiding the failure of returning the answer for “customer A” to a query about “customer B.”
5. Observability: No Metrics, No Savings
Once caching is live, you must close the metrics loop; otherwise you cannot distinguish “no money saved” from “money saved but quality dropped.” The minimal metric set includes: hit rate, share of input served from cache, amount saved after discount, change in average time-to-first-token latency, distribution of miss reasons (prefix mismatch / expired / never created), and the semantic cache’s wrong-answer interception rate and manual correction rate.
Instrumenting miss reasons is worth the effort. A prefix mismatch often points to a specific template variable; expiration points to lifecycle configuration; “never created” is usually a duplicate-creation race under concurrency, which can be mitigated with retries using randomized backoff and a single-flight pattern.
6. Invalidation, Consistency, and Fallback
The hard part of caching has never been getting a hit; it is knowing when not to hit. Three principles:
- Invalidate on data change: when a knowledge entry is updated, switch the prefix by version number, which naturally retires the old cache.
- Permission isolation: content from different tenants or different visibility scopes must not share cache keys, or you risk returning data across authorization boundaries.
- Fallback availability: when the cache service misbehaves, go straight to the origin; when a semantic cache has low confidence, go to the origin. Never return an answer that is “probably correct.”
7. Rollout Path and Expected Returns
A four-step progression is recommended: start with request structure governance (zero risk, immediate payoff); then enable automatic caching and observe hit rates; next introduce explicit caching with versioned invalidation for highly stable prefixes; finally, roll out semantic caching gradually in low-risk scenarios while keeping manual spot checks.
In businesses where the stable prefix is a large share of input and access is dense, a substantial reduction in repeated input overhead is a common result. In long-tail, low-frequency businesses, the gains come mainly from structure governance rather than caching itself. Realistic expectations matter: caching optimizes repeated computation, not model unit price, and only the two together form a complete cost strategy. If you use the relevant model services from Baidu AI Cloud, the same advice applies: apply the general methods above to request governance and metric measurement first, then evaluate the actual discount room that caching capabilities provide.
