Pidoku

Deploying on Kubernetes

Module 19 Lesson 19.e 45 min Difficulty 3/5

Prerequisites 21.c, 16.b, 19.c, 19.d


Before you start: words you need#

WordPlain meaning
PodThe smallest unit Kubernetes runs: one or more containers scheduled together on one machine (21.c).
ProbeA check Kubernetes runs against a container. Startup: has it finished starting? Liveness: is it dead? Readiness: should it get traffic?
/dev/shmShared memory: an in-RAM file system processes use to pass data quickly. Containers get only 64 MiB by default.
Grace periodterminationGracePeriodSeconds: how long Kubernetes waits after SIGTERM (the “please stop” signal) before killing a container.
Gateway / inference routerThe component in front of the pods that chooses which pod gets each request (21.i).
AutoscalerA controller that adds or removes pods based on a metric (HPA, KEDA) (23.d).
Cold startThe time from “start a pod” to “pod serving traffic”.

1. What is it?#

Running vLLM on Kubernetes so that it starts reliably, receives traffic sensibly, scales on the right signal and shuts down without cutting users off.

A vLLM pod is an unusual Kubernetes citizen:

  • it takes minutes to start;
  • it holds state that makes replicas unequal: each has its own prefix cache;
  • it is saturated long before its CPU or memory graphs say so; and
  • losing it discards every request in flight.

A Deployment with default probes and a round-robin Service runs, and is wrong in each of those four ways. This lesson lists what to configure differently, why, in terms of internals you now know, and the projects that build the cluster-level layer. Kubernetes for GPUs in general is 21.c; this lesson is the vLLM-specific part. Facts checked on 12 November 2026 against vLLM v0.32.0.

flowchart LR
  U[":i-users: Clients"] --> GW[":envoyproxy: <b>Gateway + inference router</b><br/><small>prefix- and load-aware</small>"]
  GW --> P1[":vllm: <b>vLLM pod</b><br/><small>prefix cache A</small>"]
  GW --> P2[":vllm: <b>vLLM pod</b><br/><small>prefix cache B</small>"]
  GW --> P3[":vllm: <b>vLLM pod</b><br/><small>starting: 3 min</small>"]
  P1 -.->|"/metrics, KV events"| GW
  P2 -.-> GW
  P1 --- PVC[(":i-hard-drive: <b>Shared volume</b><br/><small>weights,<br/>compile cache</small>")]
  P2 --- PVC
  P3 --- PVC
  AS[":keda: <b>Autoscaler</b><br/><small>on queue depth, not GPU %</small>"] -.-> P3
  PR[":prometheus: Prometheus"] -.-> AS
  P1 -.-> PR
  class U neutral
  class GW queue
  class P1,P2 compute
  class P3 warn
  class PVC memory
  class AS,PR io

2. Why does it matter?#

The failure modes are expensive and common:

  • A liveness probe that fires during model loading puts the pod into a restart loop that never serves a request.
  • Round-robin routing over R replicas gives each conversation a 1-in-R chance of finding its cached history, so adding replicas lowers the cache hit rate.
  • Autoscaling on GPU utilisation never scales, because a busy GPU looks equally busy at one request and at its limit.
  • A rolling update with a 30-second grace period cuts off every long answer.

3. Simple analogy#

A web server is a vending machine: it starts instantly, every machine is identical, and you can swap one out mid-afternoon. A vLLM pod is a restaurant kitchen: it takes a long time to set up in the morning, each kitchen remembers its regulars (the prefix cache), and you do not close it while diners are still eating.


4. Tiny example: the probe that kills a healthy pod#

t = 0 s     pod starts; vLLM begins downloading 140 GB of weights
t = 30 s    livenessProbe: GET /health → connection refused (not listening yet)
t = 60 s    third failure → Kubernetes kills the container
            log ends: "KeyboardInterrupt: terminated"
t = 61 s    restart; download starts again from zero … forever

The fix is a startupProbe with a long allowance, shown in section 5.


5. Technical explanation#

The pod: five differences from a web service#

1. GPU and CPU. Request the GPUs, and give the pod enough CPU for its processes: at least one physical core per process, so about 2 + N for one engine with N GPUs (16.d), more with several API servers or DP ranks. Set CPU requests equal to limits. A throttled engine core, its busy loop descheduled mid-step, shows up as lost throughput with an idle GPU, and it is the cause people find last.

