How LLM Prompt Caching Works and How to Cut Token Costs with Cache Hits

    Prompt caching can reduce LLM inference costs by roughly an order of magnitude for multi-step agent workloads. This article explains how KV cache prefix reuse works at the inference layer, why cached tokens are billed at a fraction of normal input prices, and how API pricing, GPU memory management, and cluster scheduling are shaped by cache behavior. It also provides practical engineering guidelines—stable prefixes, append-only context, session affinity, and cache-hit monitoring—to help you maximize cache hit rates in agent frameworks.

    How LLM Prompt Caching Works and How to Cut Token Costs with Cache Hits

    A typical agent task can invoke the underlying model hundreds of times. If every call re-sent and re-processed the full conversation history, token bills would explode. Yet on usage dashboards, developers see dedicated fields—named differently across providers, such as cached_tokens or cache read tokens—that track how many input tokens skipped full computation because they hit the cache. Real-world measurements show what a typical coding agent request looks like: about 119K tokens of historical prefix are read from cache, while only the roughly 875 newly added tokens go through full computation. Cached reads are usually priced at about one-tenth of regular input tokens. This article starts from that metric and explains what cache hits actually are, why they save money, and how to exploit them fully in engineering practice.

    1. The Essence of Cache Hits: Prefix Reuse of the KV Cache

    To understand cache hits, you need to go back to the inference mechanics of Transformers. When an LLM processes input, every token computes Key and Value vectors at each attention layer—the KV cache. Generation of subsequent tokens depends only on the KV vectors of earlier tokens, not on their raw text.

    This leads to a crucial property: if two requests start with character-for-character identical content, the KV computation results for that shared prefix are exactly the same, so there is no reason to recompute it. The inference system simply keeps the previously computed KV vectors in GPU memory (or a tiered storage layer). When a new request arrives, it performs prefix matching; matched segments are reused directly, and full forward computation runs only on the new tokens after the first mismatch.

    “Cache hit” is therefore not a business-level concept but a low-level rule of the inference system:

    • The match is on prefixes, not arbitrary fragments. Cache matching compares strictly from the first token onward; any divergence marks everything after that point as a miss. This means how you organize your prompt directly determines your hit rate.
    • The savings are in compute, with lower latency as a side effect. Skipping full computation over the prefix not only cuts costs but also significantly reduces time-to-first-token (TTFT), which is critical for interactive agent experiences.
    • Caches are time-limited and capacity-constrained. The KV cache consumes scarce GPU memory, so inference systems retain hot data only within a certain time window; timeouts or load pressure cause evictions.

    2. How Cache Hits Directly Reduce Token Costs

    Once the mechanism is clear, the billing logic follows naturally. For cached tokens, the inference system skips most of the compute cost, so mainstream API providers charge cache reads at a small fraction of regular input prices—commonly around one-tenth in the industry.

    A simplified calculation: suppose an agent task has 100 steps, each with an average context of 60K tokens, of which 59K is a reusable historical prefix.

    1. Without caching:
    2. Input billed per step = 60,000 tokens
    3. Total for 100 steps = 6,000,000 tokens
    4. With prefix cache hits (cache reads priced at 1/10):
    5. Cost per step ≈ 1,000 (new tokens at full price) + 59,000 × 0.1
    6. ≈ 6,900 token-equivalent cost
    7. Total for 100 steps ≈ 690,000 token-equivalent cost

    That is nearly an order of magnitude difference. This explains why agent framework designers keep emphasizing that append-only context growth is the prerequisite for controllable agent costs. If each step only appends new content to the end of the previous context, the vast majority of tokens across the session’s lifetime are billed at the cache-read rate.

    Conversely, if the framework rebuilds the prompt at every step—inserting a history summary in the middle, dynamically reordering the tool list, or writing the current timestamp into the system prompt—the cache fails on a large scale and the bill immediately reverts to full price per step.

    3. How This Rule Constrains the Entire Stack

    A cache hit looks like just a billing field, but in practice it imposes hard constraints on API pricing, GPU memory management, cluster scheduling, and agent framework design.

    API pricing: The discount on cache reads effectively passes the compute savings back to developers while incentivizing cache-friendly request patterns. It’s a win-win pricing model—the more cache-friendly the request structure, the higher the memory turnover of the system, and the more concurrency a given set of hardware can serve.

    GPU memory management: The KV cache is one of the scarcest resources in an inference cluster. The KV cache for a 100K-token context can occupy several gigabytes of memory. Systems must dynamically trade off “keeping the cache to earn hits” against “freeing memory to admit new requests.” A common approach is tiered storage: hot data stays in GPU memory, warm data is offloaded to host memory or fast disks, and cold data is discarded.

    Cluster scheduling: Prefix caching makes request scheduling stateful. Routing subsequent requests from the same session to the node holding its KV cache yields hits; random routing almost guarantees misses. “Cache-affinity scheduling” has therefore become a standard capability in high-performance inference clusters, with schedulers balancing load distribution against cache locality.

    Agent frameworks: This is where developers have the most direct influence—and the focus of the next section.

    4. Engineering Practices to Maximize Cache Hit Rates

    1. Keep the prefix absolutely stable

    This is the first principle. Everything positioned early in the prompt must be byte-for-byte stable:

    • Place the system prompt, role definitions, and tool definitions at the front, and don’t change them during a session.
    • Avoid embedding any volatile data in the prefix—timestamps, random IDs, dynamically generated greetings.
    • Keep the order of tool definitions fixed; don’t reorder them by relevance at each step.

    2. Organize context by decreasing stability

    A recommended context structure:

    1. [System prompt + tool definitions] ← Most stable, reused across sessions
    2. [Long-term memory / project context] ← Stable within a session
    3. [Conversation history and tool calls] ← Append-only, never modified
    4. [Latest user input] ← Added at each step

    The more stable the content, the earlier it should appear; the more volatile, the later. This pushes the mismatch point of each request as far back as possible, maximizing the matched prefix length.

    3. Append to history instead of rewriting it

    History should only grow, never be modified. If you need to compress context, prefer doing summary replacement at session boundaries—accepting a one-time cache miss in exchange for returning to append-only mode for subsequent steps. Frequent small rewrites are the biggest killer of hit rates.

    4. Preserve session continuity

    Server-side caches have a time-to-live. Issue multi-step calls for the same task in quick succession, and ensure scheduling affinity (most providers handle this automatically based on request fingerprints, but requests after a long idle period will likely start cold). Batch workloads should also be grouped by session rather than shuffled together.

    5. Close the loop with monitoring

    Before and after release, continuously track the share of cache-read tokens via the usage API and treat it as a regression metric for agent framework changes. A healthy coding agent typically shows a cache-read ratio above 90% of total input tokens. If that ratio drops sharply after a version update, you can be fairly confident the context-construction logic introduced prefix perturbations.

    5. Conclusion

    Prompt caching is not a marketing gimmick from any particular vendor; it is a universal rule dictated by the Transformer’s self-attention mechanism: identical prefixes mean reusable KV vectors; reusable KV vectors mean saved compute; saved compute means costs and latency drop together. It constrains API billing models at the top, GPU memory management and scheduling strategies in the inference cluster at the bottom, and directly shapes the context-design paradigm of agent frameworks in between.

    For developers, the takeaway fits in one sentence: make your prompt append like a log, and keep volatile content always at the end. Combined with continuous monitoring of cache-hit metrics, inference costs for agent workloads can typically be compressed by an order of magnitude—without changing the model itself—simply by respecting a rule the underlying system was built on all along.