Skip to content

Serving and Batching

Serving an LLM to thousands of concurrent users requires more than loading a model and running inference. This file covers the prefill-decode split, continuous batching, chunked prefill, PagedAttention and vLLM, RadixAttention prefix reuse, scheduling strategies, disaggregated prefill-decode serving, multi-model and LoRA serving, fast grammar-constrained decoding, and the metrics that matter.

  • A single LLM inference request is simple: feed in tokens, generate output tokens. But serving an LLM to 10,000 concurrent users at low latency and high throughput is a systems problem. The naive approach (process one request at a time) wastes 90%+ of GPU capacity. Smart batching and scheduling can increase throughput 10-50x without adding hardware.

Prefill vs Decode: Two Very Different Phases

  • LLM inference has two distinct phases with fundamentally different computational characteristics:

  • Prefill (prompt processing): process all input tokens simultaneously. This is a single large matrix multiplication: \(O(\text{prompt\_length} \times d_{\text{model}}^2)\). The prompt can be processed in parallel (all tokens are known). Prefill is compute-bound: the GPU's ALUs are the bottleneck.

  • Decode (token generation): generate one token at a time, autoregressively. Each new token requires attending to all previous tokens via the KV-cache. Decode is memory-bandwidth-bound: the GPU spends most time loading model weights and KV-cache from memory, not computing. Each decode step produces just one token but must load the entire model (~140 GB for a 70B model in FP16).

  • The implications:

Prefill Decode
Tokens processed All at once (parallel) One at a time (sequential)
Bottleneck Compute (FLOPS) Memory bandwidth
Arithmetic intensity High Very low
GPU utilisation High (50-80%) Low (1-10%) without batching
Latency metric Time to First Token (TTFT) Time Per Output Token (TPOT)
  • TTFT matters for user experience (how long until the response starts streaming). TPOT determines the perceived generation speed. Users tolerate higher TTFT (1-5 seconds) but expect fast TPOT (30-100 ms per token for conversational applications).

Static Batching (Naive)

  • The simplest batching: collect \(B\) requests, pad them to the same length, process them as a single batch.

  • Problem 1: requests have different prompt lengths and generate different numbers of output tokens. Short requests finish early but must wait for the longest request in the batch before the next batch can start. The GPU sits idle while generating for the one remaining long request.

  • Problem 2: padding wastes compute. If the longest prompt is 2000 tokens and the shortest is 50, the batch is padded to 2000. The GPU processes 1950 padding tokens for the short request — pure waste.

Static batching wastes GPU slots while waiting for the longest request; continuous batching fills freed slots immediately

Continuous Batching

  • Continuous batching (also called iteration-level batching) solves both problems by operating at the granularity of individual decode steps, not entire requests.

  • At each decode step:

    1. All in-flight requests generate one token in parallel (as a batch).
    2. Requests that finish (generate EOS token) are removed from the batch immediately.
    3. New requests from the queue are inserted into the freed slots immediately.
  • The batch size changes dynamically every step. The GPU is never idle waiting for stragglers, and there is no wasted padding (each request uses only the slots it needs).

  • Impact: continuous batching typically increases throughput 2-10x over static batching, with no change to model quality or significant latency increase.

PagedAttention and vLLM

  • The KV-cache creates a memory management nightmare. Each request has a KV-cache that grows with each generated token. Different requests are at different stages (different cache sizes). Allocating contiguous memory for each request wastes space (you must allocate for the maximum possible length, even if the request generates only a few tokens).