2. Shared memory. The engine core and workers communicate through a shared-memory ring buffer, and v0.32.0 also broadcasts large multimodal tensors through a shared-memory arena (on by default). A container’s default 64 MiB /dev/shm is too small. Mount an in-memory volume:

YAML
volumes:
  - name: shm
    emptyDir: { medium: Memory, sizeLimit: "8Gi" }
containers:
  - volumeMounts:
      - { name: shm, mountPath: /dev/shm }

This is the Kubernetes equivalent of Docker’s --ipc=host, and is needed for tensor parallelism in particular.

3. Model storage. Downloading tens of gigabytes on every start is slow and can be rate-limited. Use a persistent volume at the Hugging Face cache path, a pre-populated node-local disk, or a streaming loader that reads straight from object storage (--load-format runai_streamer, tensorizer, fastsafetensors, instanttensor). Provide the hub token from a Secret.

4. The compile cache. Mount a volume at ~/.cache/vllm (VLLM_CACHE_ROOT), or bake it into the image. Otherwise every cold pod repeats torch.compile (18.d). v0.32.0 also offers vllm download-kernels to install FlashInfer’s precompiled kernels instead of compiling them at first use.

5. Probes. This is where default configurations fail.

Probes for a server that starts slowly#

vLLM does not listen on its port until the engine is fully initialised: weights loaded, memory profiled, cache allocated, model compiled, graphs captured. That takes from under a minute to many minutes. The documentation’s troubleshooting note: if “the startup or readiness probe failureThreshold is too low for the time needed to start up the server, Kubernetes scheduler will kill the container”, and the log contains KeyboardInterrupt: terminated.

Use three probes with distinct jobs:

YAML
startupProbe:                 # "has it finished starting?" — generous
  httpGet: { path: /health, port: 8000 }
  periodSeconds: 10
  failureThreshold: 90        # allow up to 15 minutes
livenessProbe:                # "is it dead?" — only after startup succeeded
  httpGet: { path: /health, port: 8000 }
  periodSeconds: 10
  failureThreshold: 3
readinessProbe:               # "should it receive traffic?"
  httpGet: { path: /health, port: 8000 }
  periodSeconds: 5

The startup probe holds the other two off until it passes. Measure real startup time and set the threshold at two to three times that.

What /health means matters. In v0.32.0 it returns 200 while the engine is up and 503 once the engine core has died (EngineDeadError, 16.d). It does not report overload: a saturated vLLM is healthy. Never use liveness to shed load.

Shutting down#

When a pod is deleted, Kubernetes sends SIGTERM and waits terminationGracePeriodSeconds (30 by default) before killing it.

vLLM’s own behaviour on shutdown is set by --shutdown-timeout (seconds, default 0):

  • 0 (default): the engine core aborts all in-flight requests at once and exits.
  • N > 0: the engine drains: it stops accepting new requests, lets running ones finish for up to N seconds, then aborts the rest.

So graceful shutdown on Kubernetes needs three settings that agree:

--shutdown-timeout          ≥ your longest expected response (say 300)
terminationGracePeriodSeconds  > shutdown-timeout (say 330)
rolling update               maxUnavailable: 0, and the router stops sending first

Why round-robin is the wrong load balancer#

Two properties break the assumption that replicas are interchangeable.

Each replica has its own prefix cache. A conversation’s second turn sent to a different replica recomputes the whole history. With round-robin over R replicas, the chance of landing on the right one is 1/R.

Requests are wildly unequal. One is 50 tokens, the next 50,000. Counting requests or connections says nothing about load.

A router that understands this uses what the pods publish:

SignalSourceUsed for
vllm:num_requests_waiting, num_requests_running/metricsAvoid replicas that are queueing
vllm:kv_cache_usage_perc/metricsAvoid replicas about to preempt
KV events (BlockStored, BlockRemoved)--kv-events-configKnow which replica holds which prefix (19.b)
The prompt’s block hashesComputed by the router from token IDsMatch a request to a replica’s cache (21.h)

The cluster-level layer#

vLLM deliberately stops at one model per server. Several projects supply the rest; the documentation lists more than a dozen integrations.

