Careers Post-AI
AI infrastructure and systems: all chapters

AI infrastructure and systemsPart 2: Inference serving

Chapter 8Scaling and routing inference

30 min read, 1 lab, Advanced

A web service that gets ten times its usual traffic adds pods in seconds. An LLM service under the same spike can take ten minutes to add one replica, because it needs a GPU node, a 10 GB container image and tens of gigabytes of weights before it serves a single token. This chapter covers how to scale, route and protect inference fleets given that reality, with the Kubernetes tools teams use in late 2026.

After this chapter you can

  • Explain why GPU inference scales differently from stateless web services and break down a cold start.
  • Choose autoscaling signals that track real load, such as queue depth and concurrency, instead of CPU.
  • Describe KServe, KEDA, the Gateway API Inference Extension and llm-d, and where each fits.
  • Compare round-robin, least-pending and cache-aware load balancing.
  • Design admission control, priority, multi-model and LoRA serving, and multi-region failover.
  • Deploy an autoscaled model server on a local cluster and measure its scale-up lag.

Why GPU services scale differently

Three properties break web-scaling instincts. Replicas are expensive (one GPU node can cost more per hour than a whole web tier), so you cannot over-provision freely. Capacity per replica is bounded by KV cache memory rather than CPU, so a replica can be "full" at low utilization numbers. And starting a replica is slow, because a cold start is mostly moving bytes.

The ranges above are typical orders of magnitude, not guarantees; measure your own. Each stage has a standard mitigation:

StageMitigation
Node provisioningKeep a warm pool of GPU nodes, or reserve capacity
Image pullSmaller images, pre-pulled on nodes, local registry mirror
Weights downloadCache weights on node-local NVMe or a shared volume; stream from object storage in parallel
Load and warm-upPre-quantized weights, fewer GPUs per replica, keep a minimum replica count

Because scale-up is slow, the real job of autoscaling here is to start early and to protect the existing replicas while new ones arrive.

Autoscaling signals

The Kubernetes Horizontal Pod Autoscaler (HPA) computes a desired replica count from a metric and a target:

desired_replicas = ceil(current_replicas x current_metric / target_metric)

The formula is only as good as the metric. CPU is nearly useless for GPU serving: the CPU side mostly waits on the GPU. GPU "utilization" from the driver measures whether any kernel was running, not how much work it did, so it reads near 100 percent at both light and heavy load.

SignalExample (vLLM metric name)Good for
Queue depthvllm:num_requests_waitingScaling up: work is waiting, users are feeling it
Running requestsvllm:num_requests_runningScaling by concurrency target per replica
KV cache usevllm:kv_cache_usage_percEarly warning before queueing starts
Latencyp95 of vllm:time_to_first_token_secondsSLO guardrail; lags too much to drive scaling alone
Generated tokens per secondrate of vllm:generation_tokens_totalCapacity planning and cost per token

Metric names change between engine versions (older vLLM used gpu_cache_usage_perc), so check the /metrics endpoint of the version you run. A sound default is to scale on queue depth plus running requests per replica, with a target you found by load testing one replica to the edge of its latency SLO.

Kubernetes building blocks

Several projects divide this problem among themselves. Names and maturity as of late 2026:

ProjectRoleStatus
KServeModel serving platform: InferenceService for general models and LLMInferenceService for LLMsCNCF incubating since late 2025
KEDAEvent-driven autoscaler that feeds external metrics (Prometheus, queues) into the HPA and supports scale to zeroCNCF graduated, widely used
Gateway API Inference ExtensionKubernetes SIG project that turns a Gateway into an inference-aware load balancer with InferencePool and an endpoint pickerInferencePool is GA at v1; objectives API still alpha
llm-dDistributed serving stack built on vLLM and the inference extension: cache-aware routing, disaggregated prefill and decodeCNCF sandbox since March 2026
NVIDIA DynamoNVIDIA's datacenter-scale serving layer with KV-aware routing over vLLM, SGLang or TensorRT-LLMProduction 1.x releases

