Input Cache Hits and LLM Billing Optimization

    Input cache hits let LLM inference reuse an exact matching prefix through KV cache instead of recomputing it, often at a lower input price. This article explains how prefix matching works, why it affects both cost and latency, common billing misconceptions, and practical ways to raise hit rates without sacrificing correctness or tenant isolation.

    What an Input Cache Hit Means

    In online inference with large language models, a single request usually contains a system prompt, conversation history, retrieved passages, and the current user question. The server splits the input into tokens and bills by token count. An input cache hit means the current request’s input prefix is an exact token-sequence match with content processed recently, so the inference engine can reuse the already computed key-value cache (KV cache) instead of re-encoding the entire prefix from scratch.

    From a billing perspective, the hit portion is often charged at a lower unit price, while the miss portion is still billed at the regular input price. A cache hit is therefore not “free.” The same prefix is charged at the full rate once, and later reuse is charged at a discounted rate. Understanding this distinction is what aligns product design and request construction with real savings, rather than assuming that any repetition is automatically discounted.

    A cache hit depends on an exact prefix match, not semantic similarity. One extra space, swapping two sections of the system prompt, or inserting a dynamic timestamp in the middle changes the prefix hash and turns the request into a miss. Reusable prefixes should be treated as a first-class design concern.

    Why It Matters for Both Cost and Latency

    Decoding in large models is usually autoregressive, but the prefill stage runs a forward pass over the entire input. Long system prompts, long documents, and multi-turn history make prefill the main source of latency and compute. After KV cache reuse, prefill only has to process the new suffix. On the input side, only the new portion is billed at the full rate; the hit portion is billed at the discounted rate.

    For enterprise applications, the benefit usually shows up in three situations:

    • Fixed personas and tool instructions. Customer support, office assistants, and code-review bots often use stable system prompts of several thousand tokens.
    • Multi-turn sessions. As users follow up, history grows, but earlier turns keep reappearing as a prefix.
    • Retrieval-augmented generation (RAG). The same knowledge passage is cited repeatedly, or many people ask about the same document within a short window.

    On latency, time to first token (TTFT) often drops noticeably after a hit, which helps keep SLAs stable during peak periods. On cost, if the hit rate can reach 50% or more, the input bill can approach “pay mainly for the increment,” which matters a lot for high daily request volume.

    Billing Definitions and Common Misconceptions

    Cloud LLM services may use slightly different names, but the logic is largely the same: input is split into cache-hit tokens and cache-miss tokens, and output is still billed separately by generated tokens. Developers should align on the following points to avoid reconciliation disputes.

    First, hits are measured on token prefixes, not exposed to the business as a hash of the whole string. The application should keep serialization stable: the same message list must produce the same byte sequence and the same tokenization.

    Second, caches have a lifetime and a capacity limit. If an entry expires, is evicted, or is not shared across instances, identical content can still miss. “Theoretically the same” is not the same as “a hit on the bill.”

    Third, output is not discounted because the input hit. Savings are mainly on the input side. If the product design produces very long replies, total cost can still be dominated by output.

    Fourth, tool calls, multimodal input, and structured output change the actual input. For example, stuffing the full tool result back into context every time “pollutes” the prefix. Put volatile parts in the suffix and stable parts at the front.

    An illustrative request layout follows. It is only meant to show prefix stability, not a vendor-specific API:

    1. [system: fixed persona and constraints] ← should stay unchanged for a long time
    2. [tools: fixed portion of the tool schema]
    3. [retrieved: reusable document chunks] ← sort by document ID to avoid reordering
    4. [history: earlier turns in time order]
    5. [user: this turn's new question] ← the suffix that should change often

    For reconciliation, record total input tokens, hit tokens, miss tokens, and output tokens together. Hit rate = hit tokens / total input tokens. Put that metric in monitoring so a prompt revision that collapses the hit rate is visible.

    How to Raise the Hit Rate in Engineering

    Raising the hit rate is prefix engineering, not parameter mysticism. Work at the protocol, data, and scheduling layers.

    Protocol layer: freeze the prefix. Release system prompts as versions. Do not concatenate dates, random greetings, user city, or other volatile fields at runtime. Information that must be dynamic belongs in the user message or a separate field, and it belongs at the end. Serialization should fix field order, newlines, and whitespace so JSON key order does not drift.

    Data layer: make retrieval results reusable. Do not reshuffle RAG results on every relevance-score tweak and jitter the prefix. Use a policy such as “document ID ascending, truncated to a fixed number of chunks,” or short-lived caching of popular documents so the same document appears as the same token sequence inside a time window. In multi-tenant systems, route by tenant plus session toward the same inference instance group to reduce cross-machine cache misses.

    Session layer: bound the history window. Appending history without limit makes the prefix longer. Absolute hit volume may grow, but each new turn still adds a miss, and the context limit may be hit. In practice, use a sliding window: keep the system prompt plus the latest N turns, and insert a summary of older content as a fixed block. Version the summary text as well, so different wording on each summary does not change the prefix.

    Scheduling layer: affinity and warmup. For hot system prompts, send a warmup request during off-peak hours so the cache enters the working set. Sticky routing at session level—the same conversation_id to the same replica group—can raise multi-turn hits substantially. This is a general load-balancing idea. Specific product capabilities follow each cloud’s console documentation and are not tied to one vendor’s implementation here.

    Working with Peak and Off-Peak Pricing and Batch Jobs

    Many cloud inference services charge different unit prices at peak and off-peak times, or offer a lower price for input cache hits. Requests that can run asynchronously should go to off-peak windows: offline summarization, knowledge-base pre-encoding, evaluation-set replay, and batch quality checks. Online chat should prioritize a stable prefix and use hit rate to offset peak premiums.

    Batch jobs fit the pattern of “one long prefix, many short suffixes” especially well. For example, run hundreds of checks against the same specification: the document is computed at full price once as the prefix, and later checks are suffixes. Watch concurrency. Too much parallelism can scatter the cache or fill a single machine’s KV capacity, and the hit rate can fall. Run a small load test and watch the inflection point of hit rate and TTFT.

    Quality and Security Boundaries

    Chasing hits must not sacrifice correctness. Putting user privacy or tenant-isolation data into a shared prefix is dangerous. Cache keys must be valid only inside a tenant boundary. Even if text happens to match across tenants, KV should not be shared. Do not log the full prefix, or prompts can leak.

    Over-compressing history can also make the model “forget” important constraints. Keep safety and compliance clauses in the system prompt complete and at the front; summarize only casual chat history. Track both billing and quality: as hit rate rises, task success rate, refusal rate, and hallucination rate should not worsen materially.

    Implementation Checklist

    • Is the system prompt version-frozen, with no runtime random fragments?
    • Is serialization of messages and tool schemas stable and reproducible?
    • Are RAG chunks ordered by a stable key and truncated to a fixed size?
    • Are sessions sticky to the same inference pool, and is there a history-window limit plus a summary policy?
    • Does monitoring split hit and miss tokens, with drill-down by API, tenant, and prompt version?
    • Are peak online traffic and off-peak batch work on separate queues so they do not crowd each other’s cache working set?

    Input cache hits turn repeated computation into a measurable cost lever. Once they are designed into the request protocol and the session model, both the bill and latency improve. If the application keeps concatenating dynamic prompts, even a low unit price will not show up. Start with one core path: freeze the prefix, observe the hit rate, then extend to RAG and batch workloads, and prove the optimization with data rather than intuition.