Skip to main content
System Designhard•DECEMBER 2026•20 MIN

Design an LLM Inference Serving Engine

Continuous batching, PagedAttention KV-cache memory blocks, prefix caching, and TTFT vs TPOT latency trade-offs at OpenAI scale.

continuous batchingpaged memoryprefix cachingload sheddingml-systemsllm-servinggpu

1. Clarifying questions & SLO contract

  • Workload: Mixed prompt lengths (200–8K tokens) and variable output lengths (20–1000 tokens).
  • SLOs: TTFT (Time to First Token) ≤ 400 ms, TPOT (Time Per Output Token) ≤ 35 ms (~30 tok/s streaming).
  • Bottleneck: Prefill is compute-bound (large matrix-matrix multiply); autoregressive decode is HBM memory-bandwidth bound (streaming weights + KV cache per token).

2. Back-of-envelope KV-cache sizing

For a 70B GQA model (80 layers, 8 KV heads, d_head = 128, fp16 = 2 bytes):

  • KV cache per token: 2 (K+V) × 80 × 8 × 128 × 2 bytes = 327,680 bytes ≈ 320 KB/token.
  • At 4K context: 4096 × 320 KB ≈ 1.25 GB per concurrent request.
  • On an 80 GB H100 (~140 GB weights across 2× TP2 = ~70 GB/GPU, leaving ~10–20 GB free per GPU for KV), contiguous max_seq pre-allocation wastes ~50% of KV RAM and caps batch size.

3. Interactive continuous batching & PagedAttention simulator

Compare Static Batching (head-of-line blocking + <PAD> bubbles + ~48% KV fragmentation) against Continuous + PagedAttention with Prefix Cache enabled:

LOADING LLM SERVING & PAGEDATTENTION SIM...

4. Deep dive: scheduler & memory architecture

  1. PagedAttention (Virtual KV Memory): Split each request's KV cache into fixed-size physical blocks (e.g. 16 tokens/block) mapped via a logical-to-physical block table. Physical blocks do not need to be contiguous, cutting internal fragmentation from ~50% to <4%.
  2. Iteration-Level Continuous Batching: Schedule at single-decode-step granularity. As soon as R1 emits <EOS>, free its KV blocks and slot queued R3 into the very next GPU forward pass.
  3. Radix Prefix Caching + Sticky Routing: Hash shared system-prompt / few-shot prefix blocks into a radix tree so identical prefixes share read-only physical KV blocks (copy-on-write on divergence). Pair with consistent-hash prefix routing at the L7 gateway so repeat prompts land on the warm GPU replica.
  4. Prefill/Decode Disaggregation (Advanced): Dedicate prefill replicas to compute-bound prompt ingestion and stream KV blocks over NVLink/RDMA to decode replicas so long-prompt prefills never spike decode TPOT jitter.

5. Failure modes & trade-offs

TensionTrade-off & Mitigation
KV-cache OOM under burstsPreempt lowest-priority request by swapping its KV blocks to CPU RAM or recomputing prefill on resume.
Chunked prefill vs decode jitterSplit 8K-token prefills into 512-token chunks interleaved with decode tokens to protect TPOT SLO.
Overload cascadingEnforce queue admission control (max_queue_wait < TTFT_SLO) and return 429 early with backoff.

Related Lab Entries