Input Cache Hit: A Core Mechanism and Practical Guide to Lowering LLM Inference Costs

    This article explains how input cache hit works and why it has become a key lever for reducing large language model inference costs. It breaks down the prefix-matching mechanism behind a cache hit, outlines the main variables that affect hit rate—such as prefix stability, request timing, routing consistency, and model configuration—and describes typical high-hit scenarios like long system prompts, document Q&A, coding assistants, and batch processing. It also provides a practical guide to improving hit rate through prompt layering, removing volatile fields, controlling prefix size, observability, and fallback design, along with common pitfalls and a deployment checklist.

    1. Why Input Cache Hit Matters for Cost Reduction

    On September 9, 2026, a cloud provider announced a price reduction for its flash-series models, with overall invocation costs expected to decline further. The price adjustment is only the surface-level change. What developers should really pay attention to is one of the underlying mechanisms that make such cost reductions possible: input cache hit.

    In the inference pipeline of a large language model, cost is mainly composed of two parts: input-side processing (tokenization of the prompt, position encoding computation, and attention computation) and output-side autoregressive generation. As context windows expand from a few thousand tokens to hundreds of thousands of tokens, the computation on the input side grows roughly linearly or even faster. When a business system handles a large number of requests that share the same prefix but differ in their suffixes—such as a unified system instruction, fixed tool descriptions, repeated Q&A over a long document, or reused code repository context—recomputing the same input becomes pure waste.

    The core idea of input caching is straightforward: store the intermediate states of an input prefix that has already been computed (typically the key-value tensors in the attention mechanism). If a later request has exactly the same prefix, those states are reused directly, skipping the redundant forward computation. A single hit means the computation cost of that prefix is amortized to nearly zero.

    2. How a Cache Hit Happens

    To understand hit rate, you first need to understand what qualifies as a hit. The industry commonly uses prefix matching, and the decision chain can be summarized as follows:

    1. After a request reaches the server, the input sequence is normalized and tokenized into a token sequence.
    2. Using the prefix of the token sequence as the baseline, a cache key is computed (usually derived from a hash of the prefix content together with metadata such as the model identifier and quantization method).
    3. The cache index is checked for an entry with the same key, and whether that entry has been evicted or expired is confirmed.
    4. On a hit, the corresponding intermediate states are loaded and only the unmatched suffix is computed in the forward pass; on a miss, the full computation is performed and the result is written to the cache afterward.

    The following pseudocode illustrates the division of labor between the caller side and the cache side:

    1. # Caller side: improve hit rate with a stable prefix + variable suffix
    2. SYSTEM_PROMPT = "You are an enterprise knowledge base assistant and must follow these rules: ..." # unchanged over the long term
    3. def ask(question: str, doc_chunk: str):
    4. # The cache key can only match if the prefix stays stable
    5. prefix = SYSTEM_PROMPT + "\n" + doc_chunk
    6. return llm.chat(
    7. messages=[
    8. {"role": "system", "content": prefix},
    9. {"role": "user", "content": question},
    10. ],
    11. cache_hint=True, # illustrative: the request side signals intent to reuse the cache
    12. )

    It is important to emphasize that a hit does not depend on whether the content “looks similar.” It depends on exact, token-level identity. A single space, a line break, or a timestamp will change the cache key and invalidate the entire prefix.

    3. Key Variables That Determine Hit Rate

    Hit rate is not a matter of luck. It is a metric that can be significantly influenced by engineering practices. The main variables include:

    • Prefix length and stability: The longer and more stable the prefix, the more computation a single hit saves. Conversely, placing variable content at the beginning means a long prefix will never hit.
    • Temporal locality of request arrival: Cache entries typically have a time-to-live window and a capacity limit. If requests with the same prefix are spaced too far apart, the entry may already have been evicted.
    • Concurrency and routing consistency: In a multi-instance deployment, if requests with the same prefix are randomly distributed across instances, each instance must build its own cache, which dilutes the hit rate. Session affinity or prefix-based routing can mitigate this.
    • Model and parameter consistency: Intermediate states are not interchangeable across different model versions or precision configurations; mixing them breaks hits.
    • Degree of content normalization: Timestamps, random IDs, and ordering jitter in retrieval results all introduce false differences.

    4. Typical High-Hit Scenarios

    The first category is long-system-instruction applications. System prompts often span thousands of tokens and include role definitions, output format constraints, safety policies, and tool lists. This content barely changes within a version cycle, making it the highest-quality cacheable prefix.

    The second category is document and knowledge base Q&A. When the same long document is chunked and used as a prefix for a series of follow-up questions, only the final user question changes, and the hit rate can approach the theoretical upper bound.

    The third category is code and intelligent programming tools. Repository structure descriptions, coding conventions, dependency lists, and interface definitions form a stable prefix, while the specific code snippet to be completed serves as the suffix—a natural fit for the prefix reuse model.

    The fourth category is batch structured processing. When the same extraction or classification instruction is applied to thousands of records, the instruction is the shared prefix and each data row is the suffix, so overall cost is significantly amortized as batch size grows.

    5. Practical Guide: Raising the Hit Rate

    Step 1: Layer your prompts. Divide content into a “constant layer—low-frequency layer—high-frequency layer,” placing the constant layer first and the high-frequency variable layer last. A simple template can help:

    1. [Constant layer] role, rules, tool definitions, output format
    2. [Low-frequency layer] domain knowledge, glossary, a few examples
    3. [High-frequency layer] current retrieval chunk, user question, random identifiers

    Step 2: Strip out volatile fields. Move generation timestamps, request IDs, and random numbers out of the prompt and let the server-side logging system carry them instead, avoiding contamination of the cache key.

    Step 3: Control prefix size and eviction pressure. A longer prefix is not always better; trade-offs must be made based on cache capacity and the TTL window. For very long documents, reuse the summary layer first and load detail chunks on demand.

    Step 4: Observe rather than guess. Use logging services and monitoring/alerting systems to collect metrics such as hit rate, average hit prefix length, cache eviction count, and time to first token. Build dashboards and break them down by business line. Optimization without observability cannot be sustained.

    Step 5: Design for graceful degradation. Caching is an optimization, not a correctness dependency. Any hit failure should automatically fall back to the full computation path so functionality is unaffected.

    6. Common Misconceptions and Pitfalls

    • Assuming that “semantic similarity is enough to hit.” The decision is strict token-level matching; semantically similar but literally different content will not hit.
    • Embedding retrieval timestamps in a long prefix, causing the cache to be invalidated every round.
    • Random routing across multiple instances, causing cache fragmentation and an overall hit rate far below single-instance test results.
    • Mixing different model versions or parameter configurations, making cache entries unreusable or even producing abnormal results.
    • Focusing only on unit price while ignoring effective hits. Unit price reduction and hit rate improvement are two independent cost-reduction curves; only when they stack does the benefit become obvious.
    • Ignoring output-side cost. Input caching only optimizes the input side; output length still needs to be controlled through format constraints and structured output.

    7. The Cost Perspective: How Savings Stack Up

    Suppose a request has 8,000 input tokens and 300 output tokens. If a 7,000-token prefix hits stably, the actual billed input per request can drop to around 1,000 tokens, reducing input-side cost by more than 80%. When the provider simultaneously lowers the unit price, the two curves multiply, and the overall invocation cost decline clearly exceeds what a simple price cut would suggest. This also explains why “overall invocation costs are expected to decline” becomes the core phrasing in such announcements.

    8. Deployment Checklist

    • Have prompts been layered into constant/variable parts, with all variable content placed at the end?
    • Are there pseudo-difference fields such as timestamps or random IDs?
    • Is routing or session affinity based on prefix consistency?
    • Are hit rate, eviction count, and time to first token collected with alerts configured?
    • Is automatic fallback on hit failure implemented?
    • Are input-side optimization and output length governance being advanced in parallel?

    In general engineering practice on cloud platforms such as Baidu AI Cloud, input cache hit is regarded as part of the cost infrastructure for LLM applications: it does not change the model’s capability boundary, but it directly determines the real cost per unit of business volume. Treating it as an engineering capability that needs to be designed and observed—rather than an occasional windfall—is the right way to achieve stable cost reduction.