LLM Prompt Caching and Token Cost Reduction: A Practical Guide

    This article explains how LLM cache hits work and why they significantly reduce token costs. It covers the technical mechanism of KV cache reuse, the pricing logic behind input-side discounts, common causes of cache misses, and actionable strategies for structuring context to maximize cache hit rates. Readers will learn how to organize prompts, stabilize dynamic content, and treat cache hit rate as a first-class engineering metric.

    1. An Unusual Billing Pattern

    A single AI agent task can trigger hundreds of model calls. Intuitively, if every step resends the full conversation history, the cumulative input could easily reach tens of millions of tokens, and the bill should scale accordingly. In practice, however, the actual bill is often far lower than this estimate.

    The discrepancy is not a billing error. It comes from a field in the usage breakdown that is easy to overlook. Different platforms name it differently: some call it cached input tokens, others call it cache-hit tokens. This field records how much of the input in a given request did not undergo full attention computation but instead reused intermediate results that had already been computed.

    Industry measurements illustrate the scale. In a typical single-step request from an AI coding tool, the historical prefix is about 119K tokens, while the genuinely new content requiring full computation is only about 875 tokens. In other words, more than 99% of the input is reusable, and most of it is billed at a discounted fraction of the standard input price. This is the real reason the bill does not grow linearly with the number of calls.

    2. What a Cache Hit Really Means: Reusing KV, Not Text

    To understand cache hits, you must separate two concepts: repetition at the text level and reuse at the computation level.

    During autoregressive generation, an LLM computes Key and Value vectors for every token. These tensors form the KV Cache. Attention computation for subsequent tokens depends only on the existing KV and does not need to re-derive the representations of historical tokens. Therefore, as long as the input prefix of two requests is identical, the KV for that prefix can be taken directly without recomputation.

    This leads to a precise definition of a cache hit: when a segment of a request’s input sequence, starting from the beginning, is identical to a previous request, and the factors that affect KV values—model, weight version, quantization configuration, randomness-related parameters—are consistent, the KV corresponding to that prefix is reused directly. Those tokens count as cache hits.

    Three commonly misunderstood points deserve emphasis:

    • Hit detection is prefix matching, not set matching. If even one token differs from the start, nothing after it can hit.
    • What is reused is intermediate computation, not the response content. It does not make the model “remember” the previous answer.
    • Hits are time-sensitive. Cache entries are subject to capacity and lifetime limits, and expired entries must be recomputed.

    Schematically, a request’s input can be split into three segments:

    1. [ Stable prefix: system instructions + tool definitions + long-term history ] -> cache hit, low price
    2. [ Variable middle: timestamps, retrieval results, randomly ordered content ] -> breaks the hit, full price
    3. [ New suffix: current user input and latest tool returns ] -> full-price computation

    The engineering goal is clear: make the first segment as long as possible and the second as short as possible, or eliminate it entirely.

    3. Pricing Logic: Why the Discount Applies Only to Input

    The cost savings from cache hits are tied directly to the pricing structure. The cost of a request can be abstracted as:

    1. Total cost ≈ cached prefix tokens × discounted unit price
    2. + uncached input tokens × standard input unit price
    3. + output tokens × output unit price

    The discounted unit price is typically only a small fraction of the standard input price, while the output price is generally higher than the input price. This structure yields two implications.

    First, the key variable for cost reduction is the hit rate, not the total input volume. Compressing a 200K context to 100K yields limited benefit if the prefix remains stable; conversely, raising the hit rate from 0% to 90% in a 200K context produces immediate savings.

    Second, caching optimizes input only, not output. Making the model write less often yields less than making it read less repeated content. In agent scenarios, the optimization focus should therefore be on context organization.

    In addition, writing to the cache may incur some time or cost overhead in certain implementations. This means reusing a one-off, extremely short-lived prefix may not be worthwhile; the value of caching grows with the number of reuses.

    4. Common Causes of Cache Misses

    When hit rates fall short of expectations in practice, the cause is usually one of the following.

    Unstable prefix. Placing the current time, random IDs, or a retrieved document list at the very front, after the system instructions, makes the prefix different on every request and invalidates everything that follows.

    Non-deterministic ordering. If tool lists, knowledge base snippets, or few-shot examples are concatenated in hash-traversal order or in the order concurrent calls return, ordering jitter changes the prefix.

    Model or parameter drift. Switching model versions mid-session, changing quantization precision, or altering configurations that affect numerical computation makes old KV unusable.

    Cache eviction. When the context is too long or concurrency is too high, cache entries may be evicted due to capacity or lifetime limits, appearing as a hit rate that fluctuates unpredictably.

    Expiration and idle gaps. If the interval between two requests is too long, the cache has already expired, and the first call is necessarily full price.

    5. Actionable Optimization Practices

    Structured layering. Divide the context into a stable layer, a semi-stable layer, and a volatile layer, and concatenate them strictly in that order. Put system instructions and tool definitions first, retrieval content in the middle, and the current input last.

    Stabilize dynamic content. Move timestamps, random ordering, and pagination cursors out of the prefix; sort retrieval results before concatenating them; when changes are unavoidable, move the change point later rather than inserting it earlier.

    Control prefix length and reuse cadence. High-frequency, long-lived prefixes are the most worth caching; for one-off tasks, evaluate whether disabling the cache is more economical.

    Keep configurations consistent. Fix the model and inference configuration within the same session, and avoid mid-session changes that invalidate the entire cache.

    Improve observability. Collect per-request total input, cached amount, hit rate, and cache invalidation reasons in your monitoring and alerting system, and treat hit rate as a first-class metric in dashboards and capacity planning.

    Coordinate with the engineering stack. Logging services help trace differences in request sequences; container platforms and scheduling policies help ensure session affinity so that requests with the same prefix land on instances that can reuse the cache. In related practices at Baidu AI Cloud, such capabilities are typically offered as combinations of general cloud product categories rather than relying on a single proprietary interface.

    6. Constraints on System Design

    Cache hits are not just a cost technique; they are a low-level constraint that spans multiple layers.

    For API pricing, tiered input pricing directly changes the cost model. For GPU memory management, the KV Cache is a major source of consumption, and capacity and eviction policies set the upper bound on the hit rate. For cluster scheduling, requests and sessions need a degree of affinity, and load balancing cannot look at average latency alone. For agent frameworks, context organization, the size of tool definitions, and history compression strategies should all account for prefix stability at the design stage.

    A practical rule of thumb: before any context change, ask whether it breaks consistency from the beginning. If the answer is yes, evaluate whether the loss is worth it. Maintaining a high hit rate usually delivers more stable and predictable cost reduction than repeatedly compressing context length.