LLM Prompt Caching and Token Cost Optimization: How Cache Hits Work

    This article explains how prompt caching works in large language models and how to reduce token costs through better cache hit rates. It covers what is actually reused during inference, why an identical prefix starting from token 0 is the only requirement for a cache hit, why writing a cache can incur extra charges, and the common reasons caching fails to lower bills. It also outlines engineering practices for organizing prompts by stability, making hit rates observable, and using a simple cost model to decide whether caching is worthwhile.

    1. Asking the Right Question: What Does a Cache Hit Actually Cache?

    Many discussions treat “cache hit” as “asking the same question twice gets cheaper.” That only describes the surface. To understand the bill correctly, start with one fact: what gets reused during LLM inference is not your text itself, but the full set of intermediate computation results the model produces while processing that text.

    Take the mainstream decoder-only autoregressive architecture as an example. As the model computes attention layer by layer, it generates Key and Value vectors for every position. When later positions compute attention, they must interact with the Key/Value of all preceding positions. This means that if a prefix stays completely unchanged, the Key/Value for every layer of that prefix is deterministic and reusable. The benefit of a cache hit is precisely the elimination of this repeated tensor computation and GPU memory read/write.

    This leads to a key conclusion: the unit of a cache hit is the “position,” not the “paragraph” or the “meaning.” Semantically similar but literally different text will not hit; literally identical text appearing at a different offset will not hit either.

    Schematically, the difference between a hit and a miss looks like this:

    1. Miss: run linear projection + attention computation for all positions [t0, t1, ..., tn]
    2. Hit: load Key/Value for [t0, ..., tk] directly, compute only [tk+1, ..., tn]

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

    All the seemingly complex billing and mechanism differences trace back to one basic rule: the reusable range is the longest common prefix that is byte-for-byte identical, starting from the beginning of the sequence.

    This principle has three easily overlooked corollaries:

    1. The prefix is position-sensitive. Insert a single space, a timestamp, or a greeting at the start, and the offset of everything after it shifts, so the hit length falls back to before the insertion point.
    2. Hit length takes the minimum. The length a system can reuse equals the longest common prefix length between the current request and the sequence already in the cache; the shortest segment sets the ceiling.
    3. The hit must be prefix-contiguous. If there is a single difference in the middle, identical content after it cannot be reused across that difference.

    So placing dynamic content at the end and stable content at the front is not a style suggestion, but a hard constraint dictated by the computation structure.

    3. Why Writing a Cache Can Itself Add Cost

    Implementations differ markedly in when they write to the cache. They can be abstracted into three strategies:

    • Fully automatic lazy writes: the system decides on its own during inference what reusable state to retain. Callers do not declare anything explicitly, and there is usually no extra charge.
    • Semi-automatic explicit declaration: the caller marks a segment of content as needing to be cached via a parameter. The system allocates storage for that segment and maintains its lifecycle, and the write phase may be billed at a higher unit price.
    • Fully automatic with persistent storage: state is written to persistent media and reused across sessions and instances, allowing for more aggressive hit discounts.

    “It costs extra to write a cache” is not a contradiction. Writing is an extra action: it requires allocating storage, generating and persisting intermediate state, and maintaining indexes and expiration policies. This cost is incurred at write time, while the benefit accrues on every subsequent hit. Whether it pays off depends on the number of reuses:

    1. Total cost ≈ write cost + N × miss cost (no caching)
    2. Total cost ≈ write cost + N × post-hit cost (with caching)
    3. Caching wins only when N is large enough and post-hit cost is significantly lower

    The practical judgment is straightforward: do not cache one-off, long-tail requests that are almost never reused; cache high-reuse content such as system prompts, tool definitions, long-document Q&A, and codebase context.

    4. Why Caching Is Enabled but the Bill Does Not Drop

    This is the most common confusion, and the prefix principle explains nearly all of it:

    • Dynamic content placed first: putting the current time, user ID, or randomized recommendation slots at the beginning.
    • Unstable template ordering: serialized field order changing with language or version, causing byte-level inconsistency.
    • Hidden metadata differences: invisible characters, newline styles, full-width versus half-width punctuation, trailing whitespace.
    • Requests routed to different instances: the cache is not shared or has expired, so it must be written again.
    • Sliding context window: dropping the earliest messages to fit more content, which actively breaks the prefix.
    • Misunderstanding sampling parameters such as temperature: sampling parameters affect output randomness and have nothing to do with whether a cache hits; changing them will not improve the hit rate.
    • Insufficient reuses: the write cost has not been amortized before the task ends.

    The recommended approach is to make troubleshooting observable: log the prefix length, hit length, bytes written, and hit count for every request, and use monitoring alerts to flag abnormal drops in the hit rate. Without these metrics, cost optimization is basically guesswork.

    5. Engineering Practice: Making Hit Rate a Designable Metric

    Organize prompts by “stability” into a fixed skeleton with a variable tail:

    1. [Stable layer] Role definition, output specification, safety constraints
    2. [Stable layer] Tool/function definitions, field descriptions
    3. [Stable layer] Long documents or codebase context
    4. [Variable layer] Current user input, timestamps, retrieval results

    Supporting engineering habits include:

    1. Version your templates. Put prompt templates under version control and route changes through review to avoid accidental edits that invalidate the whole cache.
    2. Normalize serialization. Standardize JSON key order, newline characters, and encoding, and never concatenate a random ID onto the head.
    3. Place retrieval results at the end. Put dynamically recalled content after the stable context rather than inserting it in front.
    4. Preserve the session prefix. In multi-turn conversations, append to history rather than rewriting it, and push volatile information to the end when necessary.
    5. Manage cache segments. Split very long stable context into multiple independently cacheable blocks and set a lifecycle for each according to its reuse frequency.
    6. Make cost observable. Bring hit length, hit ratio, and write volume into your logging and alerting systems, and attribute cost by business line.

    6. Getting the Cost Model Right

    To evaluate whether caching optimization is worth the investment, use a simplified model:

    1. Savings ≈ cached tokens × (miss unit price − hit unit price) × number of hits − write cost

    Three points need attention: the hit unit price is usually significantly lower than the miss unit price but is never zero; the write cost is incurred only the first time; and the number of hits is determined by the business’s reuse level, not by technical capability. So the first priority in optimization is always to increase reuse, and the second is to reduce prefix instability.

    In practice with Baidu AI Cloud’s LLM services, developers should treat the billing items and caching strategy in the official documentation as authoritative, and run load tests and canary releases based on their own business’s reuse characteristics. Deciding the caching strategy with real data rather than estimates is the most reliable way to control token costs.

    7. Summary

    The essence of a cache hit is the reuse of intermediate prefix state, and there is only one criterion: an exact match from token 0 onward. Once you understand this, you can derive on your own whether writing is billed extra, why hits fail, and why different implementations offer different discounts. In practice, focus on three things: stable content first, dynamic content last, and an observable hit rate. Token cost then turns from uncontrollable fluctuation into a designable metric.