Breaking the Memory Wall in LLM Inference: KV Cache, Bandwidth, and Scheduling

    As compute is no longer the only bottleneck in LLM inference, this article breaks down the three-layer memory wall—linear KV cache growth, memory bandwidth limits during decoding, and fragmentation from allocation and scheduling—and walks through four general engineering approaches: paged KV cache management, compression and quantization, tiered storage with offloading, and dual-path scheduling with parallelism, plus the baseline metrics to measure progress.

    1. Background: Compute Is No Longer the Only Bottleneck

    For the past two years, discussions of LLM performance have almost defaulted to “the bottleneck is compute.” In real inference serving, however, a pattern keeps showing up: the GPU utilization curve does not look good, yet memory is the first thing to fill up, forcing the service to throttle requests. This is the so-called inference memory wall—what limits system capacity is not floating-point throughput, but memory capacity and memory bandwidth.

    Understanding this is the prerequisite for every optimization that follows. The memory access pattern of the inference stage (especially autoregressive decoding) is completely different from training: for every token generated, the model weights and the historical context cache must be read again, which means low computational intensity and a huge volume of memory traffic. As the context grows longer and concurrency increases, the system quickly shifts from compute-bound to bound by memory access and capacity.

    2. Root Causes: The Memory Wall Stacks Three Problems

    2.1 The KV Cache Grows Linearly With Context Length

    Autoregressive generation needs to cache the Key/Value tensors of every layer, and their size is approximately:

    1. KV_bytes ≈ 2 × layers × kv_heads × head_dim × seq_len × batch × dtype_bytes

    The factor of 2 accounts for the two caches, K and V. It is proportional to the number of layers, the sequence length, and the concurrent batch size. In long-context scenarios, the KV cache often takes more space than the model weights themselves, making it the largest consumer of memory.

    2.2 Memory Bandwidth Becomes the Real Ceiling in the Decoding Stage

    Each decoding step processes only one token, a typical low-arithmetic-intensity workload. End-to-end latency is then determined mainly by how many bytes are moved, not by how many multiply-accumulate operations are performed. Once bandwidth is saturated, adding more compute does almost nothing for throughput.

    2.3 Allocation and Scheduling Add Fragmentation and Idle Bubbles

    Request lengths are unpredictable and lifecycles differ. If large contiguous memory blocks are allocated, both internal and external fragmentation appear; when long and short requests are interleaved, requests wait on each other inside a batch, forming “bubbles” where a long request holds up the whole batch. This waste usually does not show up in theoretical calculations, yet it directly consumes usable capacity.

    3. Optimization Path 1: Treat the KV Cache as a Manageable Memory Resource

    The core idea borrows from virtual memory in operating systems: instead of requiring a contiguous memory region, split the cache into fixed-size blocks and maintain a mapping table from logical position to physical block.

    1. class KVBlockPool:
    2. def __init__(self, block_tokens=16, num_blocks=1024):
    3. self.block_tokens = block_tokens
    4. self.free = list(range(num_blocks))
    5. self.table = {} # seq_id -> [block_id, ...]
    6. def append(self, seq_id, token_id):
    7. blocks = self.table.setdefault(seq_id, [])
    8. if not blocks or self._full(blocks[-1]):
    9. blocks.append(self.free.pop())
    10. self._write(blocks[-1], token_id)
    11. def release(self, seq_id):
    12. self.free.extend(self.table.pop(seq_id, []))

    This brings three direct benefits: fragmentation is close to zero; different requests can share prefix blocks, so common context such as system prompts and few-shot examples is stored only once; and swapping in and out has a uniform granularity, which paves the way for tiered storage.

    4. Optimization Path 2: Compression and Quantization to Lower the Cache Cost per Token

    • Lower numerical precision: converting the cache from half precision to a lower-bit-width representation is the most direct gain, and it should be paired with a small amount of calibration data to assess accuracy loss.
    • Structural pruning: evict low-contribution history entries based on attention score statistics, or let adjacent positions share cache representations, trading controllable quality loss for capacity.
    • Sparsity and windowing: for very long contexts, combine a local window with a small number of global anchors instead of retaining everything.

    In engineering practice, it is advisable to make compression a configurable policy, enabled in tiers according to how sensitive the business is to latency and quality, rather than applying a single global setting.

    5. Optimization Path 3: Tiered Storage and Offloading

    Memory, host memory, local flash, and object storage form a natural capacity ladder. Sinking cold cache blocks down the ladder and fetching them back on demand can support longer contexts and higher concurrency on limited memory. Three points matter in practice: first, block granularity and prefetch strategy must match the pace of decoding to avoid a synchronous wait on every step; second, the transfer path should overlap with computation as much as possible; third, capacity watermarks and eviction policies must be set to prevent a fetch storm. Logging services and monitoring alerts are indispensable here—hit rate, fetch latency, and eviction volume are all key metrics to observe.

    6. Optimization Path 4: Coordinating Dual-Path Scheduling and Parallelism

    Dual-path means treating compute-intensive prefill and memory-access-intensive decoding as two different kinds of workload and orchestrating them separately: prefill is split by blocks, can be pipelined, and is interleaved with decoding batches; on the decoding side, admission control and priority queuing use cache capacity as the constraint. Layering a sensible combination of tensor parallelism, pipeline parallelism, and expert parallelism on top makes the distribution of weights and cache fit the bandwidth topology more closely.

    A simplified admission check can be written as:

    1. def can_admit(req, pool, watermark=0.9):
    2. need = (req.prompt_len + req.max_new_tokens + pool.block_tokens - 1) // pool.block_tokens
    3. return len(pool.free) >= need and pool.usage() < watermark

    7. Practical Advice and Metrics

    Optimization must proceed with a closed data loop. It is recommended to fix three baseline metrics: latency per token (distinguishing the first token from subsequent tokens), the concurrency each card can carry, and the cache block hit rate; then run A/B comparisons, introducing only one variable at a time. If an organization lacks a complete experimentation and observability environment, general cloud capabilities can fill the gap—for example, using a container platform to host an elastic inference cluster, object storage to accumulate evaluation datasets, and monitoring alerts plus logging services to build a metrics dashboard.

    It is worth stressing that all of the above are general industry engineering practices; there is no “one switch that solves everything.” The usual sensible order is: first adopt paged cache management to eliminate fragmentation, then apply quantization and compression to reduce the per-token cost, then introduce tiered offloading to expand capacity, and finally tune dual-path scheduling and parallel partitioning. Following this order, most long-context, high-concurrency inference services can achieve substantial improvements in throughput and cost structure while keeping generation quality essentially unchanged.