The Gateway API Inference Extension changes how requests reach model servers. An InferencePool groups the model-server pods, and an endpoint picker (EPP) chooses a pod for each request using live signals from the servers rather than a plain hash.

Load balancing strategies

Round robin assumes requests cost about the same. LLM requests vary by a factor of a hundred or more in prompt and output length, so round robin regularly sends new work to a replica already holding a long queue.

Least pending

  • Send to the replica with the fewest queued plus running requests, or least KV use.
  • Evens out load and tail latency.
  • Ignores what is already cached where.

Cache-aware

  • Send to the replica that already holds the longest matching prompt prefix.
  • Skips prefill, which cuts TTFT and GPU work.
  • Can pile popular prefixes onto one hot replica.

Production routers blend the two: score each replica on prefix overlap and on load, and stop favouring cache hits once a replica's queue grows past a threshold. A simpler approximation is consistent hashing on a session or conversation ID with a load cap, which keeps multi-turn chats on the replica holding their history. The same scoring idea extends to LoRA adapters, where you prefer replicas that already have the adapter loaded.

Queues, priority and admission control

When demand exceeds capacity, something waits or something is refused. Deciding which is admission control, and leaving it to chance means everyone's latency degrades together.

  1. Bound the queue

    Give each replica, or the gateway, a maximum queue length or maximum expected wait. Beyond that, return HTTP 429 or 503 with a Retry-After header instead of accepting work you will finish too late to matter.

  2. Classify by priority

    Separate interactive traffic from batch work such as evaluations, summarisation backfills and embeddings. Interactive requests jump the queue; batch jobs fill idle capacity and are the first to be shed.

  3. Limit by tokens, not just requests

    One request with a 100,000-token prompt can cost more than a thousand short ones. Rate-limit tenants on input plus maximum output tokens, and cap max_tokens server-side.

  4. Degrade gracefully

    Under sustained overload, route lower-priority traffic to a smaller model, shorten maximum output, or turn off expensive features before refusing requests outright.

Multi-model and LoRA adapter serving

Real platforms serve many models, and most have a long tail of rarely used ones. Giving each its own always-on GPU replica wastes most of the fleet.

PatternHow it worksTrade-off
Dedicated pool per modelEach popular model gets its own autoscaled deploymentSimple and isolated; wasteful for rare models
Scale to zeroRare models have zero replicas until a request arrivesCheap; the first user waits a full cold start
Model multiplexingOne server swaps models in and out of memoryGood for small models; swaps cost seconds or more
Multi-LoRAOne base model with many small fine-tuned adapters loaded per requestDozens of variants on one GPU; all must share a base model

Multi-LoRA is the standout for fine-tuned fleets. A LoRA adapter (see the chapter on fine-tuning systems) is often tens of megabytes against a base of many gigabytes, and engines batch requests for different adapters together. In vLLM, --enable-lora with --max-loras sets how many adapters can be active in one batch, and clients pick an adapter by passing its name as the model field.

vllm serve meta-llama/Llama-3.1-8B-Instruct --enable-lora --max-loras 8 \
  --lora-modules support-bot=/adapters/support legal-summary=/adapters/legal

Multi-region inference

GPU capacity, not user latency, is usually what pushes inference into several regions: the GPU type you need may simply be unavailable in your primary region at peak. A few seconds of generation time also dwarfs cross-region network latency, so routing a user to a distant region with free capacity is often the right call.

  • Route on capacity and queue depth first, then on network distance.
  • Replicate weights and images to every region ahead of time; a cross-region weight download during an incident is a long outage.
  • Keep enough warm capacity in a failover region to absorb the traffic while it scales, or accept shedding batch traffic during failover.
  • Respect data residency: some tenants' prompts may not leave a jurisdiction, which constrains routing.
  • Prefix caches are per replica and per region, so failover also means a TTFT spike while caches rebuild.

Key terms

