LLM Inference Compute Bottleneck: KV Cache and Continuous Batching Optimization

    Serving large language models is often limited not by raw GPU compute but by GPU memory—specifically the KV Cache that grows with concurrency and sequence length. This article breaks down the two-phase inference lifecycle (prefill and decode), explains why the KV Cache is the real driver of concurrency limits, and walks through the engineering techniques that keep inference services running under memory pressure: continuous batching, paged memory management, admission control and scheduling policies, and elastic scaling with resource pooling. It closes with a prioritized checklist for developers who want to build sustainable, high-throughput LLM inference services.

    When a conversational AI platform temporarily scales back its service availability, it makes headlines as a compute shortage. Yet such incidents are common across the LLM industry. On the surface the cause is “not enough compute,” but the underlying issue is a classic inference-system resource scheduling problem. To understand it, start with what a single inference request actually goes through on a GPU.

    1. The Inference Request Lifecycle: Two Phases, Not One

    Many developers assume that generating a response is a single forward pass. In real LLM inference, though, a request splits cleanly into two phases:

    • Prefill: The model computes the entire input prompt in parallel, producing the representations for all input tokens in one shot and building the initial KV Cache. This phase is compute-bound: it keeps GPU utilization high but lasts only briefly.
    • Decode: The model generates tokens autoregressively, one at a time. Each step processes only a single new token, yet it has to read the KV Cache for every token that came before it. This phase is memory-bound: the per-step computation is small, but it repeatedly shuttles large amounts of data through GPU memory.

    The key insight is that the number of users you can serve simultaneously is usually determined not by the compute in the decode phase but by the GPU memory consumed by the KV Cache. Only when one user finishes generating and its KV Cache is released can the system free up memory for the next request. This explains a counterintuitive pattern: even when the GPU still has compute to spare, new requests can only queue up as long as memory is full.

    2. KV Cache: The Real Memory Hog

    In autoregressive decoding, if you didn’t cache the keys and values of past tokens, generating each new token would require recomputing the entire history—a cost no one can afford. So in practice we cache the K and V tensors of every layer. That is the KV Cache.

    Its memory footprint can be approximated as:

    1. KV Cache memory ≈ 2 (K and V)
    2. × num_layers
    3. × (KV attention heads × head_dim)
    4. × sequence length (current token count)
    5. × batch size (concurrent requests)
    6. × bytes per data type (e.g., 2 for FP16)

    This formula leads to a few important conclusions:

    1. The KV Cache scales linearly with the number of concurrent requests, so the concurrency ceiling is inherently capped by available memory.
    2. It scales linearly with sequence length, so in long-context scenarios (tens of thousands of tokens) a single request can swallow several gigabytes of memory on its own.
    3. It depends on the data type: FP16 uses half the memory of FP32, and quantization can compress it further.

    This is also why, when a vendor tightens service during a compute or memory crunch, the root cause is the KV Cache—this “memory black hole”—hitting its ceiling.

    3. Batching Evolution: From Static to Continuous Batching

    The naive approach is to gather a full batch and then compute it together (static batching). The problem is that requests in a batch vary widely in generation length: short requests finish early but must wait for the long ones before the whole batch can be released, leaving the GPU idle much of the time.

    Modern inference services largely use continuous batching, often called iteration-level scheduling. The core idea is to check request status after every decode step: as soon as a request finishes, release its memory immediately and pull a new request from the waiting queue to fill the gap—no need to wait for the whole batch to align.

    1. # Simplified illustration of continuous batching scheduling
    2. def continuous_batching(running_queue, waiting_queue, step_fn):
    3. while running_queue or waiting_queue:
    4. # Admit as many new requests as the currently free memory allows
    5. admit_new_requests(running_queue, waiting_queue)
    6. # Run one decode step (all active requests share a single forward pass)
    7. outputs, kv_cache = step_fn(running_queue, kv_cache)
    8. # Evict finished requests, free their KV Cache, reclaim memory
    9. for req in list(running_queue):
    10. if req.is_finished(outputs):
    11. release_kv_cache(req, kv_cache)
    12. running_queue.remove(req)
    13. return

    Continuous batching markedly raises GPU utilization and overall throughput, making it possible to serve more users with the same compute.

    4. Paged Memory Management: Solving Fragmentation

    Even with continuous batching, the KV Cache still faces a serious problem. Because request lengths change dynamically, reserving contiguous memory based on the maximum length creates heavy internal fragmentation; growing allocations dynamically causes external fragmentation instead. The end result is “enough memory in total, but no usable block to hand out.”

    The widely adopted solution borrows the paging mechanism from operating-system virtual memory: split the KV Cache into fixed-size blocks, allocate and reclaim them on demand, and use a mapping table to track the correspondence between logical sequences and physical blocks. This dramatically improves memory utilization and cuts fragmentation. It also enables “shared prefixes”—such as an identical system prompt—to be reused by pointing to the same physical blocks, saving even more memory.

    5. Admission Control and Scheduling: Shaving the Peak

    When the request rate exceeds the system’s steady-state capacity, hard-constrained queuing is a necessary safeguard:

    • Rate limiting: Set per-user or per-tenant QPS and concurrency quotas so that a single source of traffic cannot monopolize shared resources.
    • Priority queues: Reserve lanes for paid or high-priority requests, letting ordinary requests degrade gracefully during peaks.
    • Admission and rejection policies: When memory runs short, quickly return a “try again later” response instead of letting requests pile up and bring the system down.
    • Separating long and short requests: Route long-context requests to dedicated resource pools so they do not block short ones.

    Together, these strategies determine the fairness and stability of a service operating under rigid compute constraints.

    6. Elastic Scaling and Resource Pooling

    Handling sudden compute pressure takes more than single-machine tuning; it requires elasticity at the architecture level:

    1. Horizontal scaling: Run inference instances on a container platform and scale them automatically based on signals such as queue length, GPU memory utilization, and decode latency.
    2. Resource pooling: Route requests of different sizes and context lengths to differentiated resource pools to raise overall utilization.
    3. Cost elasticity: Use on-demand elastic GPU compute from cloud providers to add or remove instances as needed—scaling down at low demand to cut cost and scaling up at peak to protect the user experience. General-purpose cloud capabilities—elastic containers, object storage, message queues, and monitoring and alerting, as offered by enterprise platforms such as Baidu AI Cloud—are the building blocks that support this kind of elastic inference architecture.

    7. Practical Recommendations for Developers

    Drawing the analysis together, here is a priority order for building a sustainable LLM inference service:

    1. Optimize single-GPU efficiency first: Turn on continuous batching and paged KV Cache to squeeze out the most throughput from one machine.
    2. Then control memory overhead: Set a sensible maximum context length, adopt FP16 or quantization, and reuse shared system prefixes.
    3. Add admission control and graceful degradation: Use rate limiting and priority scheduling to keep the system from being overwhelmed.
    4. Finally, scale elastically: Let monitoring metrics drive auto-scaling so that compute expands and contracts with load.

    Closing thought: A compute crunch is never solved by simply “adding more GPUs.” It is a systems-engineering problem that calls for the coordinated optimization of memory, scheduling, policies, and elasticity. Understanding the KV Cache and the inference lifecycle is essential knowledge for every LLM service engineer—it ultimately decides how many users you can reliably serve with the compute you have.