Prompt Caching: The Overlooked Compute Gold Mine
This article explains how prompt caching turns repeated prefix computation into measurable cost and latency savings. It covers what happens during prefill and decode, the strict matching rules and common cache invalidation traps, the pricing dimensions and capacity planning trade-offs, prompt architecture principles for agents, and the security and governance boundaries of shared caches. Readers will learn how to structure stable prefixes to raise hit rates and lower both compute bills and time to first token.
Opening: A Long-Wasted Compute Resource
For a long time, the cost structure of large model inference was governed by an implicit assumption: every request is brand new, and the model must “read” the entire context the user provides from scratch. That assumption began to wobble once conversational applications went mainstream, because real traffic shows that highly repetitive prefixes are the norm rather than the exception. System prompts, tool descriptions, few-shot examples, and long document bodies often reappear unchanged across thousands or tens of thousands of requests.
Over the past two years, the industry has gradually reached a consensus: a large amount of computation is repeatedly executed during inference, and reusing that computation translates directly into cost and latency advantages. Several cloud vendors and model platforms have introduced context caching capabilities, generally pricing the hit portion at a small fraction of the miss price (commonly around one tenth), and have published production results with hit rates above 90% and roughly 80% overall cost reduction. Behind these numbers is not marketing language but a structural opportunity left by the attention mechanism itself.
This article aims to tell the full story of this value chain: from low-level KV computation, to API pricing models, to the prompt organization philosophy of the agent era.
Chapter 1: What the Model Actually Computes During Inference
1.1 Inference Has Two Phases
Understanding the value of caching starts with understanding which phase of computation it eliminates. No matrix operation details are needed here, only a physical intuition.
Prefill phase: The model reads all input tokens at once and computes a set of Key (K) and Value (V) vectors for each position. This phase is highly parallel and compute-intensive, and most of the time to first token (TTFT) for long prompts is spent here. This explains why, in long-context scenarios, “the first token takes several seconds, and then everything is fast.”
Decode phase: The model generates tokens one by one. For each new token, it needs to look back at all previous positions, but it only reads the already computed K and V rather than recomputing them.
The key insight is a single sentence: the K and V at any position depend only on that position and the tokens before it. This means that once a prefix is fixed, its K and V are fixed and reusable. The entire value of prompt caching rests on this causality.
1.2 Why a Cache Hit Lowers Both Cost and Latency
Prefill is compute-bound, while decode is usually memory-bandwidth-bound. Caching removes the repeated part of prefill from the critical path, improving two things at once: the compute bill goes down, and time to first token goes down. The gains are most obvious in workloads with “long prefix + short output,” such as long-document question answering and code base question answering; conversely, workloads with short prefixes and long outputs benefit less.
Chapter 2: Hit Conditions and Invalidation Traps
A cache is not a switch but a set of strict matching rules. Most engineering failures come from an insufficient understanding of these rules.
- Strict prefix matching: The cache is keyed on the prefix of the token sequence. If the tokens differ from the very first one, nothing matches.
- Order sensitivity: Reordering paragraphs is equivalent to rewriting the prefix.
- Minimum length threshold: Most implementations require a prefix to reach a certain length before caching is worthwhile; prefixes that are too short will not hit.
- TTL and eviction: Cache entries have a lifetime and are evicted by policy under capacity pressure, so cold-start traffic naturally has a lower hit rate.
- Prefix drift: Putting timestamps, random IDs, or user nicknames at the beginning of a prompt makes every request a new prefix.
An illustrative structural comparison:
# Bad example: likely to invalidate the cache{Current time} Hello, {username}, here are the system rules...# Good example: stable prefix first[System rules - stable and unchanged][Tool and output format descriptions - stable and unchanged][Few-shot examples - stable and unchanged]--- above is the cacheable prefix ---[Conversation history][Current user input / dynamic variables]
Chapter 3: Pricing Model and Capacity Planning
Caching capabilities usually introduce three pricing dimensions: uncached input, cached input, and cache writes (some platforms charge a premium for writes and set a cache lifetime). This leads to one practical conclusion: once the number of reuses exceeds a certain break-even point, caching is necessarily cheaper; when reuses are very few, the write overhead may actually raise costs.
Capacity planning requires estimating “stable prefix length × number of concurrent prefix types” and using that to judge the upper bound of the hit rate. If a business has tens of thousands of mutually different system prompts, the caching benefit is structurally diluted; in that case, reduce prefix diversity rather than expecting caching to cover for it.
Chapter 4: Prompt Architecture for Agents
Intelligent coding tools and automation agents dare to carry system prompts on the order of twenty thousand tokens precisely because prefix caching amortizes that cost. Four design principles can be distilled from this:
- Layering: stable layer (rules, tool schemas) → semi-stable layer (knowledge snippets) → volatile layer (history and input).
- Append, do not rewrite: in multi-turn interactions, append new content to the tail and avoid changing the prefix.
- Externalize large objects: put long documents and retrieval results in external storage, bringing them into context through references and on-demand retrieval rather than stuffing entire passages into the prefix.
- Observability: use logging services and monitoring alerts to track prefix length, hit rate, and TTFT distribution, and treat hit rate as a first-class metric.
Chapter 5: Security and Governance Boundaries
Cache sharing also introduces a risk surface. Side-channel research shows that response latency differences alone may be enough to infer whether someone else’s input shares the same prefix, so highly sensitive scenarios should isolate cache scope, avoid cross-tenant sharing, and redact sensitive information in prompts. For compliance, data retention policies and access controls should be defined clearly, and caching should be brought into a unified data governance framework.
Conclusion
The essence of prompt caching is turning the waste of “repeated reading” into a measurable asset. For developers, it is an optimization checklist; for architects, it is a prompt layering specification; for managers, it is a clear cost curve. In general-purpose inference services on platforms such as Baidu AI Cloud, these capabilities are gradually becoming defaults, and what truly creates differentiation is the application side’s ability to design prefix structures.
