Architecture
Model serving capacity planning sizes GPU VRAM pools, continuous batching admission limits, autoscaling metrics, and N + 1 failover redundancy quantitatively from empirical prompt and decode token distributions rather than naive request counts—keeping peak KV-cache occupancy inside safe HBM limits so tail TTFT and TPOT latency never collapse under concurrency spikes.
Traditional stateless web backends scale simply on RPS x average handler CPU. LLM serving fails under that rubric along two independent hardware ceilings simultaneously: long-context prefills consume quadratic/dense compute FLOPs driving queuing spikes in Time-to-First-Token (TTFT), while long concurrent generations hold gigabytes of stateful KV-cache blocks in GPU HBM for multiple seconds per request, bounding maximum safe concurrency regardless of CPU idle headroom. Sizing clusters without empirical token CDFs (P50, P95, P99), prefix-sharing hit rates, and warm container boot times leads directly to cascading preemption storms under real bursts.
KV-Cache Block Allocator (Paged vs Contiguous)
1. KV-Cache Memory Equations and Queue Concurrency Sizing
Per-token Key-Value cache storage scales with transformer layer count , KV head count (GQA group count rather than query heads!), head dimension , and KV element bytes (2 for FP16/BF16, 1 for FP8):
Where adjusts resident context length for shared prefix hits (Radix / Automatic Prefix Caching). Applying Little's Law, steady-state sustainable arrival rate obeys , where keeping cluster KV block residency at <= 75% ensures queueing buffer against Poisson arrival bursts and long-tail decode streams.
Worked Cluster Sizing Scenario (Llama-3-70B FP8, 4x H100 80GB)
Suppose a cluster serves a 70B FP8 model (~71 GB weights spread across TP=2, i.e., 35.5 GB weights + 4.5 GB activations/overhead = 40 GB non-KV usage per 80 GB H100 -> leaving 80 GB total KV cache headroom per 2x H100 replica):
- Per-token KV cost (
80layers,GQA 8,d=128,FP16KV cache): (320 KB/token, or160 KBif quantized toFP8KV). - Workload Mix: P95 conversation consumes
4,000prompt tokens (50%shared prefix cache hit ->2,000unshared KV tokens) +500generated tokens =2,500net KV tokens =800 MBVRAM per stream (~781 MBrounded to16-token blocks). - Per
2x H100Replica Safe Concurrency (75%high-watermark): simultaneous streams. At mean4.5sgeneration duration, each replica drains cleanly (N + 1redundancy adds1warm standby replica to absorb single-node failure or rolling container drain without breaching SLA!).
2. Capacity, Replication, and Autoscaling Decisions
| Decision | Required evidence | Review trigger |
|---|---|---|
Size GPU VRAM pools using P95 effective sequence length + prefix-sharing ratio (<= 75% steady KV fill). | Production prompt/output CDF & APC hit telemetry | Context window limit raise or RAG top- jump |
Scale on vllm:num_requests_waiting & gpu_cache_usage_perc rather than Kubernetes CPU utilization. | P95 TTFT vs HPA trigger latency trace | Cold container weight load exceeds SLA (45–180s) |
Reserve explicit 20–30% headroom plus N + 1 replica availability for single-AZ/node failure drains. | Chaos worker termination drain drill during load | Peak seasonal traffic shift or pool contraction |
Favor Data Parallel replica scaling once TP satisfies latency & VRAM fit cleanly (TP=2/4 -> scale replicas). | Cross-batch TTFT/TPOT sweep across TP configs | Quantization upgrade (BF16 -> FP8) shrinking weight footprint |
3. Fleet & Headroom Sizer Implementation in Python
pythonimport mathfrom dataclasses import dataclass@dataclass(frozen=True)class WorkloadProfile:avg_prompt_tokens: intp95_output_tokens: intprefix_cache_hit_rate: floatmean_stream_duration_sec: floattarget_peak_rps: floatdef size_inference_fleet(model_weights_gb: float,gpu_vram_gb: float,tp_degree: int,kv_kb_per_token: float,workload: WorkloadProfile,safety_kv_watermark: float = 0.75,) -> dict[str, int | float]:"""Size replicas, safe max concurrency, and N+1 failover reserve from token distributions."""per_gpu_weight = model_weights_gb / tp_degreeusable_kv_gb = (gpu_vram_gb - per_gpu_weight - 4.5) * tp_degree # Reserve 4.5GB/GPU workspaceif usable_kv_gb <= 0:raise ValueError("Model weights + runtime workspace exceed GPU pool VRAM; increase TP")eff_tokens = workload.avg_prompt_tokens * (1.0 - workload.prefix_cache_hit_rate) + workload.p95_output_tokensstream_kv_gb = (eff_tokens * kv_kb_per_token) / (1024.0 * 1024.0)safe_concurrency = int((usable_kv_gb * safety_kv_watermark) // stream_kv_gb)replica_rps = safe_concurrency / max(0.5, workload.mean_stream_duration_sec)active_replicas = math.ceil(workload.target_peak_rps / max(0.1, replica_rps))return {"gpus_per_replica": tp_degree,"safe_concurrency_per_replica": safe_concurrency,"sustainable_rps_per_replica": round(replica_rps, 2),"active_replicas": active_replicas,"total_replicas_n_plus_1": active_replicas + 1,"total_gpus_provisioned": (active_replicas + 1) * tp_degree,}fleet = size_inference_fleet(model_weights_gb=71.0,gpu_vram_gb=80.0,tp_degree=2,kv_kb_per_token=320.0,workload=WorkloadProfile(4000, 500, 0.50, 4.5, 45.0),)assert fleet["total_replicas_n_plus_1"] >= 4
Decisions
| Decision | Required evidence | Review trigger |
|---|---|---|
| Size replicas using P95/P99 context/decode distributions + N+1 AZ headroom rather than averages. | KV occupancy histogram & load-test saturation point <= 80% | Context limit increase or reasoning traffic shift |
Autoscale strictly on vllm:gpu_cache_usage_perc and waiting queue depth instead of host CPU %. | Synthetic burst scale-out verifying zero OOM preemptions | Engine version upgrade or HPA webhook tuning |
Alternatives and trade-offs
- Smallest Viable Tensor Parallelism + Data-Parallel Replicas vs. Wide
TP=8: Smaller TP groups minimize intra-nodeall-reducesynchronization overhead and shrink hardware failure blast radius cleanly compared to monolithic 8-way TP instances.
Failure modes
- Sizing exclusively around uniform short averages: Mean generation length (
250tokens) masks a heavy tail (10%deep reasoning traces emitting4,000tokens) that silently monopolizes65%of total KV blocks under burst concurrency. - Counting cold containers in ready autoscaling capacity: Downloading/loading
70 GB–140 GBshards into VRAM takes60–180s(even off local NVMe caches); traffic spikes collapse queues well before Kubernetes HPA boots cold pods unless warm buffers or pre-cached NVMe DaemonSets are provisioned. - Client retry storms multiplying overload: Unbounded gateway retries re-inject timed-out
32kprefill prompts back onto saturated schedulers, guaranteeing preemption livelock unless ingress admission rejects cleanly atHTTP 429once waiting queues breach SLA deadlines. - Over-provisioning
TP=8unnecessarily whenTP=2suffices: Splitting a quantized model across8GPUs adds unnecessaryNVLink all-reducesynchronization overhead per layer and turns1failing GPU into an8-GPU blast radius rather than isolated smaller DP replicas.
Operational checklist
- Empirical
P50/P95/P99prompt length, output length, and prefix sharing histograms updated monthly. - Ingress admission limits enforce explicit waiting-queue deadlines (
HTTP 429) cleanly ahead of GPU OOM preemption. - Autoscalers read
vllm:gpu_cache_usage_percand waiting queue depth instead of host CPU %. - Scale-down
preStophooks wait for active SSE decode streams to flush cleanly before terminating containers. - Cold weight start times (
image + model load) measured realistically inside failover capacity models.
Connected Practice
- Labs: /labs/inference-batching-queueing, /labs/cost-latency-reliability
- Projects: /projects/inference-cost-latency-project
- System breakdowns: /systems/inside-vllm
Sources
- Serving capacity primary references:
vllm-paper,vllm-v0102-scheduler,kubernetes-resource-management,kubernetes-hpa
Step through live KV-cache block paging
Inspect virtual-to-physical VRAM page tables, Copy-on-Write forks, and internal fragmentation in the PagedAttention simulator.
Subscribe to Engineering Briefings
Join AI systems engineers receiving architecture teardowns, benchmark notes, and new simulator releases. Unsubscribe anytime.
