When Caching Slows Down LLM Inference: Why P99 Latency Spikes

    This article explains why adding a shared cache can make large language model inference slower instead of faster, using a real-world case where P99 latency jumped from about 3.96 seconds to 17.3 seconds on a single-node MoE deployment. It breaks the problem down across four dimensions—GPU memory, scheduling, parallelism, and consistency—and shows how cache lookup, data movement, MoE routing, and eviction can enter the critical path and amplify tail latency. You will learn a four-question admission check for deciding whether a cache is worth adding, plus engineering practices such as decoupling caching from scheduling, layered cache domains, capacity and fragmentation control, observability, and staged rollout with one-click rollback.

    1. The Counterintuitive Part: Caching Is Not Always Faster

    In performance engineering, caching is often treated as a free speedup: store a computed result, fetch it next time, and skip the repeated work. In large language model (LLM) inference serving, this assumption is repeatedly overturned by reality.

    Consider a team serving online inference for a very large Mixture of Experts (MoE) model, deployed on a single node with 8 high-performance accelerators. To speed up long-context processing, they added a shared cache layer that stored previously computed attention-related states, hoping to reuse them for similar requests. The result was unexpected: median latency barely moved, while the slowest 1% of requests (P99 latency) degraded from about 3.96 seconds to 17.3 seconds. The team eventually rolled the whole thing back.

    This is not an isolated case. It is a typical trap in LLM inference optimization: the optimization itself enters the critical path and amplifies tail latency. To understand it, you have to break “cache” from an abstract noun into four concrete chains: GPU memory, scheduling, parallelism, and consistency.

    2. Why Shared Caching Tends to Fail in MoE Inference

    1. GPU Memory Is Zero-Sum: Cache and KV Compete for the Same Space

    GPU memory in autoregressive inference is mainly occupied by three things: model weights, runtime activations, and the key-value cache (KV Cache) that grows token by token. If a shared cache stays resident in GPU memory, it directly shrinks the space available for concurrency, reducing how many requests can be processed at once and lengthening queues. A subtler issue is fragmentation: cache blocks of varying sizes and mismatched lifetimes push the memory allocator into frequent compaction, further raising allocation latency.

    A schematic capacity calculation looks like this (illustrative logic only, not a concrete API):

    1. Available GPU memory ≈ Total memory - weights - peak activations - fragmentation reserve
    2. Concurrent requests ≈ Available GPU memory / peak KV per request
    3. Compute savings from higher hit rate < queueing loss from lower concurrency => net negative

    2. Hit Detection and Data Movement Take Time

    A shared cache has to answer three questions: what to use as the key, how fast hit detection is, and how to move data on a hit. If the key is too coarse, the hit rate looks inflated but reuse is wrong; if the key is too fine (for example, including prefix, position ranges, and routing results), the cost of computing the key and looking it up rises quickly. After a hit, the state still has to be copied into the current request’s memory location, and that copy time is tightly coupled to memory bandwidth—never cheap in long-context scenarios.

    3. MoE Routing Means “Similar Requests” Are Not Actually Similar

    The core of MoE is routing: different tokens in the same layer may be dispatched to different experts. Even if two requests share the same text prefix, routing jitter and different in-batch combinations can lead to significantly different sets of experts actually doing the computation. This means the boundary of “reusable attention state” is blurry; forcing reuse either yields limited benefit or introduces correctness and consistency risks.

    4. Batching Schedules Get Interrupted by Cache Operations

    High-throughput inference relies on continuous batching: requests join as they arrive and leave as they finish. If cache lookup, insertion, and eviction run in the same critical section as scheduling, they create head-of-line blocking. A single large cache compaction operation is enough to make an entire batch wait—this is the typical mechanism behind P99 jumping from around 4 seconds to around 17 seconds: the median stays flat while the tail explodes.

    5. Eviction Policies Conflict with Concurrent Writes

    A shared cache typically faces a reality of “write-heavy, read-light, short-lived.” A global least-recently-used policy can be flushed by a burst of hot requests; a segmented policy requires extra metadata maintenance. Lock contention, version invalidation, and rollbacks during concurrent writes all turn occasional jitter into a long tail.

    3. Decide First, Optimize Second: Four Admission Questions for Caching

    Before writing any cache code, run these four admission questions. They filter out most “negative-return optimizations”:

    1. Critical path check: Does this optimization sit on a mandatory path for the request? If so, evaluate its worst-case cost, not its average cost.
    2. Upper-bound check: Theoretical maximum savings = hit rate × cost per computation. If the upper bound is limited, the added complexity is not worth it.
    3. Resource contention check: Are the memory and bandwidth the cache consumes competing with concurrency? Do a capacity calculation instead of guessing.
    4. Tail latency check: What is the impact on P99/P999? Provide a rollback switch and a staged rollout plan.

    4. Engineering Practices for Doing Caching Right

    1. Decouple from Scheduling and Move It Off the Critical Path

    Make cache lookup and population asynchronous and discardable: on a hit, accelerate; on a miss or during compaction, fall back to the original path and never block the main flow. The key principle is that a cache must never be a reason for a request to fail or wait.

    1. if cache_ready and hit:
    2. reuse() # fast path
    3. else:
    4. compute() # fallback path, guaranteed not to slow things down

    2. Layer and Partition to Avoid Global Contention

    Split the cache into layers such as “prefix reuse,” “session-level reuse,” and “cross-request sharing,” and give each layer its own capacity and eviction policy. The cross-request sharing layer is the most sensitive and should be off by default or strictly rate-limited; session-level reuse has more predictable benefits and can be enabled first.

    3. Capacity Governance and Fragmentation Control

    Manage cache entries with fixed block sizes and pre-allocated pools to reduce fragmentation and allocation jitter; set a hard limit and watermark for the cache, and reject new writes once the watermark is exceeded rather than slowing down reads.

    4. Observability First

    No measurement, no optimization. At minimum, collect hit rate, hit data-movement time, cache compaction time, queueing time caused by the cache, and a P50/P95/P99 breakdown. Only by treating “cache overhead” as a first-class metric can you tell whether it is an asset or a liability.

    5. Staged Rollout and One-Click Rollback

    Any cache capability should support percentage-based rollout, per-tenant switches, and second-level rollback. Validate tail latency with shadow traffic before launch, not just averages.

    5. A General Capability Mix for Cloud Deployment

    If you run this kind of inference service on a cloud platform, you can build a closed loop with general-purpose capability categories: use a container platform to host elastically scaling inference instances; use object storage to keep versioned files for models and intermediate artifacts; use a message queue for request peak shaving and asynchronous processing; and use logging and monitoring/alerting to accumulate hit-rate and tail-latency metrics. Baidu AI Cloud offers corresponding capabilities in these general categories, which can support the full engineering chain from staged rollout to observability and rollback, but the specific selection should still be based on capacity calculations and load testing against your own workload characteristics.

    6. Conclusion: The First Principle of Optimization

    “Caching can be slower than computing” reminds us that any optimization must be examined under the dual constraints of the critical path and tail latency. In LLM inference, GPU memory is a scarce resource, scheduling is the lifeline of throughput, and MoE routing makes reuse boundaries inherently blurry. Do the admission check first, then talk about implementation; build observability first, then talk about tuning; guarantee rollback first, then talk about scaling out. Put optimizations where they do not enter the critical path, do not compete with concurrency, and do not amplify the long tail—that is sustainable performance engineering.