How LLM Prompt Caching Works and How to Cut Token Costs

    This article explains how context caching (also known as prefix caching or KV Cache reuse) reduces LLM input token costs, the core rule that determines cache hits, the cost differences among three cache management modes, and a practical checklist for improving hit rates. It also covers how to design caching strategies alongside prompt engineering on Baidu AI Cloud.

    1. Why Context Caching Matters

    When an LLM handles a request, it converts the input sequence into high-dimensional representations layer by layer. The core cost comes from the key/value projections in the attention mechanism and the matrix operations that follow: every token passes through multiple layers to produce its Key/Value tensors and interacts with other tokens. As a conversation keeps growing, the key/value results for the earlier thousands of tokens remain unchanged, yet a conventional implementation recomputes them anyway.

    Context caching (often called prefix caching or KV Cache reuse in the industry) addresses exactly this: it stores the intermediate states that have already been computed so the next request can read them directly and skip the repeated work. What it saves is not storage but the compute spent when the model “reads your text,” which shows up on the bill as a sharp drop in the input-side token price—the reused portion can typically cost as little as 10% of the original price, or even less.

    It is worth stressing that a cache hit does not change output quality; it only changes the computation path. For the same prompt, a cache hit and a cache miss should theoretically produce identical results (aside from sampling randomness).

    2. The Only Rule: The Prefix Must Match Exactly from Token 0

    The underlying logic of all caching mechanisms can be reduced to one sentence: compare token by token from the beginning, truncate at the first position that differs, and only the common prefix before that point can be reused.

    This means a hit is a “longest common prefix” problem, not a “similarity” problem. The following patterns all break the prefix and invalidate the cache:

    1. # Miss: the system prompt is polluted by a dynamic timestamp
    2. System time: 2026-08-12 14:03:22
    3. You are a senior backend engineer...
    4. # Hit: move volatile content to the end
    5. You are a senior backend engineer...
    6. (The following is dynamic information for this request)
    7. System time: 2026-08-12 14:03:22

    Likewise, putting a user ID, session ID, or random request number at the beginning, or going back to edit earlier messages in a multi-turn conversation, will force the cache to be recomputed from the start. The common engineering practice is to place static content first and dynamic content last, and to version-control prompt templates.

    3. Cost Structure Differences Among Three Cache Management Modes

    Platforms differ in how much caching they automate, which can be abstracted into three categories:

    1. Fully automatic mode. The platform automatically records high-frequency prefixes and persists them for reuse, with no code changes required. The advantage is zero rework; the downside is weak control and unpredictable hit rates.
    2. Semi-automatic mode. The platform provides a cache declaration capability, and developers must explicitly mark the segments to cache and their time-to-live. Writing to the cache costs extra (because it requires one additional full computation plus persistence), while reads enjoy a discount. This is the root of “paying more to write the cache”: a write is a real compute and storage cost, and only the read is the payoff.
    3. Fully automatic + disk-level caching. Prefix states are persisted to disk media, whose capacity far exceeds that of GPU memory, so the read cost after a hit is extremely low. That is why the discount can look “outrageous”—it essentially trades the memory bottleneck for disk I/O and hit-policy problems.

    Once you understand these three differences, “why caching didn’t save money” usually comes down to only three answers: the prefix is broken by a dynamic field; the interval between requests exceeds the cache’s lifetime; or the write cost has not yet been amortized by subsequent hits.

    4. A Practical Checklist for Improving Hit Rates

    • Layer your prompts: put the system prompt and fixed few-shot examples first, and retrieval results and user input last.
    • Keep serialization stable: keep JSON key order, whitespace, and casing byte-for-byte identical, avoiding text that is equivalent but differently shaped.
    • Control cache granularity: split independent prefixes by business line to avoid low-frequency content diluting high-frequency caches.
    • Design continuous sessions: append-only multi-turn beats rewriting history every turn, ensuring the prefix grows monotonically.
    • Observability: use logging services and monitoring alerts to track hit counts, the share of hit tokens, and cost changes, driving tuning with data.
    • Capacity planning: in high-concurrency scenarios, combine elastic scaling from a container platform to warm high-frequency prefixes into the cache layer.

    5. Implementation Advice on Baidu AI Cloud

    In Baidu AI Cloud’s large model services, it is recommended to design the caching strategy and prompt engineering at the same level: first solidify the templates, then evaluate whether to explicitly declare caching, and finally validate the benefits with monitoring metrics. For cost-sensitive batch scenarios with stable request prefixes, the reduction in input costs from caching is often more worthwhile than switching to a smaller model; for scenarios with highly variable prefixes, prioritize optimizing prompt structure rather than blindly enabling caching.