LLM Prompt Caching: How Input Cache Hits Work and How to Optimize Costs
This article explains how input caching (prompt caching) works in large language model inference and why it matters for cost optimization. It breaks down the prefill and decode stages, shows that caching is based on matching token prefixes rather than whole requests, and presents a sample cache-hit length function. It then covers the cost difference between cache hits and misses, five engineering prerequisites for a high hit rate, a three-layer architecture for implementation, common misconceptions, and general practices for building stable prefixes and observability into your LLM applications.
1. Why Input Cache Hits Deserve Separate Attention
The industry has seen events where API pricing was restructured across an entire product line, with cache-related billing items on the input side listed separately. This kind of adjustment sends a clear signal: LLM inference cost is moving from “roughly calculated per character” toward “precisely accounted per computation path.” For developers, understanding cache hits is not a small trick for saving money; it is part of architecture design.
It should be noted that billing details, cache granularity, and validity periods differ across vendors. This article only discusses the general mechanisms and engineering methods widely accepted in the industry and does not point to the parameters of any specific product.
2. Mechanism Breakdown: What Input Caching Actually Caches
LLM inference is divided into two stages: prefill and decode. The prefill stage runs attention computation over all input tokens and generates the corresponding key-value cache; the decode stage then produces output token by token on that basis. When the input prefix of two requests is exactly the same, the key-value cache already computed by the previous request can be reused directly, and what is saved is precisely the repeated portion of the prefill computation.
Three key conclusions follow from this:
- The cache granularity is the “prefix,” not the “full text.” Only the portion that matches token by token from the very beginning can hit; any insertion or modification in the middle invalidates everything after it.
- A hit reduces computation, so in billing it usually appears as “a lower unit price for the hit portion,” not as free.
- Caches have a lifecycle, constrained by three factors: capacity eviction, time expiration, and namespace isolation.
The hit determination logic can be understood schematically as follows:
def cache_hit_len(cached_prefix: list[int], new_tokens: list[int]) -> int:n = 0for a, b in zip(cached_prefix, new_tokens):if a != b:breakn += 1return n # Hit length; the rest must be re-prefilled
3. The Billing Perspective: How the Cost Gap Between Hits and Misses Gets Amplified
Suppose that for a certain class of requests, the fixed prefix (system instructions, tool definitions, domain knowledge, few-shot examples) makes up the vast majority of the total input, while the actual user question is only a few dozen characters. On a miss, every request pays for the huge prefix; with a stable hit, only the newly added portion is billed at the standard price, while the hit portion is billed at a discounted price.
Writing the cost as a formula makes it more intuitive:
Cost per request = hit tokens × hit unit price + miss tokens × standard unit price + output tokens × output unit price
As the hit rate approaches 1, the input-side cost approximately degenerates into “a one-time amortization of the fixed prefix plus a tiny increment.” This is also why scenarios with long fixed prefixes and short incremental questions are the most sensitive to caching and benefit the most.
4. Five Engineering Prerequisites for a High Hit Rate
- Prefix stability: move volatile content (timestamps, random IDs, user nicknames, real-time retrieval results) from the head to the tail to avoid polluting the prefix.
- Fixed ordering: the template concatenation order must be version-controlled; reordering any field causes the whole thing to be invalidated.
- Namespace isolation: in multi-tenant scenarios, ensure that caches of different tenants do not interfere with each other, while avoiding mixing public prefixes with private data.
- Lifecycle matching: batch jobs should be submitted continuously in a concentrated manner to avoid cache expiration caused by long intervals.
- Observability: you must be able to measure hit length and hit rate; otherwise optimization cannot be verified.
A counterexample illustrates the destructive power of point 1:
# Wrong: the timestamp comes first, so the prefix differs on every request[2026-04-26 10:00:01] You are a customer service assistant... (long specification)... User question: how do I get a refund# Correct: stable content first, volatile content lastYou are a customer service assistant... (long specification)...User question: how do I get a refund(Current time: 2026-04-26 10:00:01)
5. Implementation Architecture: A Three-Layer Design
The access layer handles template rendering and cache key computation. It splits requests into two parts, “public prefix + session increment,” and hashes the prefix for monitoring. The routing layer schedules requests with the same prefix to the same cache domain to reduce cross-instance invalidation, while retaining the ability to automatically fall back to a standard call when the cache misses. The observability layer collects hit length, hit rate, average input size, and cost per request through logging services and monitoring alerts, forming a closed loop for continuous optimization.
{"prefix_hash": "sha256:9f2c...","prefix_tokens": 3120,"suffix_tokens": 48,"namespace": "tenant-1024","fallback": "standard"}
6. Common Misconceptions
- Thinking a hit is free: a hit only means a lower unit price; it is still billed.
- Thinking similar is enough to hit: the determination is strict token-by-token equality, and paraphrasing with synonyms counts as a miss.
- Blindly lengthening the prefix: the longer the prefix, the greater the waste on a miss; you need to balance hit rate against fixed cost.
- Ignoring the output side: output tokens are usually billed at the standard price, so controlling output length is also a cost measure.
7. General Recommendations Related to Baidu AI Cloud Practices
In access to model services on Baidu AI Cloud, it is likewise recommended to adopt “stable prefix + incremental suffix” as the default template paradigm, build a hit-rate dashboard with logging services and monitoring alerts, and incorporate cache misses as a normal fallback path into capacity planning. If a business also uses object storage to host knowledge documents, message queues for peak shaving, and a container platform to host batch inference jobs, the public prefix can be built as a versioned artifact and distributed uniformly, reducing prefix drift at the source.
8. Conclusion
Input cache hits are essentially about removing “repeated computation” from the bill. They require developers to re-examine prompt templates, request scheduling, and observability systems from the perspective of cache keys. Manage the prefix as a contract, and improvements in hit rate and reductions in cost will happen at the same time.
