Reducing LLM Inference Costs: A Practical Guide to Cache Hit Pricing

    As LLM service providers introduce discounted pricing for cached input tokens, optimizing inference costs requires a shift from minimizing total tokens to maximizing token reuse. This guide explores the technical principles of prefix KV caching, structured methods for improving cache hit rates, cost-benefit quantification, and essential boundaries for maintaining system correctness and security.

    1. From a Pricing Adjustment to the Real Structure of Inference Costs

    Recently, an interesting pricing trend has emerged in the industry: a cloud provider on its Model-as-a-Service (MaaS) platform reduced the cached input token price for a specific model in a certain region to 20% of its original price, while keeping other billing items unchanged. This adjustment appears to be a simple price change, but it reveals a key fact about the current cost structure of LLM inference—the processing cost of input tokens is not homogeneous. The reusable portion has a much lower marginal cost than the initial computation.

    To understand the significance of this adjustment, we must break down the billing structure of an inference request. The industry generally adopts a three-part structure:

    • Input tokens (cache miss): The model needs to execute a complete forward pass, incurring the highest compute cost.
    • Input tokens (cache hit): The intermediate calculation results for this prefix have been reused, requiring only incremental computation, which significantly reduces overhead.
    • Output tokens: Generated token-by-token through autoregression, which cannot be parallelized and usually has the highest unit price.

    When cached input is priced separately at a fraction of the original price, it maps the technical fact of “compute reuse” into an accountable business fact. For developers, this means the focus of cost optimization shifts from “reducing total tokens” to “increasing token reuse rate”.

    2. Technical Principles of Cache Hits: Prefix Reuse, Not Result Reuse

    It is necessary to clarify a common misunderstanding: this caching is not a result cache where “the same question returns the same answer,” but rather prefix KV caching. When Transformer’s self-attention mechanism encodes a token sequence, it generates Key/Value tensors for each position. When the prefix of a new request exactly matches a cached prefix, this KV state can be loaded directly without recalculation.

    This leads to three engineering constraints:

    1. Strict prefix matching required. Comparison is done token by token from the beginning. Once a position differs, all subsequent content cannot hit the cache.
    2. Sequence sensitive. Swapping the order of the system prompt and user instructions will result in a zero hit rate.
    3. Limited lifecycle. The cache is constrained by capacity and time-to-live (TTL). After being idle for a long time, it will be evicted and must be billed again.

    These three constraints directly dictate the design of prompt engineering and system architecture.

    3. Structured Methods to Improve Hit Rates

    3.1 Prioritize Stable Prefixes

    Place content with a low frequency of change at the very beginning, and content with a high frequency of change at the end. The recommended order is: model role and global constraints -> tool/function definitions -> domain knowledge snippets -> conversation history -> current user input.

    1. [Stable] System role and output format constraints
    2. [Stable] Tool schema definitions (fixed field order)
    3. [Semi-stable] Retrieved knowledge snippets (sorted by document ID)
    4. [Variable] Multi-turn conversation history
    5. [Variable] Current user question

    3.2 Eliminate Implicit Variables

    Timestamps, random IDs, request tracking numbers, and floating-point numbers with inconsistent precision, if concatenated into the system prompt, will make the supposedly stable prefix different every time. Such content should be moved after the prefix or replaced with placeholders injected at runtime.

    1. # Bad example: Different every time, cache never hits
    2. system = f"Current time {datetime.now()}, request {request_id}, you are an assistant..."
    3. # Good example: Stable prefix + trailing variables
    4. SYSTEM_PROMPT = "You are an enterprise knowledge base assistant. Answers must cite source IDs."
    5. def build_messages(question: str, ctx: list[dict]) -> list[dict]:
    6. return [
    7. {"role": "system", "content": SYSTEM_PROMPT},
    8. {"role": "user", "content": format_context(ctx)}, # Concatenated after sorting
    9. {"role": "user", "content": question},
    10. ]

    3.3 Batching and Concurrency Strategies

    Cache eviction is related to concurrency pressure. Performing temporal clustering of requests with the same prefix (e.g., micro-batch merging, fixed-window scheduling) is more effective at keeping the cache resident than evenly distributing them. For offline batch processing tasks, grouping and sorting by prefix before submission typically yields a significantly higher hit rate than random order.

    3.4 Context Sorting and Deduplication

    In Retrieval-Augmented Generation (RAG) scenarios, unstable ordering of recalled snippets is a hit rate killer. Snippets should be sorted by document identifier, near-duplicate fragments removed, and overly long contexts compressed or hierarchically summarized. This improves both the hit rate and reduces the total input volume.

    4. Quantifying Cost-Benefit

    Do not judge optimization effects by feel; make cache hits an observable metric. The bill for a request can be abstracted as:

    1. cost = in_hit * p_hit + in_miss * p_miss + out * p_out
    2. hit_ratio = in_hit / (in_hit + in_miss)

    Here, p_hit is typically much smaller than p_miss. For example, if 80% of a business’s input tokens can hit the cache, and the hit price is 20% of the original price, the input-side expenditure can be reduced to about one-third of the original (0.8×0.2 + 0.2×1.0 = 0.36). This explains why providers are willing to offer discounts on hit prices: it encourages resource efficiency rather than mere price reduction.

    When implementing, it is recommended to collect three types of data:

    • Hit rate: The proportion of hit input tokens to total input tokens, segmented by business line, model, and time period.
    • Cache failure reasons: Prefix mismatch, TTL timeout, capacity eviction.
    • Unit business cost: Inference expenditure per 1,000 requests or per 10,000 active users.

    Leverage the platform’s general logging services and monitoring/alerting capabilities to establish dashboards. Set alerts for when the hit rate drops below a threshold—a sudden drop is often a signal that the prompt template has been modified or the retrieval sorting logic has changed.

    5. Correctness and Security Boundaries

    Cost optimization should not come at the expense of quality or isolation. Four bottom lines must be maintained:

    1. Correctness first: Caching only reuses intermediate calculation results and does not change the model’s semantics. If output drift is detected, check the prefix concatenation rather than blaming the cache.
    2. Multi-tenant isolation: Shared prefixes must be limited to global, non-sensitive content. User data, credentials, and personal information must not enter prefixes that can be reused across requests to prevent inferring other users’ inputs via a cache side channel.
    3. Controllable invalidation: For strongly time-sensitive data such as permissions, inventory, and prices, shorten the context’s TTL or place it after the prefix.
    4. Rollback capability: Prompt templates should be version-controlled, changes should be gray-released (gradually rolled out), and hit rates and quality metrics should be compared before and after the change.

    6. Landing Checklist

    • Have prompts been reordered from “stable” to “variable” with fixed field orders?
    • Are there any residual implicit variables like timestamps or random IDs in the system prompt?
    • Are retrieved snippets sorted, deduplicated, and length-controlled?
    • Have dashboards and alerts for hit rate and unit cost been established?
    • Has it been confirmed that there is no sensitive information in cross-user shared prefixes?
    • Have prompt templates been versioned and gray-released?

    Conclusion

    Pricing cached input tokens separately and offering significant discounts essentially turns the “compute reuse capability” into a quantifiable cost lever. For engineering teams, true competitiveness does not lie in negotiating lower unit prices, but in transforming the application’s prompt structure, retrieval chain, and scheduling strategy to be naturally reusable. When the hit rate becomes a first-class metric that is continuously measured and architecturally guaranteed, the reduction in inference costs becomes structural rather than a one-time pricing dividend.