Reducing LLM API Costs: Cache Hits and Prefix Design

    This article explores strategies for reducing Large Language Model (LLM) API costs through effective KV Cache utilization and prompt prefix design. It covers the fundamentals of KV Cache, VRAM estimation, the mechanics of prefix caching, a practical implementation checklist, context management for long conversations, and considerations for self-hosted inference. Developers will learn how to optimize requests, monitor key metrics, and build a predictable cost structure regardless of vendor pricing changes.

    1. Verify the Scope of Price Reductions

    Recently, some model API providers announced price reductions for input cache hits, often accompanied by limited-time promotions. Specific pricing, applicable models, cache hit conditions, and promotion expiration dates should always be verified against official announcements before calculating costs. Since prices are subject to change, budget margins should be maintained rather than relying solely on promotional rates.

    2. What is KV Cache

    During autoregressive generation, every time the model outputs a new token, it must compute attention against all preceding tokens. If historical Keys and Values were recalculated at every step, the computational overhead would grow rapidly with sequence length. To optimize this, inference systems store the computed Keys and Values for each layer in what is known as the KV Cache. This trades VRAM for compute: memory usage increases, but redundant calculations are eliminated.

    3. How to Estimate VRAM Usage

    A common estimation formula is as follows:

    1. kv_cache_bytes = 2 * batch_size * seq_len * num_layers * num_kv_heads * head_dim * dtype_bytes

    The meaning of each variable:

    • The coefficient 2 represents storing both Key and Value.
    • As seq_len increases, memory usage grows linearly.
    • num_kv_heads is the number of KV heads. In standard Multi-Head Attention (MHA), this equals the number of attention heads. Grouped-Query Attention (GQA) and Multi-Query Attention (MQA) reduce the number of KV heads, which is the primary architectural method for reducing KV Cache size.
    • dtype_bytes depends on precision: FP16 and BF16 use 2 bytes, while INT8 uses 1 byte.
    • This formula excludes model weights, activations, framework overhead, and memory fragmentation. Actual deployments require reserving more space.

    Many references write the formula using hidden_dim. In standard MHA, num_kv_heads × head_dim equals hidden_dim, so both yield the same result. However, in GQA or MQA, they are no longer equal, and the number of KV heads should be used instead.

    Here is a hypothetical example, not based on a specific real model: Assume a model has 32 layers, 8 KV heads, a head_dim of 128, uses FP16, with a batch_size of 1 and a seq_len of 128K (131072). Plugging into the formula:

    2 × 1 × 131072 × 32 × 8 × 128 × 2 bytes ≈ 17.2 GB (approx. 16 GiB).

    If INT8 is used to store the KV Cache, the footprint is halved to about 8 GiB. If the model used standard MHA with 32 KV heads, the footprint would quadruple to about 64 GiB. This shows that model architecture and precision impact VRAM more directly than mere context length.

    4. Why Cache Hits Rely on Prefixes

    Most server-side prefix caches match tokens from the very beginning. Only the exact identical starting portion can be reused; as soon as a single character differs midway, all subsequent caches miss. Therefore, system prompts, role definitions, and fixed knowledge bases should be placed at the very beginning, while dynamic content like user queries should be appended at the end.

    A common mistake is inserting timestamps, request IDs, or usernames into the system prompt. Since these change every time, the prefix shifts, and cache misses are almost guaranteed.

    Different vendors also have varying cache rules, such as granularity (fixed-length chunks vs. entire requests), minimum hit length, Time-To-Live (TTL), and discount mechanisms. These details must be confirmed via official documentation and should not be inferred from one vendor to another.

    5. Executable Practice Checklist

    1. Static Prefixes: Place unchanging instructions, examples, and knowledge bases at the start of the message. Avoid inserting timestamps, random IDs, or user identifiers.
    2. Dynamic Content Suffixing: Place variable content like user questions and retrieved snippets at the end.
    3. Similar Prefix Routing: If self-hosting inference, hash by prefix to schedule requests with shared prefixes to the same instance, improving local cache hit rates.
    4. Cache Key Design: When building your own cache, the cache key should include the model name, version, tokenizer version, and system prompt version. Old caches should not be read after a model upgrade.
    5. Monitoring Metrics: Track cache hit rate, Time To First Token (TTFT), per-token latency, VRAM utilization, and actual cost per 1,000 requests.
    6. Cost Stress Testing: Use real traffic samples to calculate hit rates and estimate costs accordingly. Looking only at unit prices can lead to overestimating or underestimating actual spend.

    6. Context Management for Long Conversations

    Long conversations do not require concatenating the entire history in every turn. One approach is to use summaries to retain established conclusions and constraints, while preserving the raw conversation for auditing purposes.

    Summaries lose details, especially numbers, dates, names, and proper nouns. After generating a summary, verify that key entities match the original text. Additionally, if the summary changes every turn, it breaks prefix stability, requiring a trade-off between context completeness and cache hits.

    7. Considerations for Self-Hosted Inference Services

    When deploying privately or self-hosting in the cloud, you can use container management alongside GPU virtualization and partitioning technologies to achieve multi-model co-location. Concurrently, configure logging services and monitoring alerts to detect latency spikes or insufficient VRAM promptly.

    During multi-model co-location, models compete for VRAM. Set VRAM limits and priorities for each model. KV Cache quantization reduces VRAM usage but may impact output quality. It requires validation using a fixed evaluation dataset, rather than just looking at memory numbers.

    8. Risks and Boundaries

    • API prices and cache rules can change at any time, and limited-time promotions may expire. Set budget alerts and prepare fallback plans, such as switching to alternative models or reducing context length.
    • Cache hits primarily reduce the cost of input tokens. Output tokens generally do not receive the same discounts and must be calculated separately.
    • Prices across different vendors cannot be compared directly. Billing units, model capabilities, and cache rules vary.
    • This article does not provide actual compression ratios for any specific models. If specific numbers are needed, measure them on your own models and workloads.

    Conclusion

    API price reductions represent a real cost opportunity, but pricing is dictated by vendors and is not guaranteed by technical laws. What developers can control is prefix design, request routing, and the monitoring system. By mastering these, system costs remain predictable and controllable even if prices fluctuate.