LLM Prompt Caching and Token Cost Optimization: A Practical Guide

    This article explains how LLM prefix caching works and why it lowers token costs for long-context AI agents. It covers the difference between cache reads and new tokens, the technical basis of prefix reuse, how cached-input discounts and cache-write charges shape real bills, common causes of cache misses, and practical context-engineering patterns such as layered context, append-only history, stable serialization, and subtask isolation. It also shows how to track cache hit rate and per-task cost, and lists common misconceptions about caching.

    1. A Counterintuitive Billing Pattern

    When an agent task finishes, the model may have been called hundreds of times. Intuitively, every request carries the full conversation history of hundreds of thousands of tokens, so the cost should grow linearly with the number of calls, or even faster. Yet the actual bill is often far lower than expected.

    The gap is not a billing error. It comes from two fields in the usage data that are easy to overlook. Within the input tokens of a single request, the portion marked as a cache read is usually billed at a discounted fraction of the normal input price. Only the newly added portion that is not covered by the cache is billed at full price. Platforms name these two fields differently, but the meaning is the same: one is the length of the reused prefix that hit the cache, and the other is the newly added length that actually went through full computation for this request.

    In an observed coding-assistant scenario, a single-step request read about 119K tokens of historical prefix and performed full computation on only about 875 newly added tokens, with most of the former billed at roughly one-tenth of the normal input price. This rule is not a marketing feature of a particular product. It is a natural result of how inference systems are implemented, and API pricing, GPU memory management, cluster scheduling, and agent framework design all operate under its constraints.

    2. What a Cache Hit Really Means: Prefix Reuse, Not Result Reuse

    A common misconception needs to be cleared up first: a cache hit does not cache the answer. It caches intermediate state.

    LLM inference has two stages. The prefill stage runs one forward pass over the input sequence and produces the intermediate representations at each position along with the key and value tensors needed for attention. The decode stage then generates tokens one by one on that basis. Prefill is the expensive part: its computation scales with input length, and the GPU memory occupied by the key and value tensors also grows linearly with length.

    Prefix caching works like this: if the leading tokens of the current request are exactly identical to those of a previous request, the corresponding intermediate state can be reused directly, skipping the repeated computation. The condition for a hit is therefore a prefix that is strictly equal token by token, not semantic similarity.

    Three hard constraints follow from this:

    • Order sensitivity: if any token in the prefix changes, everything from the point of change onward is invalidated.
    • Length sensitivity: a hit always counts in whole-prefix units, and truncating or inserting content breaks all subsequent positions.
    • Position sensitivity: reuse depends on consistent positional encoding and attention masks, so moving identical content elsewhere usually does not hit.

    Schematic examples show how request construction directly determines hit effectiveness:

    1. # High hit rate: history unchanged, only appended at the end
    2. [system prompt][tool definitions][history turns 1..N][new input this turn]
    3. # Low hit rate: timestamps/random IDs/reordering cause prefix drift
    4. [system prompt (with current time)][tool definitions (random order)]...

    3. Billing Logic: Why the Discount Is Structural

    Cache reads can be discounted because they save reusable resources: compute and GPU memory bandwidth. The system still has to read the cached key and value tensors and take part in attention computation, and there is still GPU memory usage and scheduling overhead. That is why the price is not zero, but it is significantly lower than full-price input.

    Writing to the cache, by contrast, requires extra work: allocating space for the new prefix, saving the intermediate state, and maintaining the index and eviction policy. Most platforms therefore charge separately for cache writes, usually at a price higher than normal input. This leads to an important engineering judgment: caching is not a free acceleration switch but a long-term investment with an upfront cost. The write cost is amortized only when the same prefix is reused by multiple subsequent requests.

    A simplified cost model helps with decisions:

    1. Cost per request ≈ new tokens × full price
    2. + hit prefix × discount price
    3. + first-time written prefix × write price
    4. With prefix length P and reuse count n, average cost decreases as n grows;
    5. when n is small, the write overhead may offset the benefit.

    The practical implication is that batched, serial calls that share the same prefix benefit most. One-off calls with different prefixes gain almost nothing and pay extra write fees.

    4. Typical Sources of Cache Misses

    Many “there is a cache but it never hits” problems in engineering come from prefixes being changed unintentionally:

    • Dynamic injection: inserting the current time, a random request ID, or a user nickname into the system prompt.
    • Structural drift: unstable ordering of tool definitions or knowledge snippets, producing a different serialization each time.
    • Content write-back: inserting model output or retrieval results into the middle of the history instead of appending them at the end.
    • Context trimming: deleting several turns from the middle to control length, which invalidates everything after them.
    • Multiple branches: parallel subtasks each rewriting the same history, forming mutually mismatched branch prefixes.
    • Lifecycle issues: cache entries have a lifetime, so a request after a long idle period requires a new write.

    5. Cache-Friendly Agent and Context Design

    Since hits depend on prefix stability, stability should be a first-class goal in the architecture.

    1. Organize context in layers. Split content into a stable layer (system instructions, tool contracts, long-term rules), a slowly changing layer (task background, retrieved material), and a volatile layer (current observations and new output), and order them strictly this way so volatile content is always at the tail.

    2. Manage history by appending. Only append conversation turns and tool call results at the end; never modify or delete them in the middle. When a correction is needed, override the old conclusion with newly appended content instead of rewriting history.

    3. Serialize deterministically. Use fixed key order and fixed formatting for tool definitions and structured data to avoid drift from hash traversal order or floating-point formatting differences.

    4. Separate prefix from suffix. Move volatile information such as timestamps and session identifiers to the end of the request or to parameter positions, keeping the opening bytes identical.

    5. Trade compression for hits. Summarize and compress very long histories into a smaller, stable summary block, which both reduces full-price new tokens and makes the prefix last longer. The compression result should be cached and reused to avoid re-summarizing at every step.

    6. Isolate subtasks. Parallel branches should use their own independent and fixed prefixes to avoid cross-contamination, with shared parts extracted into a read-only stable layer.

    7. Batch and warm up. For a long prefix that is known to be reused, perform one write during idle time so subsequent requests hit directly.

    6. Observability: Turning Hits into an Operational Metric

    Optimization must be measurable. It is recommended to collect, at the gateway layer, the total input, hit prefix length, new length, and write length for every request, and to compute the hit rate and cost per task:

    1. Hit rate = hit prefix tokens / total input tokens
    2. Cost per task = Σ(new × full price + hit × discount price + write × write price)

    With logging services and monitoring alerts, dashboards can be broken down by business line, model tier, and agent type. When the hit rate drops abnormally, the cause can usually be traced in the change records to a prompt template adjustment or a serialization change. If an enterprise runs its inference gateway on general cloud capabilities, it can deploy a stateless gateway on a container platform, archive request samples in object storage, and use a message queue to smooth peaks, forming a complete observability and replay pipeline.

    7. Common Misconceptions

    • Assuming semantic similarity is enough: the check is strict token-by-token equality.
    • Assuming caching saves GPU memory: a hit still occupies GPU memory and only saves repeated computation.
    • Assuming longer is always better: writes have a cost, and with insufficient reuse the net result can be a loss.
    • Assuming a hit does not affect output: a hit only changes the computation path, not model behavior, but changing the prefix itself does change the output.
    • Relying on a single switch: real gains come from the combination of context architecture, serialization discipline, and a monitoring loop.

    8. Conclusion

    Prefix caching turns the seemingly wasteful practice of resending history into a structural advantage billed at a discount. Its precondition is a strictly stable prefix, its cost is the first write and GPU memory usage, and its benefit scales with the number of reuses. For developers the path is clear: layered and append-only context organization, deterministic serialization, moderate history compression, and branch isolation, plus an observability system centered on hit rate and cost per task. Get these four things right, and the cost curve of long-context agents will genuinely decouple from business scale.