Prefix Caching Economics: How Hit Rate Determines Your Input Cost

    This article explores the economic impact of prefix caching, analyzing how the cache hit rate significantly reduces input costs in Large Language Model (LLM) inference. It details the necessary conditions for effective prefix reuse, best practices for cache key design, and strategies for monitoring and breaking down hit rates across different operational dimensions.

    1. Calculating the Cost

    Consider a sample pricing model: cached input costs 0.10 units per million tokens, while uncached input costs 3 units per million tokens—a 30x price difference. These figures are for demonstration only; always refer to your provider’s current pricing and billing units.

    Assume an API request has an input of 20,000 tokens, where the first 18,000 tokens consist of system prompts, tool definitions, and conversation history that can be reused. The newly added portion is 2,000 tokens.

    • Full miss (0% hit rate): 20,000 × 3 ÷ 1,000,000 = 0.06 units
    • 90% hit rate: 18,000 × 0.10 ÷ 1,000,000 + 2,000 × 3 ÷ 1,000,000 = 0.0018 + 0.006 = 0.0078 units

    This represents an 87% reduction in single-request input cost. If you process 1 million such requests per month, the input cost would be approximately 60,000 units with a full miss, compared to roughly 7,800 units at a 90% hit rate.

    The calculation formula is as follows:

    Single Input Cost = (Hit Tokens × Hit Price + Missed Tokens × Miss Price) ÷ 1,000,000

    Note that this only accounts for input costs. Output token fees, cache write fees (if charged separately by the provider), and network or server overhead are excluded.

    2. Conditions for Prefix Reuse

    Cache matching applies to the segment of the token sequence from the very beginning, not the entire prompt. Two requests can only share intermediate state if their initial token sequences are identical. “Identical” here refers strictly to the token sequence; text that looks the same at the character level may still tokenize differently.

    KV Cache (Key-Value Cache) consists of the keys and values computed across all layers as the model processes each token. Inference engines save these results, allowing new requests with matching prefixes to reuse them directly and only compute the newly added suffix. Different inference engines have varying granularities and alignment requirements for reusable prefixes. Some engines align by fixed-size chunks, meaning a prefix smaller than a chunk size may fail to hit the cache. Always verify this against provider documentation or your own testing.

    Reuse typically requires the following conditions:

    1. Consistent model name and version: Old caches generally become invalid after a model upgrade.
    2. Consistent tokenizer: The same text will be split into different tokens under different tokenizers.
    3. Token-by-token prefix consistency: This includes spaces, line breaks, punctuation, and field order.
    4. Variable content placed at the end: If timestamps, request IDs, or usernames are inserted at the beginning of a system prompt, all subsequent content will miss the cache.
    5. Cache not expired: If there is a long interval between requests with the same prefix, the cache may be cleared due to expiration or eviction.

    In real-world projects, the most common culprits for cache misses fall into three categories: unstable field ordering during JSON serialization, random changes in the order of tool definition arrays, and inserting the current date into system prompts.

    3. How to Design Cache Keys

    The cache key determines whether two requests can share the same prefix segment. If you assemble prefixes at the application layer or self-host your inference service, consider including the following fields in your key or hash:

    • Model identifier and version
    • Tokenizer version
    • System prompt version or content hash
    • Canonicalized hash of tool definitions (achieved by sorting key names, fixing array order, and removing extraneous whitespace)
    • Few-shot example version
    • Tenant or isolation identifier: In multi-tenant scenarios, caches should be isolated by tenant to prevent different customers from sharing cache states.
    • Inference engine critical configurations, such as block size

    A practical approach is to concatenate the above fields in a fixed order and hash them, for example:

    prefix_key = sha256(model_id | tokenizer_version | sys_prompt_hash | tools_canonical_hash | tenant_id)

    Sampling parameters (like temperature) typically do not affect the intermediate state of the prefix, but provider behaviors may vary. Always test before going live.

    Before deployment, check against this checklist:

    • Are there timestamps, random numbers, or request IDs in the prefix?
    • Is the serialization of tool definitions stable? Do two outputs for the same input produce identical bytes?
    • Do you synchronously update the version number when modifying the system prompt?
    • Do you compare the hit rate before and after changes using the same set of samples?

    4. How to Break Down and Monitor Hit Rate

    The hit rate formula is:

    Hit Rate = Hit Tokens ÷ Total Input Tokens

    Statistics should be based on token counts rather than request counts. Otherwise, a long request and a short request would carry the same weight, and a miss in a long request could be masked by hits in short requests.

    It is recommended to break down the hit rate across at least the following dimensions:

    • Interface or business scenario: Track customer service Q&A, code assistants, and retrieval-augmented generation (RAG) separately.
    • Prompt template version.
    • Prefix length tiers: For example, less than 1,000 tokens, 1,000 to 5,000 tokens, and greater than 5,000 tokens.
    • Time period and traffic: During off-peak hours, the interval between requests increases, which can lower the hit rate due to cache expiration.
    • Instances and routing: If the cache only exists within a single instance, load balancing may scatter requests from the same session across different instances.