FullStack AI Hub
Studio
AI & LLM Systems · 02. Inference & Retrieval
10 min
6 steps
Intermediate

LLM Inference & KV Cache

Trace prompt prefill, autoregressive KV cache growth, continuous batching, and PagedAttention on live GPU pools.

AI & LLM Systems02. Inference & RetrievalLesson 1 of 2
10 minIntermediate6 steps

LLM Inference & KV Cache

Trace prompt prefill, autoregressive KV cache growth, continuous batching, and PagedAttention on live GPU pools.

TTFT (P95)
180 ms
Throughput
62 tok/s
GPU Util
14%
KV VRAM
6 GB
LLM KV-Cache & PagedAttention Lab2,048 ctx · Batch 1 · GQA
Phase 1/5
Phase 1: Parallel Prefill (Compute-Bound)COMPUTE-BOUND · 2,313 tok/s

All 2,048 prompt tokens process in one dense GEMM matrix multiply — Tensor Cores hit 92% compute utilization while populating initial K/V tensors.

80 GB H100 VRAM · KV Block Map (32 Blocks)38.7 / 80 GB (48%)
Weights: 38.0 GBActive KV: 0.3 GBWaste: 0.43 GB
R1
R1
reserved
reserved
reserved
reserved
reserved
reserved
reserved
reserved
reserved
reserved
reserved
reserved
reserved
reserved
reserved
reserved
reserved
reserved
reserved
reserved
reserved
reserved
reserved
reserved
reserved
reserved
reserved
reserved
reserved
reserved
Active Batch Slots & Hardware Bottleneck
Tensor Core Compute92%
HBM Memory Bandwidth44%
R1Prefill 819 tok
In This LessonStep 1 of 6
What You Will Master
  • ✓Distinguish compute-bound prompt prefill (TTFT) from memory-bandwidth-bound token decode (TPOT)
  • ✓Prevent GPU out-of-memory fragmentation using PagedAttention virtual KV blocks
  • ✓Multiply throughput by swapping static batching for iteration-level continuous batching
  • ✓Isolate long-prompt prefill spikes from streaming decode workers

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
Static BatchingOffline bulk document scoring with uniform prompt lengthsFast requests wait idle until the longest response in the batch finishes
Continuous BatchingInteractive chat APIs with highly variable output lengthsRequires iteration-level scheduler that swaps finished sequences every token step
PagedAttentionHigh-concurrency serving where KV cache dominates GPU HBMAdds block-table indirection, reclaiming 60%+ wasted contiguous memory
Prefill/Decode DisaggregationMixed workloads combining 32k-token RAG prompts with low-latency streamingTransfers KV cache state over high-speed RDMA/NVLink between worker pools

Step-by-Step Architectural Breakdown (6 Steps)

Full architectural walkthrough transcript and state transitions for LLM Inference & KV Cache.

STEP 01 · SETUPJump to step →

Single GPU Serving One Prompt at a Time

When a user sends a 2,000-token prompt to an LLM API, inference runs in two distinct phases: **Prefill** processes all input tokens in parallel to produce the first token, and **Decode** generates one token at a time autoregressively.

Without batching, a single H100 GPU spends most of the decode phase waiting on HBM memory bandwidth to read model weights—leaving Tensor Cores under 10% utilized.

idea:Prefill is compute-bound (matrix-matrix math); decode is memory-bandwidth-bound (streaming gigabytes of weights for one token).

Prefill PhaseDecode PhaseTTFTTPOT
STEP 02 · PROBLEMJump to step →

Static Batching & KV Cache Fragmentation

To raise GPU utilization, teams group 16 requests into a **static batch**. Because each prompt could grow up to 8,192 tokens, naive allocators pre-reserve huge contiguous KV cache slabs in VRAM.

Short 50-token answers sit trapped behind a 2,000-token essay, while pre-allocated memory slabs waste over 60% of precious GPU HBM and trigger premature OOM rejections.

watch:Reserving worst-case contiguous KV slabs caps max batch size long before GPU compute is actually full.

KV CacheStatic BatchingVRAM FragmentationHead-of-Line Stall
STEP 03 · SOLUTIONJump to step →

Continuous Batching + PagedAttention

Engines like vLLM and TensorRT-LLM split each request’s KV cache into fixed-size **virtual pages** (e.g., 16 tokens per block) mapped through a lightweight page table—just like OS virtual memory.

Paired with **iteration-level continuous batching**, the moment one request emits an EOS token, its pages are freed and a waiting prompt enters the GPU on the very next decode step.

good:PagedAttention cuts KV memory waste from >60% down to under 4%, letting the same GPU serve 4×–8× more concurrent streams.

PagedAttentionContinuous BatchingBlock TablePrefix Sharing
STEP 04 · TECHNIQUEJump to step →

Disaggregated Prefill & Decode Pools

When a single 64k-token PDF summary enters a shared GPU, its heavy prefill compute hijacks the GPU for 800 ms—causing every active chat user on that GPU to experience a visible streaming freeze (decode jitter).

Disaggregated serving splits the fleet into **Prefill Workers** (compute-optimized) and **Decode Workers** (bandwidth-optimized), transferring computed KV blocks across fast interconnect.

idea:Decoupling Prefill from Decode lets you scale TTFT and inter-token streaming smoothness independently.

Prefill PoolDecode PoolChunked PrefillInter-Token Latency
STEP 05 · TRADE-OFFJump to step →

Quantization & Speculative Decoding Trade-Offs

Compressing weights from FP16 to **FP8 or INT4** halves memory bandwidth per token and doubles KV cache room—at a tiny precision cost on hard coding or math tasks.

**Speculative decoding** runs a tiny draft model to propose 4–6 tokens ahead, then verifies them in a single parallel forward pass of the large target model—accelerating latency without changing output quality.

watch:Speculative decoding shines at low batch sizes (latency-critical UX), but loses efficiency when GPUs are already compute-saturated at high concurrency.

FP8 QuantizationSpeculative DecodingDraft ModelVerification Pass
STEP 06 · RECAPJump to step →

Production Inference Architecture Recap

High-throughput LLM serving is an exercise in **memory bandwidth and scheduling**. Start with continuous batching + PagedAttention, enable prefix caching for repeated system instructions, and isolate long prefills when streaming jitter appears.

good:Measure TTFT, TPOT, and KV cache utilization together—optimizing tokens/sec alone hides painful P99 time-to-first-token stalls.

Prefix CachingKV-Aware RoutingGPU UtilizationToken Economics

Related Production Deep-Dives & Simulators

Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h 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.