FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Inference Serving Architecture

How routing batching caching autoscaling and accelerators serve model workloads.

Freshness: current•16 min read•Production Infrastructure and AI Economics

Key Learning Outcomes

  • ✓Trace routing queueing batching and execution
  • ✓Relate cache pressure to throughput and latency
  • ✓Select scaling signals for inference workloads
Full Technical Reference Document

Mental model

An LLM inference engine is a stateful queueing scheduler wrapping finite HBM memory pools and Tensor Core budgets. Replacing static padded request batches with iteration-level continuous batching, PagedAttention virtual KV blocks, bounded chunked prefill, and prefill-decode disaggregation eliminates fragmentation and head-of-line latency stalls simultaneously.

Priority admission gate
Chunked prefill budgeting
Paged KV block allocation
Iteration-level forward step
Preemption or KV disaggregation
Conceptual teaching model synthesized from:Efficient Memory Management for Large Language Model Serving with PagedAttentionvLLM inference and serving engineHorizontal Pod AutoscalingvLLM V1 scheduler at v0.10.2

Learning outcomes

  • Quantify padding waste in static request-level batching versus iteration-level continuous scheduling in vLLM V1.
  • Explain how PagedAttention eliminates external fragmentation and upfront max_seq_len over-reservation using fixed-size KV blocks.
  • Size chunked prefill token budgets (max_num_batched_tokens) to protect decode inter-token latency (ITL) from long-prompt stalls.
  • Evaluate when prefill-decode (P/D) disaggregation over NVLink or RDMA outperforms unified chunked-prefill pools.

Theory

