When Caching Is Slower Than Computing: The Tail Latency Trap in LLM Inference
Caching repeated computation seems like a sure win, but in large language model inference it can quietly devastate tail latency while leaving the median untouched. This article walks through a real-world case where adding a shared KV cache pushed p99 latency from 3.96 seconds to 17.3 seconds, explains the hidden costs of caching—lookup overhead, data movement, lock contention, and eviction churn—and shows why tail requests suffer first. It also provides a practical diagnostic method for breaking latency down by percentile and stage, along with optimization strategies and rollout guidance for shipping caching features safely.
1. Background
Online inference services typically describe latency using multiple percentiles. The median (p50) reflects the typical request experience, while p99 reflects the slowest 1% of requests. The two mean very different things. For user-facing services, tail requests often determine timeout rates, retry volume, and user churn, making tail latency a core metric for capacity planning and stability assessment.
Large language models frequently adopt a Mixture-of-Experts (MoE) architecture. This structure lets different sub-networks of the model handle different types of computation, expanding parameter scale without significantly increasing per-inference compute. During deployment, the model is sharded across multiple accelerators within a node, relying on high-speed interconnects for coordinated computation. Under this setup, every step of computation depends on synchronization across multiple devices—if any one component slows down, the overall response suffers.
2. Case Study: Same Mean, Exploding Tail
A team added a shared cache to the inference service of an ultra-large MoE model. The cache stored previously computed attention intermediates—KV cache. The design was straightforward: when similar long-text requests appeared, the system could reuse historical results and skip redundant computation.
Post-launch results diverged from expectations. Median latency barely changed, but p99 latency rose from 3.96 seconds to 17.3 seconds—a more than fourfold increase. The team ultimately rolled the feature back entirely.
This case shows that the same optimization can perform in opposite ways at different percentiles. Looking only at averages or medians makes it hard to detect tail degradation. When evaluating cache benefits, teams need to monitor percentiles, hit rates, and per-stage timings simultaneously.
3. The Benefits and Costs of Shared Caching
The benefit of caching comes from avoiding redundant computation. For long-context requests, attention computation cost grows with sequence length. On a cache hit, the system can skip large chunks of computation and read existing results directly—savings that are often substantial.
But caching has its own costs, including:
- Lookup overhead: Every request must compute a cache key, query the index, and determine whether it hits. Even a single lookup taking tens of microseconds adds up under high concurrency.
- Data movement: If cached data resides in remote memory or on other nodes, reads traverse the network. Network latency and bandwidth fluctuations show up directly in request duration, and these fluctuations are often random.
- Serialization and deserialization: Cross-process or cross-node transfers require format conversion. This consumes CPU time and may queue up under heavy load.
- Locks and contention: Concurrent reads and writes to shared structures require locking for consistency. Lock waits get amplified in high-concurrency scenarios and cluster during peak periods.
- Miss path: On a miss, the request pays the lookup cost and then performs the full computation anyway. This is pure overhead with no benefit.
- Eviction and thrashing: Cache capacity is finite; once full, new data evicts old data. Unstable access patterns cause frequent swap-in and swap-out, degrading hit rates while the system pays for wasted writes.
Each of these costs is small in isolation, but they stack up on specific requests—which is precisely why the tail suffers most.
4. Why Tail Latency Degrades First
A simplified model illustrates this. Assume per-request latency is:
T = T_lookup + (1 − h) × T_compute + h × T_fetch
where T_lookup is lookup overhead, T_compute is full computation time, h is hit rate, and T_fetch is the time to read cached data. This model ignores queuing and concurrency; it is only meant to show the mechanism.
Around the median, most requests have a high h, and T_fetch is far smaller than T_compute, so caching delivers clear benefits and the median is largely unaffected. In the tail, the situation reverses. Slow requests tend to be new content or extremely long texts with low h—the system pays lookup costs without earning enough reuse benefit. Meanwhile, T_lookup and T_fetch themselves fluctuate, and any jitter landing on a tail request directly stretches p99.
Beyond this model, three effects amplify the tail problem.
Synchronized waiting amplifies the tail. In multi-device parallelism, every layer of computation must wait for all participants to finish. If one device is waiting on cached data, the entire step waits. This is the well-known weakest-link effect: total time is determined by the slowest branch. The more random waits caching introduces, the more likely the slowest branch lands in the tail.
Long requests crowd out cache space. Long requests write large volumes of data and easily trigger evictions, pushing out prefix cache entries that other requests are actively using. Evicted requests turn into misses, their latency spikes, and a chain reaction follows.
Queuing effects amplify non-linearly. When a cache operation slows down, subsequent requests wait in the queue. As system utilization approaches capacity, wait time grows far faster than load. This non-linear relationship makes tail latency acutely sensitive to even small performance regressions.
5. Diagnosis: Break Down by Percentile and Stage
The core of diagnosis is splitting latency into stages and tracking hit rates separately at different percentiles. Recommended steps:
- Run the same traffic with caching on and off. Replay real traffic to ensure both groups share the same request distribution, then compare p50, p95, and p99.
- Record per-stage timings and hit status for every request. Include lookup, data read, computation, and total duration.
- Measure hit rates for tail requests specifically. Global hit rates alone can be misleading; compute the hit rate within slow requests separately.
- Examine stage breakdowns of slow requests. If p99 requests spend most of their time in lookup or read stages, the problem lies in the cache path itself; if the time is mostly in computation, the problem may stem from queuing or resource contention.
Here is an illustrative script for computing percentiles and tail hit rates:
import statisticsfrom dataclasses import dataclass@dataclassclass RequestTrace:lookup_ms: floatfetch_ms: floatcompute_ms: floathit: bool@propertydef total_ms(self) -> float:return self.lookup_ms + self.fetch_ms + self.compute_msdef percentile_report(traces: list[RequestTrace]) -> dict:totals = [t.total_ms for t in traces]cuts = statistics.quantiles(totals, n=100) # 99 percentile pointshit_rate = sum(t.hit for t in traces) / len(traces)return {"p50": cuts[49], "p99": cuts[98], "hit_rate": hit_rate}def tail_hit_rate(traces: list[RequestTrace], threshold_ms: float) -> float | None:tail = [t for t in traces if t.total_ms >= threshold_ms]if not tail:return Nonereturn sum(t.hit for t in tail) / len(tail)
With the data in hand, focus on two questions: after enabling the cache, is the hit rate for p99 requests notably lower than the overall rate? And do lookup and read stages account for an abnormally high share of time in p99 requests? The answers directly point to the root cause.
6. Optimization Directions
Once diagnosis is clear, start from the following directions.
- Admission control. Enable caching only for sufficiently long prefixes. Short requests involve little computation, so lookup cost may exceed the compute saved—routing them through the normal path is more sensible.
- Set time budgets with fallback. Cache lookups must have a timeout cap. On timeout, recompute directly, treating the cache as an optional accelerator rather than a hard dependency on the critical path.
def get_or_compute(cache, key, budget_ms, compute_fn):block = cache.try_get(key, timeout_ms=budget_ms) # returns None on timeoutif block is not None:return block, "hit"return compute_fn(), "miss"
This code is illustrative. In a real implementation, ensure the fallback path is thoroughly tested, and set timeout budgets based on tail latency targets rather than gut feel.
- Local-first design. Keep cached data on the same node as the computation whenever possible, reducing network jitter from cross-node transfers.
- Tiered capacity and eviction policy. Partition cache space by request popularity and length, preventing a single long request from occupying global capacity. Eviction policies should consider access frequency, not just write time.
- Asynchronous writes and prefetching. Move cache writes and prefetching to the background so they never block the main request path. This prevents write operations from slowing online requests.
- Make tail latency a release gate. Throughput and average latency cannot represent the overall user experience. Every change should be checked against p99 with an explicit degradation threshold.
7. Rollout and Rollback Recommendations
The risk with caching features is that their benefits and costs fall on different requests—averages mask the damage. Roll out with strict percentile monitoring, keep rollback ready, and treat p99 regression as an immediate rollback trigger.
