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–8Ktokens) and variable output lengths (20–1000tokens). - SLOs: TTFT (Time to First Token)
≤ 400 ms, TPOT (Time Per Output Token)≤ 35 ms(~30 tok/sstreaming). - 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
4Kcontext:4096 × 320 KB ≈ 1.25 GBper concurrent request. - On an
80 GBH100 (~140 GBweights across2×TP2 =~70 GB/GPU, leaving~10–20 GBfree per GPU for KV), contiguousmax_seqpre-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
- PagedAttention (Virtual KV Memory): Split each request's KV cache into fixed-size physical blocks (e.g.
16tokens/block) mapped via a logical-to-physical block table. Physical blocks do not need to be contiguous, cutting internal fragmentation from~50%to<4%. - Iteration-Level Continuous Batching: Schedule at single-decode-step granularity. As soon as
R1emits<EOS>, free its KV blocks and slot queuedR3into the very next GPU forward pass. - 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.
- 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
| Tension | Trade-off & Mitigation |
|---|---|
| KV-cache OOM under bursts | Preempt lowest-priority request by swapping its KV blocks to CPU RAM or recomputing prefill on resume. |
| Chunked prefill vs decode jitter | Split 8K-token prefills into 512-token chunks interleaved with decode tokens to protect TPOT SLO. |
| Overload cascading | Enforce queue admission control (max_queue_wait < TTFT_SLO) and return 429 early with backoff. |