Traditional neural serving engines group BB requests into a static tensor padded to (max⁡iLin,i,max⁡iLout,i)(\max_i L_{\text{in},i}, \max_i L_{\text{out},i}) and hold every GPU slot until the longest sequence emits end-of-sequence (EOS). If one request emits 1,024 tokens while three others finish at 32 tokens, the engine wastes over two-thirds of active GPU iterations. Continuous iteration-level scheduling (implemented in vLLM's V1 scheduler, vllm/v1/core/sched/scheduler.py) makes scheduling decisions on every forward step: finished sequences release their KV blocks immediately and queued requests enter the running batch on the very next token step.

Even with continuous batching, contiguous KV allocation wastes 60%–80% of HBM because engines must pre-reserve contiguous buffers up to max_model_len before knowing how long a response will grow, leaving unusable external fragmentation holes between variable-length sequences. PagedAttention (vllm-paper) virtualizes KV memory into fixed-size pages of BpageB_{\text{page}} tokens (typically 16). A per-sequence block table maps logical token positions onto non-contiguous physical GPU blocks allocated lazily on demand, bounding internal waste to at most Bpage−1B_{\text{page}} - 1 tokens on the tail page and enabling zero-copy prefix sharing across requests sharing system prompts.

KV-Cache Block Allocator (Paged vs Contiguous)

Prompt Length (L tokens)64 tokens
Blocks per seq: ⌈L/B⌉ = 4Page Size B = 16
Active Sequences (Concurrency)3 requests
Total blocks needed: 12Pool Capacity: 32
Physical GPU Block Table (32 × 16-Token Pages)Allocated: 12/32 Blocks
#0S0
#1S0
#2S0
#3S0
#4S1
#5S1
#6S1
#7S1
#8S2
#9S2
#10S2
#11S2
#12·
#13·
#14·
#15·
#16·
#17·
#18·
#19·
#20·
#21·
#22·
#23·
#24·
#25·
#26·
#27·
#28·
#29·
#30·
#31·
Blocks per Seq⌈64/16⌉ = 4
Allocated Blocks12 / 32
Internal Waste0 tokens
Fragmentation0%

Continuous batching alone still suffers from prefill-decode interference: when a 16,384-token RAG prompt arrives, running its entire prefill in one step hijacks the GPU for hundreds of milliseconds, stalling ITL across every concurrent interactive decode stream (head-of-line blocking). Two production architectures solve this:

  1. Chunked Prefill: Splits long prompts into bounded slices (e.g., Tchunk=512–2,048T_{\text{chunk}} = 512\text{–}2{,}048 tokens) and merges each prefill slice with active 1-token decode steps up to a fixed iteration token budget:

Niter_tokens=∑s∈Decode1+∑p∈Prefilltchunk(p)≤TbudgetN_{\text{iter\_tokens}} = \sum_{s \in \text{Decode}} 1 + \sum_{p \in \text{Prefill}} t_{\text{chunk}}(p) \le T_{\text{budget}}

Piggybacking decode tokens onto prefill chunks saturates Tensor Cores while capping worst-case decode ITL jitter.

  1. Prefill-Decode (P/D) Disaggregation: Dedicates separate GPU pools to compute-bound prefill and bandwidth-bound decode, streaming materialized KV blocks over NVLink or RDMA. Disaggregation wins on strict SLO isolation whenever KV transfer latency TxferT_{\text{xfer}} is negligible relative to co-located prefill stalls:

Txfer=Nprompt⋅KV_bytes_per_tokenβinterconnectT_{\text{xfer}} = \frac{N_{\text{prompt}} \cdot \text{KV\_bytes\_per\_token}}{\beta_{\text{interconnect}}}

When aggregate free KV blocks drop below demand during extreme bursts, the scheduler performs preemption—either swapping evicted blocks to host CPU RAM or discarding them for later recomputation (recompute often beats PCIe swap latency on fast compute models).

Worked quantitative example

Consider 4 requests arriving together with output lengths [32, 64, 128, 1024] on a model with max_model_len = 4,096 and 128 KiB/token GQA-8 KV footprint:

  • Static Padded Batching + Contiguous max_model_len Reservation: Reserving contiguous slots for 4,096 tokens per request pins Mres=4×4,096×128 KiB=2.0 GiBM_{\text{res}} = 4 \times 4{,}096 \times 128\text{ KiB} = 2.0\text{ GiB} upfront, while waiting 1,024 iterations occupies 4 * 1,024 = 4,096 decode slot-steps for only 32 + 64 + 128 + 1024 = 1,248 real tokens—wasting 69.5% of slot-steps on idle padding!
  • PagedAttention (B_page = 16) + Continuous Batching: Actual blocks needed match live token growth (ceil(len / 16)), keeping internal fragmentation below 4% on average and freeing the 32-token request's slots after step 32 so new requests backfill immediately.
  • Chunked Prefill vs P/D Disaggregation on an 8,192-Token Prompt: Full unchunked 8k prefill stalls co-located decode by ~400 ms. Chunking prefill into 512-token steps (16 iterations) caps per-step decode interruption near ~25 ms. Conversely, transferring the 8,192 * 128 KiB = 1.0 GiB KV cache from a dedicated prefill pool over 400 Gbps RoCEv2/RDMA (50 GB/s effective) takes Txfer=1.07 GiB/50 GB/s≈21.5 msT_{\text{xfer}} = 1.07\text{ GiB} / 50\text{ GB/s} \approx 21.5\text{ ms}—completely decoupling decode ITL from 8k+ prefill bursts.

Inference serving architecture comparison

Serving DesignKV FragmentationHead-of-Line Decode StallBatch ThroughputOperational Complexity
Static Batching + Contiguous KVVery high (60%–80% waste)Severe (max_out stalls)Low (1x baseline)Minimal
Continuous Batching + PagedAttentionMinimal (< 4% tail page)High during long prefillsHigh (2.5x–3.5x)Moderate (block table + preemption)
Chunked Prefill + Continuous BatchingMinimal (< 4%)Bounded by T_budgetVery high (decode piggybacks prefill)Moderate (token-budget tuning)
Disaggregated Prefill / Decode (P/D)Minimal (< 4%)Eliminated across poolsPeak per-tier specializationHigh (RDMA/NVLink KV transport + P:D ratio)

Trade-offs

Chunked prefill inside a unified GPU pool maximizes hardware utilization because decode tokens ride along inside prefill matrix multiplications for almost free, avoiding idle interconnect overhead or rigid prefill-to-decode replica sizing ratios. However, very long prompts (32k–128k tokens) still raise decode ITL slightly across all chunks, and unified pools share failure domains.

Prefill-decode disaggregation delivers unmatched TTFT and ITL isolation for latency-critical interactive products at scale, enabling independent tensor-parallelism topologies (e.g., high-TP compute nodes for prefill, memory-optimized nodes for decode). Its costs are network fabric requirements (NVLink / 400G RDMA), KV transfer serialization complexity, and dynamic capacity imbalance when average prompt-to-output length ratios shift mid-day.

Failure modes and misconceptions

  • Assuming higher max_num_batched_tokens always improves user experience. Raising the iteration token budget boosts prefill throughput, but oversizing it lets multi-thousand-token prefills inflate decode ITL spikes across streaming chat users.
  • Ignoring preemption thrashing (num_preemptions_total) under tight KV pools. Running KV utilization at 99% causes constant sequence eviction and recomputation loops that burn compute without advancing completed tokens; target 80%–85% steady utilization with backpressure gating.
  • Mixing interactive and long-document batch traffic without priority classes. Without separate queues or preemption priority, batch extraction jobs starve interactive TTFT and consume shared KV blocks.
  • Forgetting prefix-cache memory pinning hazards. Copy-on-write prefix KV blocks accelerate shared system prompts massively, yet pinning stale tenant prefixes without LRU eviction starves new requests of physical pages.

Decision scenario

A multi-tenant coding assistant handles both short interactive autocomplete/chat prompts (400 input tokens, 150 output tokens, strict ITL P99 at most 30 ms) and repository-wide refactoring requests (16,000 input tokens, 800 output tokens) on 8-GPU nodes connected via InfiniBand/RDMA. Users report rhythmic 380 ms freezes during streaming whenever someone submits a full-repository prompt.

First, verify whether unified chunked prefill (max_num_batched_tokens = 512, enable_chunked_prefill = True) paired with priority scheduling (prioritizing running decodes and short interactive prefills before chunking long repository prompts) pulls decode ITL P99 under 30 ms. If peak repository-upload concurrency still forces prefill chunk queues over TTFT budgets, transition to 2:6 disaggregated Prefill-to-Decode pools transferring PagedAttention KV blocks over RDMA while monitoring KV utilization (under 85%) and preemption counters.

Implementation example

This Python iteration scheduler models continuous batching with PagedAttention physical block accounting, chunked prefill token budgeting (T_budget), and LIFO preemption when free KV blocks exhaust.

python
from collections import deque
from dataclasses import dataclass
import math
​
@dataclass
class SeqState:
seq_id: str
prompt_rem: int
tokens: int = 0
blocks: int = 0
​
def step_scheduler(
running: list[SeqState], waiting: deque[SeqState], free_blocks: int, page: int = 16, budget: int = 512
) -> tuple[int, int, int, list[str]]:
rem, preemptions, scheduled = budget, 0, []
for seq in list(running) + list(waiting):
if rem <= 0:
break
toks = 1 if seq.prompt_rem == 0 else min(seq.prompt_rem, rem)
need = max(0, math.ceil((seq.tokens + toks) / page) - seq.blocks)
while need > free_blocks and running and running[-1] is not seq:
victim = running.pop()
free_blocks, victim.blocks = free_blocks + victim.blocks, 0
waiting.appendleft(victim)
preemptions += 1
if need <= free_blocks:
if seq in waiting:
waiting.remove(seq); running.append(seq)
free_blocks, seq.blocks = free_blocks - need, seq.blocks + need
seq.prompt_rem, seq.tokens = max(0, seq.prompt_rem - toks), seq.tokens + toks
rem -= toks; scheduled.append(seq.seq_id)
return budget - rem, free_blocks, preemptions, scheduled
​
run_q, wait_q = [], deque([SeqState("chat-1", 64), SeqState("rag-2", 1200)])
assert step_scheduler(run_q, wait_q, free_blocks=64) == (512, 32, 0, ["chat-1", "rag-2"])
Reflect before revealing the guide

How do chunked prefill and prefill-decode disaggregation protect decode inter-token latency without sacrificing GPU utilization?

Prerequisites & Related Concepts (4)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-101Model Serving and Inference

Understand inference engines memory scheduling batching routing scaling distributed execution lifecycle controls observability and economics.

19 concepts~23h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next