ProjectWhat it adds
llm-dA CNCF Sandbox project since March 2026 (founded by Red Hat, Google Cloud, IBM Research, CoreWeave and NVIDIA), built around vLLM: prefix-aware routing from KV events, tiered cache offloading, prefill/decode disaggregation over NIXL, wide expert parallelism, autoscaling on inference signals. v1.0.0 on 20 October 2026.
Gateway API Inference ExtensionThe Kubernetes standard for model-aware routing (InferencePool, v1 since its 1.0 release; v1.6.2 in September 2026), implemented by Envoy-based and other gateways
vLLM production-stackA Helm chart from the vLLM organisation: a router with model- and prefix-aware routing, Grafana dashboards, KV offloading through LMCache
AIBrixAlso from the vLLM organisation: LoRA management, autoscaling, distributed KV cache
KServe, KubeRay, LeaderWorkerSetGeneral model serving and multi-node orchestration with vLLM as the runtime
NVIDIA DynamoA distributed serving framework that can use vLLM as its engine (21.j)

For multi-node single-replica deployments (TP plus PP across machines, or wide EP), LeaderWorkerSet provides the “one leader pod plus N worker pods that start and stop together” primitive a plain Deployment lacks.

Autoscaling#

GPU utilisation is the wrong signal: a GPU serving one request shows high utilisation, and one at its real limit shows the same (22.d). Scale on what saturation looks like:

SignalScale up when
vllm:num_requests_waitingSustained above a small number per replica
p95 of vllm:request_queue_time_secondsAbove a fraction of your TTFT target
vllm:kv_cache_usage_percSustained above about 0.9
vllm:admission_rejections / 503 rateAdmission control is rejecting

The other half is lead time. A new replica helps only once it has started, and that takes minutes, so scaling from the current queue is always late. Headroom must cover the traffic that arrives while a pod boots; the program in section 6 computes it.

Ways to shorten the boot:

TechniqueWhat it removes
Weights on a fast local or shared volume, or a streaming loaderDownload
Persisted compile cache; vllm download-kernelstorch.compile and kernel JIT
-O1, or fewer CUDA graph sizesCapture time, at some run-time cost
Sleep mode (--enable-sleep-mode)Everything, for a pod kept alive: level 1 moves weights to CPU RAM and discards the KV cache; level 2 discards both. Waking from level 1 takes seconds.
vllm preloadWeight loading across engine restarts: a daemon per GPU keeps the sharded, quantised weights resident and hands them over by CUDA IPC. CUDA and ROCm; TP, EP and DP but not PP.
Initialized snapshots (experimental)Initialisation itself, via a CRIU checkpoint on the same machine. Currently one NVIDIA GPU, TP 1, root, plaintext HTTP only.

6. Under the hood: probe thresholds and headroom#

From measured boot phases, compute a safe startup probe and how many spare replicas a traffic ramp needs.

Go
// boot.go — startup-probe thresholds and autoscaling headroom from measured boot times.
package main

import (
	"fmt"
	"math"
)

func main() {
	// --- Measured for one pod (seconds) ---
	phases := []struct {
		name       string
		cold, warm float64 // warm = weights on local disk, compile cache present
	}{
		{"schedule pod + pull image", 45, 15},
		{"download weights", 240, 0},
		{"load weights to GPU", 40, 40},
		{"profile + create KV cache", 8, 8},
		{"torch.compile", 70, 6},
		{"capture CUDA graphs", 25, 25},
	}
	var cold, warm float64
	fmt.Printf("%-28s %8s %8s\n", "phase", "cold", "warm")
	for _, p := range phases {
		fmt.Printf("%-28s %7.0fs %7.0fs\n", p.name, p.cold, p.warm)
		cold += p.cold
		warm += p.warm
	}
	fmt.Printf("%-28s %7.0fs %7.0fs\n\n", "total", cold, warm)

	const period = 10.0
	for _, c := range []struct {
		name string
		t    float64
	}{{"cold", cold}, {"warm", warm}} {
		threshold := math.Ceil(2.5 * c.t / period)
		fmt.Printf("startupProbe (%s start): periodSeconds %.0f, failureThreshold %.0f  (allows %.0f s)\n",
			c.name, period, threshold, threshold*period)
	}

	// --- Autoscaling headroom ---
	const (
		perReplica = 12.0 // requests/s one replica sustains within the SLO (from a benchmark)
		current    = 60.0 // requests/s now
		growth     = 0.25 // traffic grows this fraction per minute during a ramp
	)
	fmt.Printf("\ntraffic %.0f req/s, growing %.0f%%/min, one replica handles %.0f req/s\n",
		current, growth*100, perReplica)
	fmt.Printf("%-12s %14s %18s %16s\n", "boot time", "traffic by then", "replicas needed", "spare to hold now")
	for _, boot := range []float64{warm, cold} {
		future := current * math.Pow(1+growth, boot/60)
		need := math.Ceil(future / perReplica)
		now := math.Ceil(current / perReplica)
		fmt.Printf("%9.0f s %12.0f r/s %18.0f %16.0f\n", boot, future, need, need-now)
	}
}