Cold start
The time from deciding to add a replica to that replica serving traffic, dominated by provisioning and moving images and weights.
Horizontal Pod Autoscaler
The Kubernetes controller that changes a workload's replica count to keep a metric near its target.
KEDA
Kubernetes Event-driven Autoscaling, which feeds external metrics such as Prometheus queries into the HPA and can scale to zero.
InferencePool
A Gateway API Inference Extension resource that groups model-server pods behind an inference-aware endpoint picker.
Endpoint picker
The component that chooses a model-server pod per request using live load, cache and adapter signals.
Cache-aware routing
Sending a request to the replica that already holds the KV cache for the longest part of its prompt.
Admission control
Deciding whether to accept, queue, degrade or reject a request based on current capacity and priority.
Multi-LoRA serving
Serving many LoRA adapters on one shared base model, batching requests for different adapters together.
Lab

Autoscale a model server on Kubernetes and measure scale-up lag

Advanced, 90 min

Goal: run llama.cpp's server on a local kind cluster, autoscale it with KEDA on a Prometheus metric of in-flight requests, load it, and record each stage of the scale-up timeline.

You need: macOS or Linux with Docker (Docker Desktop with at least 4 CPUs and 8 GB memory allocated, or Docker Engine on Linux; WSL2 works on Windows), plus kind, kubectl and helm. On macOS: brew install kind kubectl helm. Everything here runs on your own machine.

  1. Create a cluster and install Prometheus (trimmed to the server only, scraping every 15 seconds) and KEDA.
kind create cluster --name infer
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo add kedacore https://kedacore.github.io/charts
helm repo update
helm install prometheus prometheus-community/prometheus -n monitoring --create-namespace \
  --set alertmanager.enabled=false --set prometheus-pushgateway.enabled=false \
  --set prometheus-node-exporter.enabled=false --set kube-state-metrics.enabled=false \
  --set server.persistentVolume.enabled=false --set server.global.scrape_interval=15s
helm install keda kedacore/keda -n keda --create-namespace
kubectl get pods -A

Wait until kubectl get pods -A shows the Prometheus server and KEDA pods Running.

  1. Deploy the model server. An init container downloads the GGUF file into each new pod, so every scale-up pays a realistic weights-download cost. The annotations tell Prometheus to scrape /metrics, and the readiness probe keeps traffic away until the model is loaded.
llm.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: llm
spec:
  replicas: 1
  selector:
    matchLabels:
      app: llm
  template:
    metadata:
      labels:
        app: llm
      annotations:
        prometheus.io/scrape: "true"
        prometheus.io/port: "8080"
        prometheus.io/path: "/metrics"
    spec:
      initContainers:
        - name: fetch-model
          image: curlimages/curl:latest
          command: ["sh", "-c"]
          args:
            - curl -fL -o /models/model.gguf https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct-GGUF/resolve/main/qwen2.5-0.5b-instruct-q4_k_m.gguf
          volumeMounts:
            - name: models
              mountPath: /models
      containers:
        - name: server
          image: ghcr.io/ggml-org/llama.cpp:server
          args: ["-m", "/models/model.gguf", "--host", "0.0.0.0", "--port", "8080",
                 "-np", "2", "-c", "4096", "-t", "2", "--metrics"]
          ports:
            - containerPort: 8080
          readinessProbe:
            httpGet:
              path: /health
              port: 8080
            periodSeconds: 5
          resources:
            requests:
              cpu: "1"
              memory: 1Gi
            limits:
              memory: 2Gi
          volumeMounts:
            - name: models
              mountPath: /models
      volumes:
        - name: models
          emptyDir: {}
---
apiVersion: v1
kind: Service
metadata:
  name: llm
spec:
  selector:
    app: llm
  ports:
    - port: 8080
      targetPort: 8080
kubectl apply -f llm.yaml
kubectl rollout status deploy/llm --timeout=10m

Note how long this first rollout takes: image pull, model download and load. That is your baseline cold start.

  1. Add the autoscaler. KEDA queries Prometheus for in-flight plus queued requests across all pods and targets an average of 2 per replica, matching the 2 slots per pod.
