LLM Inference Cost and Cache Hit Rate: A Practical Guide

    This article explains how to control large language model inference costs by improving KV cache hit rates. It covers why caching is the primary cost lever, the three rules that determine whether a prefix hits, structured techniques such as prefix normalization and session stickiness, scheduling and batching trade-offs between throughput and latency, how to diagnose performance drift, and the observability metrics and capacity planning practices needed to hold SLAs under traffic peaks. A deployment checklist is included.

    1. Background: Capability Limits vs. Cost Limits

    A model’s capability ceiling is set by the model itself. What actually determines user experience and commercial viability is cost per request, tail latency, and stability. Once call volume grows from thousands per day to hundreds of millions, inference is no longer “a process plus a port” but a distributed system spanning nodes and racks. Operator implementations, collective communication, request scheduling, and cache management are tightly coupled, so jitter in any one of them is amplified along the call chain into end-to-end metrics.

    Performance work therefore cannot stop at “posting a benchmark score.” It has to be grounded in concrete deployment conditions: which accelerator chips are used, what interconnect bandwidth exists within and across machines, how context lengths are distributed, and when concurrency peaks occur. Optimization advice that ignores deployment conditions usually produces results nobody can reproduce.

    2. KV Cache: The First Lever on Cost

    Autoregressive decoding needs the key and value tensors of every previously generated token. Without caching, complexity grows quadratically with sequence length; with caching, the computation for repeated prefixes is eliminated entirely.

    Hit rate is not a mystery but a measurable engineering metric. Three rules dominate:

    1. A hit requires an exact prefix match. The cache is keyed on the token sequence prefix, so a single differing character invalidates the whole segment.
    2. The time window determines survival. Cache entries are constrained by capacity and eviction policy; shorter gaps between requests make hits more likely.
    3. Length and concurrency drive eviction. Long contexts consume more GPU memory, and high concurrency accelerates eviction.

    The hit decision can be abstracted as:

    1. def lookup(prefix_tokens, cache, ttl):
    2. entry = cache.get(prefix_tokens)
    3. if entry is None or now() - entry.ts > ttl:
    4. return None # miss, full prefill required
    5. return entry.kv # hit, skip prefix computation

    In practice, you can repeat requests with the same prefix at fixed intervals and plot how the hit rate decays over time, which reveals whether the capacity configuration is reasonable.

    3. Structured Ways to Raise the Hit Rate

    • Prefix normalization: put the system prompt, tool descriptions, and few-shot examples first and keep them byte-stable; move volatile fields (timestamps, session IDs) to the end.
    • Session stickiness: route the same session to the same replica to avoid repeated prefill across instances.
    • Tiered caching: keep hot data in GPU memory, with host memory and local storage as a second tier, plus asynchronous swap-in and swap-out.
    • Structured output constraints: a stable output template reduces wasted recomputation and retries.

    4. Scheduling and Batching: Balancing Throughput and Latency

    Continuous batching lets long and short requests run together and improves GPU utilization significantly, but it introduces head-of-line blocking. Workable strategies include grouping requests by prefix to maximize reuse, giving long requests a separate quota, rate limiting on a token budget rather than request count, and degrading gracefully when requests time out.

    5. Performance Drift: From Symptom to Root Cause

    When the same model behaves differently at different times, the usual causes are accumulated quantization error, distribution shift in positional encoding when attention extrapolates to long contexts, and numerical path differences caused by changes in batch composition. To localize the issue, align inputs, fix randomness, and bucket output distributions, turning a vague “it feels dumber” into a comparable metric shift.

    6. Observability and Capacity Planning

    Metrics that must be collected: cache hit rate, share of time spent in prefill vs. decode, queueing time, eviction count, and cost per thousand tokens. Feeding these into a unified logging service and a monitoring and alerting system, combined with elastic scaling from the container platform, is what keeps SLAs intact during traffic peaks. In these scenarios, Baidu AI Cloud typically offers a general combination of capabilities spanning container platforms and monitoring and alerting, which makes it easier for teams to build a closed loop of their own.

    7. Implementation Checklist

    1. Define a baseline of deployment conditions and lock down the load-test scripts; 2. Establish a prefix convention and a cache capacity model; 3. Ship hit-rate and drift dashboards; 4. Validate every optimization with canary comparisons; 5. Make cost metrics part of the release gate.