LLM Inference Optimization: When Prefix Caching Is Slower Than Recomputing

    A shared prefix cache intended to accelerate long-context inference left median latency largely unchanged while pushing p99 latency from about 4 seconds to more than 17 seconds. This article examines the remote I/O, queueing, and parallel synchronization costs behind the regression, then explains how cost-aware cache selection, asynchronous retrieval, tiered fallback, and tail-latency testing can guide a better caching strategy.

    LLM Inference Optimization: When Prefix Caching Is Slower Than Recomputing

    In software engineering, adding a cache is almost a reflex: store a result once, reuse it later, and avoid repeating the work. That intuition holds in many systems. In large language model inference, however, it can backfire.

    An optimization effort for a very large mixture-of-experts (MoE) inference service illustrates the problem. The team introduced a shared cache to speed up long-context processing. Median latency barely changed, while tail latency deteriorated sharply.

    The lesson is straightforward but easy to overlook: reading cached data has a cost, and that cost is often underestimated.

    1. The Regression: Enabling Caching Increased Tail Latency

    The service ran a very large MoE model on nodes equipped with eight accelerators each. An MoE architecture routes inputs to a subset of specialized model components, or experts, allowing the total parameter count to grow substantially without a proportional increase in computation.

    To reduce time to first token for long-context requests, the team added a shared prefix cache. It stored attention intermediates computed for previous requests. When a new request shared a prefix with an earlier one, the system could reuse those intermediates instead of computing them again.

    The design looked compelling on paper. Production measurements told a different story:

    • Median latency: Almost no improvement.
    • p99 latency: Increased from approximately 4 seconds to more than 17 seconds.

    Because tail latency directly affects service-level agreement (SLA) performance, the team rolled back the feature before investigating the regression.

    Why had a cache designed to accelerate inference become a bottleneck?

    2. Understanding the Hardware and Workload

    2.1 The Attention State Was Compact

    The model used a low-rank compressed attention representation. Rather than retaining separate, full-sized key-value representations for every attention head, it compressed the persistent per-token information into a shared low-rank vector. This kept the storage footprint per token small and fixed.

    The system stored this state using low-precision quantization, packing every 256 tokens into a block. Each block occupied roughly a dozen megabytes, corresponding to a few tens of kilobytes per token.

    This footprint matters because caching is a trade-off between computation avoided and the cost of retrieving stored state. In this system, compact attention state narrowed the potential benefit of caching, making it especially important to compare retrieval time with measured recomputation time.

    2.2 Multi-GPU Synchronization Amplified Delays

    Long-context prefill is compute-intensive. The team used context parallelism, dividing a long input across multiple GPUs within a node. The GPUs exchanged intermediate results at each processing step so that each could access the context it needed.

    This introduced an important dependency: all eight compute units had to synchronize.

    If one GPU stalled while waiting for cached data, the other seven could be forced to wait as well. Cache retrieval latency therefore did not remain an isolated delay. Synchronization turned it into a system-wide slowdown, with the slowest participant determining progress.

    2.3 The Cache Had Two Tiers

    The cache architecture consisted of two layers:

    • L1 local cache: Stored in each inference engine’s own memory. Access was fast, but capacity was limited, and entries were not visible to other instances.
    • L2 shared cache: Stored in a separate remote key-value service. It offered greater capacity and could be accessed by all inference engines.

    The regression originated in the seemingly attractive L2 tier.

    3. Root Causes: Three Hidden Costs of Remote Caching

    3.1 A Serialized Access Bottleneck

    The shared cache service was a centralized component. During traffic spikes, multiple inference instances issued reads and writes simultaneously, and requests queued at the shared entry point.

    Local caches allowed instances to operate independently. The shared tier introduced a common bottleneck. As concurrency increased, so did the time spent waiting to access it.

    3.2 Network and Serialization Overhead

    Although an individual block occupied only roughly a dozen megabytes, a long-context request could involve hundreds or thousands of blocks.

    Retrieving those blocks from remote storage, deserializing them, and transferring them into GPU memory took time. In some workloads, the complete retrieval path was slower than recomputing the required state on the GPUs.

    A cache hit could therefore be slower than a miss—the literal meaning of “caching is slower than computing.”

    3.3 Synchronization Amplified Variability

    Context-parallel synchronization propagated cache-read variability across all participating GPUs. A slow remote read on one compute unit became a delay for the entire group.

    This explains why median latency remained almost unchanged while p99 deteriorated. Most requests either used the local cache or had sufficiently different prefixes that they missed the cache. A smaller group of requests that hit L2 absorbed the remote retrieval costs and their synchronization effects.

    The resulting slowdown was concentrated in the tail rather than spread evenly across requests.

    4. A Better Approach: Make Caching Cost-Aware

    The team’s redesign centered on four principles.

    4.1 Estimate the Benefit Before Using a Cache Hit

    A cache hit should not automatically trigger retrieval. The system first needs to estimate two costs:

    • Retrieval cost: Data size divided by measured bandwidth, plus expected queueing time, deserialization, and transfer to GPU memory.
    • Recomputation cost: Measured prefill time for the relevant number of tokens.

    The cache path should be selected only when retrieval is meaningfully faster than recomputation. Otherwise, the system should recompute.

    This decision can be lightweight: a lookup based on measured costs followed by a threshold comparison.

    1. def should_use_cache(tokens, est_read_ms):
    2. recompute_ms = tokens * cost_per_token # Calibrated from measurements
    3. # Leave a safety margin to avoid unstable borderline decisions
    4. return est_read_ms < recompute_ms * 0.7

    The safety margin helps avoid choosing the cache when its estimated advantage is too small to withstand normal latency variation.

    4.2 Overlap Asynchronous Retrieval with Computation

    The next principle is to remove remote cache retrieval from the critical path.

    When a request arrives, the system starts GPU recomputation immediately while fetching cached state asynchronously in the background. It uses whichever result becomes available first:

    • If the cached state arrives first, stop recomputation and use it.
    • If recomputation finishes first, discard the retrieved cache data.

    This approach hides retrieval latency behind computation rather than making progress depend on remote I/O. The synchronization barriers no longer need to wait solely for a cache read to complete.

    4.3 Use Tiered Fallback and Throttle Writes

    The cache hierarchy also needs clear priorities:

    • Prefer L1 local cache hits, using L2 as a fallback.
    • Rate-limit and coalesce L2 writes so that concurrent write traffic does not consume bandwidth needed for reads.
    • Prioritize frequently reused prefixes, such as system prompts and the beginnings of long documents, when retaining entries. Avoid persisting cold data.

    These measures focus shared-cache resources on data with a stronger chance of delivering useful reuse.

    4.4 Evaluate Tail Latency, Not Just Averages

    One of the most important lessons was about evaluation.

    Average and median latency can conceal bottlenecks that affect only a subset of requests. Any optimization involving shared resources should therefore treat p95 and p99 latency as core acceptance metrics.

    Testing must also reflect production traffic peaks. Low-volume offline replay is not enough to establish whether a centralized cache will behave well under contention.

    5. Broader Engineering Lessons

    Although this case involved LLM inference, its lessons apply to cache design more generally.

    1. Caching is not free. Network transfers, serialization, and queueing all contribute to retrieval cost. When recomputation is relatively inexpensive, the economics of caching must be reassessed.

    2. Shared resources create queues. A centralized component can become a serialization point under high concurrency. Capacity planning should account for peak demand, not just average load.

    3. Synchronization amplifies local delays. In tightly synchronized parallel systems, a small stall can slow the entire group. Tail latency is an essential indicator of this behavior.

    4. Use measurements to guide decisions. In cloud-native inference platforms, logging, monitoring, and alerting can provide visibility into cache hit rates, retrieval times, and queue lengths. Those measurements should inform each optimization decision.

    Caching is ultimately an exchange: storage and data movement in return for less computation. When computation becomes faster, stored state becomes more compact, or retrieval moves farther away, that exchange may no longer be worthwhile.

    Good system design does not assume that caching is always a win. It measures the full cost of reuse and chooses the faster path.