LLM Prompt Caching: How Cache Hits Work and Reduce Token Costs

    Learn how LLM prefix caching reuses KV states, when cache hits can reduce input token charges, and how to structure prompts for reliable reuse. This article covers multi-turn conversations, agent workflows, self-hosted caching architectures, cost measurement, and the security and context-management boundaries that determine real task-level savings.

    1. Why Longer Conversations Do Not Always Increase Costs Proportionally

    In multi-turn conversations and agent workflows, a model often needs to read the same system instructions, business documents, tool definitions, and message history repeatedly. As a task progresses, each request becomes longer. It may therefore seem that every turn incurs the full computational cost of processing the entire history.

    In practice, three quantities must be distinguished:

    • Input tokens submitted: The complete input sent by the client.
    • Input tokens recomputed: The portion the server must process because it cannot reuse existing states.
    • Prices applied: Whether cached and uncached input tokens are billed at different rates.

    If the server supports input prefix caching and the cache for an identical prefix is still valid, it may avoid repeating the full input computation for that history. If the service also offers discounted pricing for cached input, those tokens may be billed at a lower rate.

    A cache hit does not mean the request has become shorter. It means that intermediate states associated with identical input have been reused. The client may still send the complete history, and network transfer, request parsing, and some scheduling overhead remain.

    There is also an important qualification: support for cache reuse does not necessarily mean a service offers discounted cached-input pricing. Computational savings and billing savings are related, but they are not the same thing.

    2. What Does the Cache Store?

    Prefill and Decoding Are Separate Stages

    Inference in an autoregressive large language model typically has two stages.

    The first is prefill, or input processing. The model reads the prompt and produces intermediate states in its attention layers that subsequent computation will need.

    The second is decoding, or incremental generation. The model generates one new token at a time, adds the state for that position to the existing states, and continues generating.

    This should not be interpreted as “the model recomputes the entire history from scratch for every output token.” During normal inference with a KV cache, some intermediate results for earlier positions are retained and used directly during subsequent generation.

    The KV Cache Stores Intermediate Attention States

    In attention, queries, keys, and values are used to calculate attention weights and aggregate information. The keys and values for previous positions can usually be retained for later positions to use. These retained states form the KV cache.

    A KV cache is neither a backup of the original text nor a copy of the complete answer. It consists of internal tensors computed by the model for a particular input sequence.

    A useful way to think about it is:

    The token sequence is the source material. The KV cache is the reusable working state left behind after the model processes that material.

    Cross-request caching extends this reuse from a single generation to multiple requests. When a new request contains an input prefix that has already been processed, the inference system can resume from the corresponding state and process only the new portion.

    A cache hit does not eliminate all subsequent computation, however. New input and output tokens still require processing and may continue to access historical KV states. The attention access, memory consumption, and decoding costs associated with long contexts do not disappear simply because the prefix is cached.

    3. Why Does Reuse Require an Identical Prefix?

    Causal Attention Defines the Reuse Boundary

    Under standard causal attention, the state at a position depends on the input at that position and all earlier positions, not on later tokens.

    If the model, tokenization, positional encoding, and relevant execution settings are compatible, two requests with exactly the same tokens from the beginning through a given position can reuse the intermediate states for that prefix.

    If a token changes somewhere in the sequence, later positions may have different states because their context has changed. The KV states for the original suffix can no longer be reused directly.

    For example:

    1. Request 1: Fixed instructions + Fixed documents + User question A
    2. Request 2: Fixed instructions + Fixed documents + User question B

    These requests can share the prefix states for “Fixed instructions + Fixed documents.”

    Now consider:

    1. Request 1: Timestamp A + Fixed instructions + Fixed documents + User question
    2. Request 2: Timestamp B + Fixed instructions + Fixed documents + User question

    Because the requests differ at the beginning, the identical documents that follow generally cannot be reused as part of that continuous prefix.

    Similar Text Is Not Necessarily Identical Input

    Cache matching generally depends on the actual token sequence received by the model, not on semantic similarity as perceived by a reader.

    Any of the following may change the match:

    • Different spaces, line breaks, or punctuation.
    • A different order of tool definitions or document sections.
    • Changes to message roles, templates, or delimiters.
    • Timestamps or random identifiers inserted near the beginning.
    • Inconsistent text serialization.

    Cache optimization therefore requires checking the stability of the complete rendered model input, not just whether the main text looks unchanged.

    The length of an exact match also does not necessarily equal the reported number of cached tokens. Cache block boundaries, minimum cacheable lengths, expiration times, and server-side policies can affect the amount actually reused.

    Prefix Caching Is Different from Semantic Caching

    Exact prefix caching reuses intermediate model states. The model still performs the remaining inference for the current request.

    Semantic caching typically retrieves a previous answer based on question similarity and attempts to return that result directly. It can reduce or even avoid model calls, but it risks treating similar questions as equivalent.

    The correctness boundaries differ:

    • Prefix caching checks whether input states are compatible.
    • Semantic caching must also determine whether an earlier answer applies to the current question.

    These mechanisms should not be treated as interchangeable when designing a system.

    4. How Cache Hits Reduce Token Charges

    Suppose a request has:

    • Total input tokens: (I)
    • Cached input tokens: (H)
    • Output tokens: (O)
    • Standard input price: (P_i)
    • Cached input price: (P_c)
    • Output price: (P_o)

    If the service charges different rates for cached and uncached input, the base cost is:

    [
    \text{Cost} = (I-H)P_i + HP_c + OP_o
    ]

    Token counts and price units must be consistent. If prices are quoted per million tokens, convert the token counts accordingly.

    The following example is entirely hypothetical and does not represent any provider’s pricing.

    Assume standard input costs 10 currency units per million tokens and cached input costs 2 currency units per million tokens. A request contains 100,000 input tokens, of which 90,000 hit the cache:

    1. Input cost without caching:
    2. 100,000 / 1,000,000 × 10 = 1 currency unit
    3. Input cost with caching:
    4. 10,000 / 1,000,000 × 10
    5. + 90,000 / 1,000,000 × 2
    6. = 0.28 currency units

    The input cost for this request falls by 72%. The total request cost does not necessarily fall by 72%, because this calculation does not reduce output charges.

    If the service also charges for cache writes, storage, or other items, include those charges in the cost model. Creating a cache for a long prefix used only once, or rarely reused, may not be worthwhile.

    An answer generated in the previous turn is billed as output for that turn. It does not automatically qualify for cached-input pricing just because it might be cached later. Such pricing may apply only when the answer is submitted again as input in a subsequent request and actually produces a cache hit.

    5. Why Conversations and Agents Are Good Candidates for Caching

    Multi-Turn Conversations Naturally Build Growing Prefixes

    A typical conversation can be represented as:

    1. Turn 1: System instructions + User message 1
    2. Turn 2: System instructions + User message 1 + Reply 1 + User message 2
    3. Turn 3: System instructions + User message 1 + Reply 1 + User message 2 + Reply 2 + User message 3

    If earlier messages remain unchanged, each later request usually contains a substantial continuous portion of the previous request. This creates strong potential for prefix reuse.

    Whether the previous turn’s generated content can immediately become reusable in the next turn depends on whether the inference engine retains the relevant states and whether the next request’s rendered tokens match them. New message-boundary markers or template changes can also affect where the match ends.

    Agent Workflows Often Combine Long Histories with Small Updates

    Agents frequently carry the same task instructions, tool definitions, file contents, and execution history across requests. Each step may add only a small tool result or action instruction.

    A long stable prefix with a short per-step addition is well suited to reducing repeated input-processing costs.

    However, this advantage can be lost if the agent rearranges documents, rewrites history, or inserts the current state at the beginning of the prompt on every turn. Cache effectiveness depends not only on the model service but also on how the framework organizes context.

    Caching Does Not Replace Context Management

    Caching reduces repeated processing, but it does not solve every long-context problem:

    • Context windows still have length limits.
    • Historical information may become stale or contradictory.
    • Irrelevant content may affect model decisions.
    • Long histories still consume KV storage.
    • Request transfer and parsing costs remain.

    Cache optimization should therefore work alongside summarization, document selection, and history trimming. Low-value history should not be retained indefinitely merely to improve the cache hit rate.

    6. How to Structure Prompts for Effective Cache Hits

    Put Stable Content Before Dynamic Content

    Without compromising instruction priority or task correctness, organize stable content into a continuous prefix:

    1. Stable system rules
    2. Stable tool definitions
    3. Reusable business documents
    4. History appended in order
    5. New questions and tool results for the current turn

    If timestamps, request IDs, or random identifiers are not needed by the model, keep them in request metadata or logs. When they must appear in the prompt, place them according to task requirements while avoiding unnecessary disruption of the stable prefix.

    Keep Rendering and Serialization Consistent

    Use stable ordering and consistent formatting for tool definitions, configuration objects, and document excerpts.

    The same material should not produce different model input because of collection iteration order, random sorting, or changing formatting. Version prompt templates and record a digest of the final rendered input to help investigate fluctuations in cache hits.

    A temporary drop in hit rate after a template update is generally expected: the new template creates a different prefix.

    Avoid Rewriting Established History on Every Turn

    Summarizing the entire history on each turn may shorten the input, but it may also invalidate the existing prefix.

    A more balanced approach is to manage context by task phase. Keep appending during a continuous execution phase, then summarize and reorganize when the task enters a new phase, historical information loses value, or the context approaches its limit.

    Whether restructuring is worthwhile depends on input length, cache reuse, answer quality, and end-to-end latency—not on a single metric.

    7. Implementing Cross-Request Caching in Self-Hosted Inference

    Block Storage and Prefix Indexing

    A common approach divides KV states into fixed-size storage blocks and uses logical mappings to manage physical memory. This reduces fragmentation and waste associated with large contiguous allocations.

    The system also needs an index to identify reusable prefixes. A block identifier generally needs to account not only for the tokens in the current block but also for the preceding prefix state. Otherwise, it could incorrectly reuse a block whose local text is identical but whose earlier context differs.

    Block storage addresses memory management. Prefix indexing addresses reuse identification. A block-based memory mechanism alone does not automatically provide cross-request caching.

    Prefix Trees and Eviction Policies

    Another approach organizes shared prefixes in a tree. Requests reuse states along common paths and store their new content at branch points.

    Regardless of the data structure, the system needs cache eviction. When storage is limited, it may prioritize removing states that have not been accessed recently, have fewer references, or provide less benefit.

    Retaining more cached states creates more opportunities for hits, but it can leave less memory for active requests. Maximizing the hit rate too aggressively may therefore reduce concurrency.

    Routing and Tiered Storage

    In a multi-instance deployment, requests with the same prefix may be routed to different nodes. If the relevant cache is not local, the opportunity for reuse may be lost.

    Scheduling can account for cache affinity, but it must also preserve load balancing.

    Some architectures move colder states to other storage tiers. This expands retention capacity, but restoring a cache requires data transfer. For short prefixes, restoration may cost more than recomputation. Measurement is necessary to determine whether it is beneficial.

    8. Measuring Savings Beyond the Cache Hit Rate

    A high hit rate does not necessarily mean a lower bill. At minimum, track the following metrics.

    Input-token-weighted cache hit rate. Divide total cached input tokens by total input tokens over the measurement period. This better reflects the reuse value of long requests than the percentage of requests with any cache hit.

    Actual billing and cost per task. Track standard input, cached input, output, and other charges. Focus on the total cost of completing a task.

    Time to first token and total completion time. Caching usually has a more direct effect on input-processing time. Overall task latency also depends on queueing, output length, tool calls, and network conditions.

    Cache occupancy and effective throughput. In self-hosted systems, monitor whether cached states reduce memory available to active requests and whether restoration, eviction, or scheduling adds overhead.

    Retries and result quality. A lower cost per request does not necessarily mean a lower cost per task. If a caching optimization causes context errors, increases retries, or lowers task success rates, the overall benefit may be negative.

    Evaluate cold-cache, warm-cache, and high-concurrency conditions separately. Keep request content and output lengths as comparable as possible. A single ideal cache hit is not a substitute for production measurements.

    9. Security and Applicability Boundaries

    KV caches contain internal states related to the input. They require protection even though they are not stored as plaintext. Systems should account for access controls, tenant isolation, retention periods, cleanup mechanisms, and sensitive-data handling requirements.

    Sharing caches across users or tenants requires particularly clear security boundaries to prevent incorrect reuse and potential side-channel risks. Cache identifiers and lookup logic must also guard against collisions and state mixing caused by incompatible configurations.

    A cache hit does not guarantee identical output. The model still performs subsequent generation, and sampling settings and execution behavior may affect the result. Applications that require consistency need separate output constraints, validation, and result-management mechanisms.

    10. Optimize for Effective Task Cost

    LLM cache hits reuse KV intermediate states for identical input prefixes under compatible conditions. This reduces repeated prefill computation and can lower input token charges when the service provides corresponding pricing.

    Effective implementation rests on four priorities:

    1. Build the longest useful continuous prefix from stable content.
    2. Verify savings through actual usage and billing rather than assuming similar text will produce a hit.
    3. Optimize caching together with context management, storage capacity, and scheduling.
    4. Evaluate total task cost, latency, success rate, and security boundaries.

    The goal is not to keep all history in the context forever. It is to reuse valuable computation appropriately without compromising correctness.