Continuous Batching for LLM Inference: Principles and Practice of Concurrency Optimization

    This article explains why concurrency is difficult for large language model serving and how continuous batching keeps GPUs busy. It covers why decoding is memory-bound, how to estimate KV cache capacity, paged memory management, and admission control. It also outlines complementary techniques, including weight quantization, chunked prefill, and speculative decoding, along with the metrics used to evaluate results.

    1. Why Concurrency Is Hard

    Concurrency pressure on LLM services usually comes from two sources: the number of requests arriving at the same time, and the wide variation in generation length across requests. The first determines queuing time, while the second determines how long each request occupies resources. When scheduling is poorly designed, a system may reach only a small fraction of its theoretical throughput, even when hardware resources are sufficient.

    In practice, the same accelerator can produce tokens per second that differ by an order of magnitude depending on its batching strategy. The key to solving concurrency problems is therefore to keep every forward pass filled with as much useful work as possible. Simply adding more machines does not address the underlying problem.

    2. The Iterative Nature of LLM Inference

    LLM inference has two phases. The first is prefill, in which the model processes the entire user prompt at once and builds its intermediate state. The second is decode, in which the model generates one new token per step, appends it to the context, and runs the next round of computation.

    Consider the prompt “Describe the Yangtze River in one sentence.” If the answer contains about 20 tokens, the system must run about 20 decode forward passes. Each step depends on the result of the previous one, so a single request cannot be parallelized over time. It can only advance one step at a time.

    3. The Bottleneck Is Memory Access, Not Compute

    Each decode step must read the model weights from GPU memory into the compute units. The computation for a single step is relatively small, so the time spent reading weights dominates. This stage is limited by memory bandwidth and is therefore a memory-bound workload.

    This leads to a direct conclusion. If the system serves only one request at a time, that request bears the full cost of reading the weights. If multiple requests are merged into one batch, a single weight read serves all of them, and the memory access cost per token drops. The larger the batch, the higher the compute utilization, and the closer the throughput gets to the hardware limit.

    4. The Memory Budget Determines the Batch Size Limit

    The maximum batch size depends mainly on how many sequences’ KV caches fit in GPU memory. The KV cache stores the keys and values of every past token in each layer’s attention. Its size grows linearly with sequence length.

    The upper bound can be estimated with the following formula:

    KV cache bytes per token ≈ 2 × number of layers × hidden dimension × bytes per element

    For example, assume a model has 32 layers and a hidden dimension of 4096, stored in 16-bit floating point. Each token then takes about 512 KB. A sequence of length 2048 needs about 1 GB of GPU memory. If 20 GB of memory is reserved for the KV cache, the theoretical maximum is about 20 such sequences at the same time. This figure does not yet account for activations and temporary buffers.

    Some models use architectures such as grouped-query attention, which reduces the number of key and value heads. Their actual memory footprint can be noticeably lower than the estimate above. The estimate is only a reference for capacity planning. Verify it with measured data before going live.

    5. The Cost of Static Batching

    The traditional approach collects requests into a batch and runs inference only after the batch is full. Static batching has two clear problems.

    First, sequences in the same batch generate different numbers of tokens. Short responses finish early but must wait for the longest sequence to complete. During that time, compute resources sit idle or are occupied by padding.

    Second, a new request must wait until the current batch finishes before it can enter, which increases queuing delay.

    6. How Continuous Batching Works

    Continuous batching, also called iteration-level scheduling or dynamic batching, schedules at the level of each decode step instead of whole batches. After each step, the scheduler checks the batch state. Sequences that have generated an end-of-sequence token or reached the maximum length leave the batch immediately and release their resources. New requests waiting in the queue join the batch at the next step.

    Pseudocode:

    1. while service is running:
    2. new_request = take from the waiting queue any request that fits in the remaining KV cache memory
    3. batch.add(new_request)
    4. run one decode step for all sequences in batch
    5. for sequence in batch:
    6. if sequence generated the end-of-sequence token or reached the maximum length:
    7. return result(sequence)
    8. batch.remove(sequence)
    9. free the memory of sequence

    This design keeps the GPU as fully loaded as possible. Short requests do not have to run alongside long ones, and the time to first token for new requests is noticeably shorter. Continuous batching mainly eliminates idle time at the scheduling level. To realize its full benefit, it also requires supporting memory management and admission control.

    7. Memory Management Is a Key Supporting Component

    If every sequence is allocated a contiguous block of GPU memory sized for the maximum length in advance, a large amount of memory is wasted and fragmented, which makes it hard to use. A better approach is to split the KV cache into fixed-size blocks, allocate them on demand, and return them as soon as a sequence finishes. This paged style of management can significantly improve memory utilization, which allows more concurrent sequences.

    Admission control is equally important. The scheduler should decide whether to accept a new request based on the remaining memory. This prevents memory exhaustion during generation, which would cause request failures or force preemption. For very long requests, you can set a per-request context limit, or split long prompts and run chunked prefill, so that a single request cannot fill the entire batch.

    8. Other Optimizations That Can Be Combined

    1. Weight quantization: Compressing weights from 16-bit to 8-bit or 4-bit reduces the memory the model occupies, leaving more space for the KV cache. Quantization can reduce accuracy, so validate output quality with an evaluation set.
    2. Chunked prefill: Split the prefill of long prompts into smaller chunks and interleave them with the decode steps of other requests. This reduces the impact of long requests on the latency of short ones.
    3. Speculative decoding: A smaller draft model proposes multiple candidate tokens at once, and the main model verifies them in parallel. When the acceptance rate of candidates is high, the main model runs fewer serial steps.
    4. Request priority and timeouts: Assign higher priority to interactive requests and use a separate queue for offline tasks, so the two workloads do not compete for the same resources.

    9. How to Measure the Effect of Concurrency Optimization

    Do not rely on a single metric when evaluating a concurrency scheme. Common metrics include:

    • Throughput: Tokens generated per unit of time, which measures overall system output.
    • Time to first token (TTFT): The time from request arrival to the first output token. It directly affects the interactive experience.
    • Time per output token (TPOT): The average interval between adjacent tokens in streaming output. It affects how smooth the generation feels.
    • Tail latency (such as P99): The experience of the slowest requests.

    Testing should use request lengths and arrival patterns that closely match real traffic. In public benchmarks, continuous batching typically delivers a throughput improvement of several times to roughly tenfold over static batching. Actual gains depend on model size, hardware, load distribution, and scheduling parameters, so these results should not be applied directly to other scenarios.

    10. Practical Recommendations

    1. Measure before tuning: Record memory usage, batch size distribution, and queue wait times to identify the real bottleneck.
    2. Set memory watermarks: Reserve headroom for traffic bursts. When usage exceeds the threshold, throttle or queue requests instead of accepting more.
    3. Separate workload types: Long-form generation, short Q&A, and offline batch jobs suit different queues and parameters.
    4. Use autoscaling in the cloud: Combine the autoscaling of your container platform with monitoring and alerting services. Scale up or down based on queue length and tail latency.
    5. Run regression tests after every parameter change: Confirm that both output quality and latency metrics meet their targets.