PagedAttention maps virtual KV-cache pages to non-contiguous physical GPU memory, eliminating fragmentation and enabling on-demand allocation

  • PagedAttention (Kwon et al., 2023) applies the OS concept of virtual memory (chapter 16) to the KV-cache. The cache is divided into fixed-size pages (blocks of token positions). Pages are allocated on demand and can be non-contiguous in physical GPU memory.

  • The benefits:

    • No fragmentation: pages are uniform size, so there are no "holes" of wasted memory between requests.
    • Lazy allocation: memory is allocated only when tokens are actually generated, not pre-allocated for maximum length.
    • Copy-on-write: requests that share a common prefix (e.g., system prompts) share the same KV-cache pages. Only when the requests diverge are the pages copied.
  • vLLM is the inference engine built around PagedAttention. It achieves 2-4x higher throughput than static-allocation serving (like HuggingFace's text-generation-inference without paged attention) by virtually eliminating KV-cache memory waste.

Chunked Prefill

  • Continuous batching removes straggler bubbles, yet colocating prefill and decode on the same GPU introduces a subtler stall known as prefill-decode interference. Imagine 64 conversational users streaming tokens smoothly at 25 ms per token when a single user uploads a 32K-token document. Processing that entire prompt in one monolithic prefill step monopolises the GPU for hundreds of milliseconds, freezing every active user's stream and spiking Time Per Output Token (TPOT).

  • Chunked prefill (popularised by Sarathi-Serve and now standard across vLLM, SGLang, and TensorRT-LLM) resolves this by slicing long prompts into fixed-size chunks (for example, 512 or 2048 tokens) and piggybacking one prefill chunk into the same forward pass as the ongoing decode batch. Because decode tokens are memory-bandwidth-bound and leave Tensor Core FLOPS heavily underutilised, folding a prefill chunk into each decode step saturates the spare compute capacity almost for free. Every step stays bounded by a predictable token budget, smoothing out TPOT jitter while raising total GPU utilisation.

RadixAttention and Tree-Based Prefix Reuse

  • PagedAttention lets concurrent requests share identical prefix pages while they are running, yet naive engines discard a request's KV cache the instant generation finishes. In real workloads (multi-turn chat histories, shared system prompts, RAG documents, agent tool definitions, and branching tree-of-thought searches), subsequent requests repeatedly traverse the exact same prefixes.

  • RadixAttention (introduced in SGLang) organises GPU KV-cache pages inside a radix tree (a compressed prefix trie) that persists across requests. Each tree edge represents a sequence of tokens pointing to its cached KV pages in HBM. Rather than deleting KV pages when a request finishes, RadixAttention keeps them resident in the tree and evicts only the least recently used leaf branches when free memory runs low.

  • When a new prompt arrives, the runtime walks the radix tree to locate the longest cached prefix match and skips prefill for every matched token. Pairing the radix tree with cache-aware scheduling (reordering queued requests so prompts sharing a hot prefix run back-to-back before their pages are evicted) dramatically lifts prefix hit rates, slashing TTFT and redundant compute across multi-turn and agentic workloads.

Scheduling Strategies

  • When multiple requests are waiting and the GPU can only process a limited batch, scheduling decides which requests to serve:

  • First Come First Served (FCFS): process requests in arrival order. Simple but unfair: a user submitting a 10K-token generation blocks all users behind them.

  • Shortest Job First (SJF): process the request that will finish soonest. Minimises average latency but penalises long-running requests (they may starve). In practice, estimated output length is unknown, so SJF uses heuristics (prompt length, user history).

  • Preemption: if a high-priority request arrives, pause a lower-priority in-progress request (swap its KV-cache to CPU memory or SSD), serve the high-priority request, then resume the paused one. vLLM supports this.

  • Priority-based: assign priorities to users or request types. Real-time interactive queries get higher priority than batch processing jobs. Combined with preemption, this ensures latency SLOs for high-priority traffic.

  • Token budget: limit the total number of tokens in the active batch. This prevents a few long requests from monopolising GPU memory and starving new requests.

Disaggregated Prefill and Decode Serving

  • Even with chunked prefill, forcing prefill and decode to share the same GPUs creates an awkward compromise at large scale. Prefill is compute-bound and prefers modest parallelism tuned for low TTFT, whereas decode is memory-bandwidth-bound and thrives on wide batching, generous KV-cache headroom, and smooth TPOT.

  • Disaggregated prefill and decode serving physically separates the two phases onto independent GPU pools connected by a high-speed KV transfer fabric.

    • Prefill pool runs compute-optimised workers dedicated solely to digesting incoming prompts and building initial KV caches without worrying about interrupting streaming users.
    • Decode pool runs bandwidth- and capacity-optimised workers dedicated solely to autoregressive token generation, delivering flat, predictable TPOT completely insulated from sudden spikes in long-prompt traffic.
    • KV-aware router and transport layer routes prompts to prefill workers holding warm prefix matches, then streams newly computed KV blocks directly from prefill GPU HBM into decode GPU HBM over NVLink (within a rack domain) or RDMA (InfiniBand or RoCE across nodes) asynchronously so compute rarely stalls.
  • DistServe (Zhong et al., 2024) established the theoretical and empirical blueprint for disaggregation, proving that matching parallelism strategies independently to prefill and decode boosts cluster goodput (requests meeting both TTFT and TPOT SLOs simultaneously) far beyond colocated deployments.

  • Mooncake (Moonshot AI, powering Kimi) took disaggregation into hyperscale production by making the KV cache a first-class distributed resource. Its Mooncake Transfer Engine handles non-blocking RDMA KV transfers between prefill and decode pools, while Mooncake Store pools underutilised host DRAM and SSDs across the cluster for massive content-addressed prefix caching.

  • NVIDIA Dynamo brings disaggregated serving to enterprise multi-engine fleets (orchestrating vLLM, SGLang, and TensorRT-LLM workers). It pairs KV-aware routing and dynamic autoscaling of the prefill-to-decode worker ratio with NIXL (an accelerated non-blocking transfer layer over NVLink and RDMA), allowing operators to rebalance pools automatically as traffic shifts between prompt-heavy RAG queries and generation-heavy reasoning sessions.

Multi-Model and LoRA Serving

  • In production, you often serve multiple models (different sizes for different tiers, different fine-tuned variants for different tasks).

  • Model multiplexing: load multiple models on the same GPU and route requests to the appropriate model. GPU memory is shared: a 40 GB GPU might hold a 13B model (26 GB) and a 7B model (14 GB) simultaneously.

  • LoRA serving: instead of deploying separate fine-tuned models, deploy one base model with multiple LoRA adapters (chapter 6). Each adapter adds <1% parameters. Requests are routed to the appropriate adapter at inference time.

  • S-LoRA (Sheng et al., 2023): serves thousands of LoRA adapters from a single base model. Adapters are stored on CPU and paged into GPU memory on demand. The base model's KV-cache and weights are shared; only the small LoRA matrices differ per request.

  • Punica (Chen et al., 2023): batches requests across different LoRA adapters by using a custom CUDA kernel that applies different LoRA matrices to different requests within the same batch. This avoids the overhead of switching adapters per request.

Constrained and Guided Generation

  • Many production systems require an LLM to emit strictly formatted outputs such as valid JSON, SQL queries, typed tool-call arguments, or domain-specific code. Grammar-constrained decoding guarantees 100% structural compliance on the first pass without wasteful retry loops (which commonly fail 10-30% of the time on nested schemas).

  • At every decode step, the engine consults the active grammar state and masks out every vocabulary token that would lead to an invalid continuation, setting forbidden logits to \(-\infty\) before softmax sampling so probability mass is renormalised cleanly across valid tokens alone.

  • Early libraries like Outlines (Willard & Louf, 2023) proved the power of compiling JSON schemas and regular expressions into finite-state machines (FSMs), yet checking every candidate inside a 128K-token vocabulary on the CPU at every decode step could introduce milliseconds of host overhead that stalled fast GPUs.

  • Modern high-performance grammar engines such as XGrammar (MLC/LMSYS) and LLGuidance (Guidance AI) shrink this overhead to microseconds per step, enabling near-zero-cost structured decoding inside vLLM, SGLang, and TensorRT-LLM. They achieve this by splitting the vocabulary into context-independent tokens (whose validity for each grammar state can be precomputed and cached ahead of time) and a tiny subset of context-dependent tokens evaluated dynamically.

  • During generation, the grammar engine compiles permitted token IDs into a compact vocabulary bitmask (one bit per token, where 1 permits and 0 forbids) on the CPU in parallel with GPU model execution. Applying that bitmask to the logits on the GPU takes a few microseconds, supports full context-free grammars (such as recursive JSON and programming languages), and integrates smoothly with RadixAttention prefix caching and fast-forwarding over deterministic schema boilerplate.

Request Routing

  • Not every query needs the biggest model. Request routing directs queries to different models based on estimated difficulty:

  • Cascading: try a small model first. If the small model's confidence is below a threshold (e.g., the softmax probability of the top token is < 0.8), escalate to a larger model. Easy queries (80%+ of traffic) are served cheaply by the small model; only hard queries use the expensive model.

  • Learned routing: train a lightweight classifier (or use the small model's perplexity) to predict which model tier a query needs. Route "What is 2+2?" to a 3B model and "Explain the mathematical foundations of quantum entanglement" to a 70B model.

  • Impact: if 80% of queries can be handled by a model that costs 10x less, the average cost per query drops by ~70%. This is one of the highest-impact cost optimisations for multi-model deployments.

  • On-device + cloud hybrid routing: Cactus (github.com/cactus-compute/cactus) implements request routing at the device level. It runs a small model on-device (phone, laptop, wearable) via custom ARM SIMD kernels, and automatically routes to a cloud model when the local model's confidence is low or the query exceeds the device's capability. The application uses an OpenAI-compatible API for both paths — the routing is transparent. This is cascading at the infrastructure level: the first tier is free (on-device), the second tier costs money (cloud API). For applications where most queries are simple (assistant Q&A, autocomplete, transcription), on-device handling covers 70-90% of traffic at zero marginal cost.

Inference Metrics

  • The right metrics depend on the use case:
Metric What It Measures Target (Conversational) Target (Batch)
TTFT Time to first token <1 s less important
TPOT Time per output token <100 ms less important
Throughput Tokens/second (total) less important maximise
p99 Latency Worst 1% of requests <5 s <30 s
Cost per token $/1M tokens minimise minimise
SLO compliance % of requests meeting latency target >99% >95%
  • TTFT vs TPOT tradeoff: aggressive batching increases throughput (more tokens/s total) but increases TPOT (each token takes longer because the GPU processes more requests). The scheduling strategy must balance throughput (revenue) against latency (user experience).

  • Cost per token is the ultimate metric for production. It combines hardware cost (GPU rental), throughput (tokens/s), and utilisation. A system running at 50% GPU utilisation costs 2x more per token than one at 100%. This is why batching, scheduling, and PagedAttention matter so much — they increase utilisation.

Coding Tasks (use CoLab or notebook)

  1. Simulate continuous vs static batching and measure the throughput difference.

    import random
    import time
    
    def simulate_static_batching(requests, batch_size=8):
        """Process requests in fixed batches. Wait for all to finish."""
        total_tokens = 0
        total_time = 0
    
        for i in range(0, len(requests), batch_size):
            batch = requests[i:i + batch_size]
            max_len = max(r['output_len'] for r in batch)
            # All requests in the batch take as long as the longest
            batch_time = max_len * 0.01  # 10ms per token
            total_time += batch_time
            total_tokens += sum(r['output_len'] for r in batch)
    
        return total_tokens / total_time  # tokens per second
    
    def simulate_continuous_batching(requests, max_batch=8):
        """Process with continuous batching. Remove finished, add new."""
        total_tokens = 0
        total_time = 0
        active = []
        queue = list(requests)
    
        while active or queue:
            # Fill batch
            while len(active) < max_batch and queue:
                active.append({'remaining': queue.pop(0)['output_len']})
    
            if not active:
                break
    
            # One decode step: all active requests generate 1 token
            for req in active:
                req['remaining'] -= 1
            total_tokens += len(active)
            total_time += 0.01  # 10ms per step
    
            # Remove finished requests
            active = [r for r in active if r['remaining'] > 0]
    
        return total_tokens / total_time
    
    # Generate requests with varied output lengths
    random.seed(42)
    requests = [{'output_len': random.randint(10, 500)} for _ in range(100)]
    
    static_tps = simulate_static_batching(requests)
    continuous_tps = simulate_continuous_batching(requests)
    
    print(f"Static batching:     {static_tps:.0f} tokens/s")
    print(f"Continuous batching: {continuous_tps:.0f} tokens/s")
    print(f"Speedup: {continuous_tps / static_tps:.1f}x")
    

  2. Calculate the KV-cache memory savings from PagedAttention. Compare pre-allocated (worst case) vs paged (actual usage).

    def paged_vs_preallocated(n_requests, max_seq_len, avg_seq_len, page_size, kv_per_token_bytes):
        """Compare memory usage: preallocated vs paged KV-cache."""
        # Preallocated: every request gets max_seq_len slots
        preallocated_gb = n_requests * max_seq_len * kv_per_token_bytes / 1e9
    
        # Paged: allocate only what is used (with page granularity)
        import math
        avg_pages = math.ceil(avg_seq_len / page_size)
        paged_gb = n_requests * avg_pages * page_size * kv_per_token_bytes / 1e9
    
        waste_preallocated = (max_seq_len - avg_seq_len) / max_seq_len
        waste_paged = (avg_pages * page_size - avg_seq_len) / (avg_pages * page_size)
    
        print(f"Requests: {n_requests}, Max seq: {max_seq_len}, Avg seq: {avg_seq_len}")
        print(f"  Preallocated: {preallocated_gb:.1f} GB (waste: {waste_preallocated:.0%})")
        print(f"  Paged:        {paged_gb:.1f} GB (waste: {waste_paged:.0%})")
        print(f"  Savings:      {preallocated_gb - paged_gb:.1f} GB ({preallocated_gb/paged_gb:.1f}x)")
        print()
    
    # Llama-70B: ~1.3 KB per token per layer, 80 layers = ~100 KB per token total
    kv_bytes = 100_000
    
    # Scenario 1: short requests, large max
    paged_vs_preallocated(256, max_seq_len=4096, avg_seq_len=256, page_size=16, kv_per_token_bytes=kv_bytes)
    
    # Scenario 2: varied lengths
    paged_vs_preallocated(256, max_seq_len=8192, avg_seq_len=1024, page_size=16, kv_per_token_bytes=kv_bytes)
    
    # Scenario 3: long context
    paged_vs_preallocated(64, max_seq_len=131072, avg_seq_len=16000, page_size=16, kv_per_token_bytes=kv_bytes)