scaledobject.yaml
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: llm
spec:
  scaleTargetRef:
    name: llm
  minReplicaCount: 1
  maxReplicaCount: 4
  pollingInterval: 10
  advanced:
    horizontalPodAutoscalerConfig:
      behavior:
        scaleDown:
          stabilizationWindowSeconds: 120
  triggers:
    - type: prometheus
      metadata:
        serverAddress: http://prometheus-server.monitoring.svc.cluster.local
        query: "sum(llamacpp:requests_processing) + sum(llamacpp:requests_deferred)"
        threshold: "2"
kubectl apply -f scaledobject.yaml
kubectl get scaledobject llm
kubectl get hpa

Expect READY True on the ScaledObject and an HPA named keda-hpa-llm showing a current value near 0.

  1. Generate load from inside the cluster with six parallel workers for five minutes. In-cluster load matters: kubectl port-forward would pin every request to a single pod.
load.yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: load
spec:
  parallelism: 6
  completions: 6
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: load
          image: curlimages/curl:latest
          command: ["sh", "-c"]
          args:
            - |
              end=$(( $(date +%s) + 300 ))
              while [ $(date +%s) -lt $end ]; do
                curl -s -o /dev/null -w "%{http_code} %{time_total}\n" http://llm:8080/v1/chat/completions \
                  -H "Content-Type: application/json" \
                  -d '{"model":"qwen","max_tokens":256,"messages":[{"role":"user","content":"Write a long story about a lighthouse keeper."}]}'
              done

In one terminal watch pods with timestamps, in a second watch the HPA, then start the load in a third and note the time.

kubectl get pods -l app=llm -w | while read -r line; do echo "$(date +%T) $line"; done
kubectl get hpa keda-hpa-llm -w | while read -r line; do echo "$(date +%T) $line"; done
date; kubectl apply -f load.yaml
  1. Reconstruct the timeline from events. Record when load started, when the HPA desired count changed, when each new pod was scheduled, when its init container finished and when it became ready.
kubectl get events --sort-by=.lastTimestamp | grep -E "llm|keda-hpa"
kubectl logs -l job-name=load --prefix --tail=10

You should see desired replicas climb to 3 within about a minute of load starting (scrape interval plus KEDA polling plus the HPA sync), then each new pod spend most of its startup in the fetch-model init container. During that window the first pod's requests_deferred stays high and request times in the load logs stretch out. After the Job ends, replicas fall back to 1 once the stabilization window passes.

Check your work: a SCALING.md table with timestamps for each stage and the total lag from load start to the last new pod ready, split into "decision lag" (metric to new desired count) and "startup lag" (pod created to ready). On a laptop, startup lag should dominate.

Stretch: cut the startup lag. Replace the per-pod download with a shared cache (a hostPath volume on the kind node, or a PersistentVolumeClaim populated once), rerun the test and compare. Then add a second trigger on p95 request latency and explain which trigger fires first and why.

Check yourself

An HPA scales a vLLM deployment on CPU utilization. During a traffic spike, users see multi-second TTFT but no new replicas appear. Why?

Your scale-up timeline shows 20 seconds of decision lag and 6 minutes of startup lag, mostly downloading weights. Which change helps most?

A chat product sends multi-turn conversations with long shared system prompts. Replicas are behind a round-robin Service. What does switching to cache-aware routing with a load cap mainly improve?

During an overload, a nightly evaluation job and live customer chat share one inference pool, and chat latency triples. Which design fixes the root cause?

A company has 40 customer-specific fine-tunes of the same 8B base model, most used a few times an hour. What is the most efficient serving pattern?

Recap

  • GPU replicas are expensive, memory-bound and slow to start, so cold starts are mostly about moving images and weights.
  • Autoscale on queue depth and in-flight requests per replica, never on CPU or raw GPU utilization.
  • KServe, KEDA, the Gateway API Inference Extension and llm-d each own a layer: platform, autoscaling, routing and distributed serving.
  • Least-pending routing balances load; cache-aware routing saves prefill; good routers blend both with a load cap.
  • Bounded queues, priority classes and token-based limits decide who waits while new capacity starts.
  • Multi-LoRA and scale to zero handle long tails of models, and multi-region routing follows GPU capacity first.

Go deeper