Output:

phase                            cold     warm
schedule pod + pull image         45s      15s
download weights                 240s       0s
load weights to GPU               40s      40s
profile + create KV cache          8s       8s
torch.compile                     70s       6s
capture CUDA graphs               25s      25s
total                            428s      94s

startupProbe (cold start): periodSeconds 10, failureThreshold 107  (allows 1070 s)
startupProbe (warm start): periodSeconds 10, failureThreshold 24  (allows 240 s)

traffic 60 req/s, growing 25%/min, one replica handles 12 req/s
boot time    traffic by then    replicas needed spare to hold now
       94 s           85 r/s                  8                3
      428 s          295 r/s                 25               20

How to read it:

  • The cold start of about seven minutes needs a startup probe that tolerates about eighteen. Download dominates; a pre-populated volume removes it.
  • Headroom follows boot time. During a 25%-per-minute ramp, a warm start needs 3 spare replicas running now; a cold start needs 20. Every second removed from startup is capacity you no longer keep idle.

7. Performance implications#

  • CPU throttling shows as an idle GPU and uneven inter-token latency. Requests equal to limits; no CPU-sharing with noisy neighbours.
  • Routing decides the cache hit rate. Prefix-aware routing can matter more for TTFT than any engine flag on multi-turn workloads.
  • Network for multi-node pods. RDMA for EP or disaggregation usually needs hostNetwork, privileged pods and ulimit -l unlimited (19.a, 19.b).
  • Fewer, larger pods vs more, smaller ones. Larger TP per pod is fewer replicas to route between, but each failure loses more capacity.

8. Production implications#

A deployment checklist:

  • CPU: at least 2 + N physical cores per engine, requests equal to limits.
  • /dev/shm as an in-memory volume.
  • Weights and compile cache on persistent or pre-populated storage.
  • startupProbe sized to two or three times measured startup.
  • --shutdown-timeout and terminationGracePeriodSeconds covering your longest response; maxUnavailable: 0.
  • A gateway in front. --api-key does not protect every route; never expose development endpoints. v0.32.0 no longer allows every CORS origin by default; set --allowed-origins for browser clients.
  • --allowed-media-domains if the model accepts media URLs.
  • Admission limits set from a benchmark (19.d).
  • Metrics scraped; alerts on queue time, preemptions, admission rejections and /health 503s.
  • Routing that is at least load-aware, and prefix-aware if conversations are long.
  • Autoscaling on queue signals, with headroom for boot time.

9. Common mistakes#

  1. A liveness probe without a startup probe. Restart loop during loading.
  2. Leaving --shutdown-timeout at 0 and expecting Kubernetes’ grace period alone to protect in-flight requests. vLLM aborts them immediately.
  3. Default /dev/shm. Tensor-parallel pods fail or crawl.
  4. Round-robin Services for multi-turn chat.
  5. Autoscaling on GPU utilisation.
  6. CPU limits far below requests’ needs, or no CPU request at all.
  7. Downloading weights on every start from the public hub.

10. Hands-on exercise#

  1. Run boot.go with phase timings from your own cluster. What is your cold-to-warm ratio, and which phase dominates?
  2. With traffic growing 50% per minute, how many spare replicas does a cold start require? At what growth rate does scale-from-zero become impossible within your SLO?
  3. Deploy two replicas behind a round-robin Service and send a 20-turn conversation. Read usage.prompt_tokens_details.cached_tokens on each turn. Repeat with session affinity on a conversation ID.
  4. Start a pod with --shutdown-timeout 120, begin a long streaming request, delete the pod and watch the log’s [shutdown] lines. Repeat with the default.

11. Interview questions#

  1. Why does a liveness probe with a 30-second initial delay put a vLLM pod into a restart loop?
  2. What does vLLM do with in-flight requests on SIGTERM by default, and how do you change it?
  3. Why does adding replicas behind a round-robin balancer reduce the prefix-cache hit rate?
  4. Name two signals better than GPU utilisation for autoscaling, and say what each indicates.
  5. Compare sleep mode, vllm preload and a persisted compile cache: which part of cold start does each remove?

12. Further reading#

Checked on 12 November 2026 against vLLM v0.32.0.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in