When Caching is Slower Than Compute: The Underestimated Cost of Cache Reads
Caching intermediate attention states during large language model inference is generally expected to reduce latency. However, in large-scale Mixture of Experts (MoE) models, remote cache reads can paradoxically slow down services by significantly amplifying tail latency (p99). This article explores why average metrics hide these read costs, how multi-GPU synchronization and centralized storage exacerbate the straggler effect, and how to diagnose and resolve these issues through conditional fetching, batching, asynchronous writes, sharding, and timeout mechanisms.
1. Background: Caching Should Save Time, So Why Does It Slow Down Services?
A team was running inference services on a massive Mixture of Experts (MoE) model. The MoE architecture allows different sub-networks to process different types of inputs, scaling up parameters with only a limited increase in compute. The model was deployed on a single node equipped with 8 high-end AI accelerators.
The bottleneck for long-context inference primarily lies in the prefill phase. To reduce redundant computation, the team added a shared cache layer to store previously computed intermediate attention results. When the prefix of a subsequent request matched or closely resembled a historical request, the system would read directly from the cache, skipping that portion of the computation.
The test results were unexpected. After enabling the cache, the median request latency barely changed, but the slowest 1% of requests (p99 latency) spiked from 3.96 seconds to 17.3 seconds. The team was ultimately forced to roll back the feature entirely.
The core issue is that reading from the cache takes time. This overhead is masked in average metrics but amplified in tail latency. Let’s break down this phenomenon, starting with the structure of the inference pipeline.
2. Understanding the Inference Chain: Why Cache Attention States?
2.1 Storage Format of Attention States
In autoregressive inference, each newly generated token requires the key-value (KV) information of all preceding tokens. This information typically consumes a large amount of GPU memory, leading to various compression schemes.
Multi-head Latent Attention (MLA) is one common approach. It compresses the KV information of each token into a shared, low-rank vector. The benefit is that regardless of the number of attention heads, the data volume required per token remains fixed and relatively small.
In this case, the system stored data in FP8 precision, packing every 256 tokens into a block. A single block was approximately 12.4MB, averaging about 48.4KB per token. With a fixed block size, the read and write unit for the cache is also fixed, making network transmission and management easier.
2.2 Synchronization Requirements from Context Parallelism
Prefill computation for long contexts is highly demanding, so the team also utilized Prefill Context Parallelism. This technique splits a long text into multiple chunks, distributing them across multiple GPUs for simultaneous processing. Once complete, the GPUs must exchange results over the network so that each card has the full context information.
Synchronization brings a direct consequence: the speed of the entire node is dictated by the slowest GPU. The 8 GPUs operate like a set of interlocking gears; if one card lags, the other 7 must wait. This is commonly known as the “barrel effect” or the straggler effect.
2.3 Layered Cache Architecture
The cache system is divided into two tiers:
- L1 Cache: Located in the local memory of each inference process. It offers the fastest access but has limited capacity and is only visible within that specific process.
- L2 Cache: Located in an independently deployed in-memory key-value store. It has a large capacity and can be shared across all inference instances within the same cluster.
The shared nature of the L2 layer is valuable because it allows different instances to reuse each other’s computation results. However, it also acts as a centralized resource where all read and write requests from all instances converge. This centralization is the root cause of the issues discussed below.
3. Phenomenon Analysis: Why Averages Mask Tail Latency Degradation
3.1 The Full Cost of a Single Cache Read
When many teams measure the benefits of caching, they only look at “how much compute time is saved on a hit.” In reality, a remote read involves at least the following steps:
- Query request queueing and key lookup;
- Network round trip (RTT);
- Data transfer;
- Deserialization and writing to GPU memory or RAM;
- If it’s a miss, you still pay the overhead of a futile query.
Take the 12.4MB block as an example. Assuming a network bandwidth of 10 Gbps and ignoring protocol overhead, the pure transfer takes about 10 milliseconds. If re-computing that block only takes a few milliseconds, then reading from the cache is actually slower than computing. This is a hypothetical example—actual values depend on hardware, network, and compute load—but the derivation applies to all scenarios.
3.2 Multi-GPU Synchronization Amplifies Tail Risk
Assume the probability of a single GPU exceeding the p99 latency threshold is 1%, and the GPUs are independent of each other. The probability that at least one GPU in an 8-GPU node becomes slow during a single request is:
1 − (1 − 0.01)^8 ≈ 7.7%
This means that even if a single GPU performs very stably, the probability of the entire request falling into the slow tail is nearly 8 times that of a single GPU. Cache reads increase the latency variance of each GPU, and these tail events are further amplified by 8-GPU synchronization. This is the primary reason why the median latency remained almost unchanged while p99 degraded significantly.
3.3 Queueing Effects in Shared Storage
The L2 layer has a single write endpoint, meaning all write requests from all instances queue up here. Under high system load, queueing wait time grows non-linearly with utilization. When utilization rises from 50% to 90%, the wait time increases by far more than double. This “queueing” during peak traffic is the source of tail latency.
4. Diagnostic Methods: Shifting from Averages to Percentiles and Segmented Timing
The key to pinpointing the problem is breaking down request latency into observable segments and tracking percentiles for each. Recommended practices include:
- A/B Toggle Testing: Enable and disable the cache under identical traffic loads, comparing p50, p95, and p99 metrics.
- Segmented Timing: Record the time taken for lookup, transfer, deserialization, computation, write-back, and synchronization waiting.
- Per-GPU Statistics: Identify the slowest GPU for each request and track its latency distribution.
- Hit Rate Tracking: Record the ratio of L1 hits, L2 hits, and misses, as well as the average benefit for each scenario.
An illustrative segmented timing code snippet:
import timefrom contextlib import contextmanagerstage_stats = {}@contextmanagerdef timed(stage):start = time.perf_counter()try:yieldfinally:cost_ms = (time.perf_counter() - start) * 1000stage_stats.setdefault(stage, []).append(cost_ms)def handle_block(key):with timed("l1_lookup"):block = l1_cache.get(key)if block is None:with timed("l2_fetch"):block = l2_cache.get(key)if block is None:with timed("recompute"):block = compute_block(key)return block
With this data, the team can answer a crucial question: Is the compute time saved by the cache greater than the read time it costs?
5. Root Cause Summary
Based on the comprehensive analysis, the problem can be categorized into four areas:
- Reads are not free. Hitting the cache still requires network transfer and deserialization, costs that can approach or even exceed those of recomputing.
- Synchronization amplifies the tail. During multi-GPU coordination, variance from a single read is amplified through synchronization points, increasing tail latency alongside GPU count.
- Centralized writes create bottlenecks. Multiple instances writing to the same storage endpoint simultaneously cause queueing times to spike during peak periods.
- Hidden overhead of misses. When similar requests are rare, numerous queries end up missing, yet they still incur the cost of querying and waiting.
These four points demonstrate that the benefit of caching cannot be judged solely by hit rate; the time saved on a hit must be greater than the cost of reading.
6. Optimization Strategies
6.1 Decide on Remote Cache Reads Based on Expected Benefit
The core principle: only access the remote cache when the expected benefit exceeds the expected cost. Expected benefit equals the hit probability multiplied by the recompute time. Expected cost includes the overhead of each query and the transfer overhead if hit.
def should_read_remote(hit_prob, recompute_ms, lookup_ms, fetch_ms, safety=1.2):expected_gain = hit_prob * recompute_msexpected_cost = lookup_ms + hit_prob * fetch_msreturn expected_gain > expected_cost * safety
Hit probability can be dynamically estimated based on the historical statistics of request prefixes. For prefixes with low hit rates, computing directly is often faster.
6.2 Prioritize Local Cache to Reduce Remote Access
L1 hits have virtually no network cost and should be the preferred path. By tuning local cache capacity, eviction policies, and pre-warming mechanisms, you can increase the L1 hit rate, thereby reducing the volume of requests hitting L2.
6.3 Batch Reads and Writes to Reduce Round Trips
Multiple blocks involved in the same request can be merged into a single batch read to minimize network round trips. Writes can similarly be batched. Note two things with batching: batches that are too large will increase single-request latency, so reasonable limits must be set.
6.4 Asynchronous Write-Backs Off the Critical Path
Writes following computation should not block the current request. Write-backs can be placed in a background queue, handled by a separate thread or coroutine. The queue needs an upper limit; when full, writes should be dropped directly, as losing a cache entry only affects the hit rate, not correctness.
6.5 Sharding to Reduce Single-Point Contention
The L2 layer can be sharded across multiple storage instances using prefix hashing, distributing the write load. After sharding, the queueing pressure on individual instances drops significantly. The sharding strategy must balance data distribution and request locality.
6.6 Set Read Timeouts and Fallback to Compute
Remote reads must have a time budget. Upon timeout, immediately fall back to recomputing, capping the slow tail within the budget.
import asyncioasync def load_block(key, budget_ms):try:return await asyncio.wait_for(l2_cache.get(key), timeout=budget_ms / 1000)except asyncio.TimeoutError:return None # Caller falls back to recompute upon receiving None
The budget value can be set to a proportion of the compute time, such as half. Timeout rates must be monitored; a consistently high rate indicates that the storage layer is overloaded.
6.7 Trade-offs in Block Size
Larger blocks mean higher data volumes per read/write and better transfer efficiency, but coarser granularity reduces the utilization of partial hits. Smaller blocks offer better flexibility but increase metadata and request counts. Block size should be determined based on the actual distribution of hit lengths.
7. Validation and Rollout Strategy
After optimization, validation should focus on the following metrics:
- Hit rate: Tracked separately for L1 and L2.
- Time saved: Total compute time saved during hits.
- Read cost: Percentiles for query, transfer, and deserialization times.
- Tail latency: p50, p95, p99, and the distribution of the slowest GPU per request.
- Queue depth and timeout rate: Reflects the load status of the L2 layer.
For rollout, a canary deployment is recommended. First, compare the percentile curves with the cache on and off under a small fraction of traffic. Only gradually expand the rollout when p99 does not degrade and there is a measurable improvement in throughput or average latency. If p99 degrades, adjust the expected benefit threshold or timeout budget first, rather than abandoning the entire caching strategy outright.
8. Reusable Engineering Lessons
- Cache benefits should be measured by “saved compute time minus read cost,” not just by hit rate.
- Performance evaluation should prioritize percentiles; averages mask tail issues.
- In multi-GPU synchronization scenarios, minor variances on a single GPU are amplified and must be observed on a per-GPU basis.
- Centralized shared storage is a potential bottleneck; writes should be asynchronous and sharding considered.
- Every remote access should have a timeout and fallback path to ensure the slow tail remains controllable.
- The ultimate goal of caching is to reduce overall latency, not to increase the hit rate itself.
