Why Caching Can Be Slower Than Computing: A Deep Dive into LLM Inference Performance Optimization
In traditional software engineering, trading space for time is a golden rule, but in large-scale MoE-based LLM inference, enabling a shared cache can actually multiply tail latency. This article explains why cache reads in GPU inference carry hidden costs—HBM bandwidth walls, index lock contention, and eviction overhead—that can exceed the cost of recomputation, and presents a restructured caching design based on asynchronous prefetching with double buffering, lock-free indexing, and adaptive cache granularity. It also covers how to build end-to-end monitoring with Baidu AI Cloud to correlate p99 latency with cache I/O, demonstrating that effective caching requires deep understanding of hardware bandwidth limits and concurrency mechanisms rather than blindly applying conventional wisdom.
Why Caching Can Be Slower Than Computing: A Deep Dive into LLM Inference Performance Optimization
In traditional software engineering, “trading space for time” is a golden rule. To make systems run faster, we habitually store intermediate computation results in a cache, expecting to reuse them directly when similar requests arrive. However, in LLM inference scenarios built on ultra-large Mixture-of-Experts (MoE) models, this common wisdom is being overturned: introducing a cache not only fails to deliver meaningful speedups, but actually causes tail latency to spike severalfold. This article reconstructs how this phenomenon emerged and explores how to re-engineer the caching mechanism at the architectural level.
1. Caching Logic and Background in LLM Inference
To understand why caching can become a “performance killer,” we first need to review the underlying architecture and attention mechanisms of modern large models. Cutting-edge ultra-large models generally adopt the Mixture-of-Experts architecture. By dividing the model into multiple “expert” sub-networks and activating only a subset of them per inference pass, MoE dramatically expands the parameter count without proportionally increasing compute.
When processing long context, attention computation is extremely expensive. To reduce this cost, the industry proposed a multi-head latent attention technique based on low-rank compression. It compresses the key-value information of each token into a shared low-rank vector. A notable advantage of this design is that, regardless of how many attention heads the model has, the amount of intermediate data stored per token is fixed and very small.
In a typical FP8-precision setup, the system usually packs 256 tokens into a single “block.” After compression, a block of 256 tokens takes only about 12.4MB of storage—roughly 48.4KB per token. On the surface, such a small data footprint looks ideal for large-scale caching. So when a team deployed this MoE model on nodes composed of multiple mainstream high-performance accelerator cards, they naturally added a shared cache layer to store previously computed attention data.
2. The Pain Point: Counterintuitive Performance Degradation
Once the carefully designed shared cache was enabled, the engineers were met with startling monitoring data: median latency barely changed, but p99 latency—the metric representing tail performance—jumped from 3.96 seconds to 17.3 seconds, a nearly 4x regression. Faced with such a severe degradation, the team had to roll back the feature entirely.
Why does reusing data take longer than recomputing it from scratch? The core conclusion of this widely discussed study is: cache reads themselves carry extremely high hidden costs, and under high-concurrency LLM inference, these costs are severely underestimated.
3. Deep Analysis: Breaking Down the Hidden Costs of Cache Reads
The time consumed by a cache read is not simply “data size / bandwidth.” In GPU inference scenarios, the hidden costs manifest in several dimensions:
1. The HBM Bandwidth Wall and Data Movement Overhead
GPU compute units (such as Tensor Cores) are extremely fast, but HBM bandwidth is finite. When a cache miss or partial hit occurs, the system must move large KV cache blocks from host memory or remote storage into GPU memory. This involves PCIe transfers or network I/O, whose latency far exceeds that of on-chip tensor computation. In extreme cases, the time spent moving a 12.4MB block is already enough for the GPU to recompute that token’s attention multiple times.
2. Cache Indexing and Lock Contention
In a multi-GPU, high-concurrency environment, a shared cache layer must maintain a global hash table or index tree. Every cache lookup requires hashing, comparison, and potentially lock acquisition. As cache capacity and concurrent request volume grow, thread blocking caused by lock contention deteriorates sharply—directly driving up p99 tail latency.
3. Fragmentation and Eviction Overhead
With eviction policies such as LRU (Least Recently Used), the system must constantly update linked-list pointers and may even trigger memory allocation and deallocation. Under extreme concurrency, frequent cache breakdowns and evictions can push the system into a “thrashing” state, where substantial compute resources are wasted on cache management.
4. The Fix: Turning the Cache into a True Accelerator
Having identified the root causes, the team deeply re-engineered the underperforming cache system. The core idea: eliminate read/write blocking and overlap cache I/O with GPU computation asynchronously.
1. Asynchronous Prefetching and Double Buffering
Instead of the synchronous pattern of “request arrives -> query cache -> block waiting for data -> execute computation,” the re-engineered system introduces a double-buffering mechanism. When the inference engine predicts that upcoming computation may need certain KV cache blocks, it asynchronously issues I/O requests to prefetch them into a standby buffer in GPU memory. By the time computation actually begins, the data is already in place, completely hiding the I/O wait time.
# Pseudocode example: async prefetch overlapped with computationasync def infer_with_cache(request):# 1. Asynchronously prefetch the required KV cache blocksprefetch_task = asyncio.create_task(load_cache_to_gpu(request.token_ids))# 2. Synchronously run pre-computation that doesn't need the cache (e.g., embeddings)embedding_output = compute_embeddings(request)# 3. Await the prefetch; the pre-computation has overlapped with I/Ocached_kv = await prefetch_task# 4. Run the attention computationreturn attention_compute(embedding_output, cached_kv)
2. Lock-Free Index Design
To address lock contention in concurrent lookups, the system switched to a lock-free hash table design. Atomic operations are used to update cache state, avoiding the thread-suspension overhead of traditional mutexes. Additionally, by sharding the cache index across different GPU stream processors, concurrent throughput is greatly improved.
3. Dynamically Adaptive Cache Granularity
Rather than sticking to a fixed 256-token block size, the system dynamically adjusts cache granularity based on current HBM bandwidth utilization and compute load. When bandwidth is idle, it uses large blocks to reduce the number of index lookups; when bandwidth is tight, it degrades to small blocks or even disables caching entirely and recomputes directly, keeping overall latency stable.
5. Building a Performance Monitoring System with Cloud-Native Capabilities
When optimizing low-level inference performance like this, solid observability is indispensable. With Baidu AI Cloud’s container platform and logging services, development teams can build an end-to-end monitoring system. By streaming internal inference engine events—such as cache hit rate, prefetch duration, and HBM bandwidth utilization—to the monitoring and alerting system in real time, engineers can clearly visualize the correlation curve between p99 latency and cache I/O wait time.
This cloud-native-grade monitoring not only enables rapid root-cause localization when problems occur, but also allows engineers to use stress-test data in subsequent iterations to visually verify the actual effectiveness of optimizations such as double buffering.
6. Conclusion
“Caching being slower than computing” is not sensationalism—it is a real-world reflection of the tug-of-war between compute power and memory-bandwidth bottlenecks in the era of large models. As MoE models and long-context processing become increasingly common, simply applying the traditional “just add a cache” mindset no longer works. We must deeply understand underlying hardware bandwidth limits and concurrency synchronization mechanisms, and apply system-level transformations such as asynchrony and lock-free design, before caching can truly deliver the value of “trading space for time.” This is also a reminder to all developers: any performance optimization must be grounded in detailed monitoring data—be wary of hidden costs masked by intuition.
