This deep dive is Chapter 9, Production LLM Serving Stack, from Fuheng Wu’s book Distributed AI Systems, published by Packt, which also publishes Deep Engineering. All the code for this chapter is in the book’s GitHub repository.
Fuheng Wu walks through the full path from a single model runner on one GPU to a production LLM serving stack on Kubernetes. After completing this chapter and the exercises in the last part, you should be able to:
Build API gateways that route requests to multiple model backends
Implement rate limiting to protect services from overload
Deploy canary releases with automated rollback capabilities
Instrument distributed systems with OpenTelemetry for observability
Deploy and manage LLM serving infrastructure on Kubernetes
Design production-ready serving systems with proper monitoring and fault tolerance
Let’s get started.
Everything fails all the time.
Werner Vogels, CTO of Amazon
Anatomy of a production LLM serving system
In the previous chapters, we explored how to train large models at scale using distributed techniques like DDP, FSDP, DeepSpeed, and Megatron-LM. We also examined inference engines like vLLM and SGLang that optimize single-node and multi-node inference. Now it’s time to put these pieces together into a complete production system.
AI model serving encompasses a broad spectrum of workloads. Traditional machine learning models—gradient boosted trees, linear models, and small neural networks—are typically served on CPUs with frameworks like TensorFlow Serving or Triton Inference Server. Computer vision models for image classification or object detection can also run efficiently on CPUs using optimized runtimes like ONNX Runtime, which has powered production CV workloads for years; GPUs are only necessary for the larger models or when throughput requirements are higher. These workloads have relatively predictable latency since input sizes are fixed. Diffusion models for image generation (Stable Diffusion, DALL-E) present unique challenges with their iterative denoising process, requiring careful batching strategies and often benefiting from techniques like classifier-free guidance caching.
LLM serving, however, has its own distinct characteristics that set it apart from these other workloads. The autoregressive nature of text generation means that output length is unpredictable—a simple “yes” or “no” question might generate 2 tokens, while a code generation request might produce 2,000. This variability makes batching and resource allocation fundamentally different from fixed-output models. The KV cache grows linearly with sequence length, creating memory pressure that doesn’t exist in traditional ML serving. And the streaming nature of chat applications means users expect to see tokens as they’re generated, not just a final response.
This chapter focuses specifically on LLM serving, building on the inference engines we covered in Chapters 6 and 7. The architectural patterns we discuss—routing, load balancing, observability—apply broadly to AI serving, but the specific implementations and trade-offs are tailored to the unique demands of large language models.
A production LLM serving system is more than just a model running on a GPU. It’s a complex distributed system with multiple components working together to provide reliable, scalable, and cost-effective inference services. Understanding this architecture is essential before diving into specific deployment strategies.
A typical production serving stack includes the following components:
API Gateway. The gateway sits between clients and the backend services, handling request routing, authentication, rate limiting, and load balancing. It’s the single entry point that abstracts away the complexity of multiple model runners and routing decisions.
Model Runner. This is the heart of the system: a stateful, GPU-backed inference engine that manages model loading, KV cache, and continuous batching. In production, you’ll typically use vLLM or SGLang (covered in Chapters 6 and 7) as the model runner, but the architectural principles apply regardless of which engine you choose.
Monitoring and Observability. Production systems need visibility into what’s happening. Rather than a standalone service, observability is typically integrated into each component through instrumentation libraries. This includes metrics collection (typically exported to Prometheus), distributed tracing (OpenTelemetry), and structured logging. Without observability, debugging production issues becomes nearly impossible.
Tokenizer Service (optional). A stateless, lightweight service that handles text tokenization and detokenization. Modern inference engines like vLLM handle tokenization internally, so a separate tokenizer service is less common. It can be useful for counting tokens before inference (for billing or rate limiting), validating input length, or when using custom inference backends.
Figure 9.1 shows how these components fit together. Clients send requests to the API Gateway, which routes them to the appropriate model runner based on the requested model and current load. All components report metrics and traces to the observability stack.
A simplified implementation is available in code/basic/. The examples use Qwen2.5-1.5B-Instruct as the default model, which runs comfortably on most GPUs with 8GB+ VRAM. For even smaller footprints, you can substitute Qwen2.5-0.5B-Instruct or TinyLlama-1.1B-Chat by modifying the model name in the code.
To try them out, first install the dependencies. We tested with the following versions in a conda environment:
conda create -n usao python=3.12
conda activate usao
pip install fastapi==0.133.1 uvicorn==0.35.0 httpx==0.28.1 \
pydantic==2.12.5 transformers==4.57.3 vllm==0.15.1Your environment may require different versions—adjust as needed for compatibility with your CUDA and PyTorch setup.
If you encounter a 401 Client Error or 403 Forbidden when downloading models, you need to set your Hugging Face token:
export HF_TOKEN=your_huggingface_tokenYou can get a token from huggingface.co/settings/tokens. Some models require accepting license agreements on their model page before access is granted.
Start the model runner in one terminal (this will download and load the model):
cd code/basic
uvicorn model_runner:app --host 0.0.0.0 --port 8002The model runner (code/basic/model_runner.py) is a FastAPI service that wraps vLLM for inference. It loads the model on startup and exposes a /generate endpoint. The model loading takes a minute or two on first run as it downloads weights and compiles CUDA graphs.
In another terminal, start the API gateway:
uvicorn api_gateway:app --host 0.0.0.0 --port 8000The API gateway (code/basic/api_gateway.py) is the public-facing entry point. In this simplified example, it provides rate limiting and routes requests to the model runner. A production gateway would add authentication, load balancing across replicas, and request queuing.
You can then send requests to the gateway:
curl -X POST http://localhost:8000/generate \
-H "Content-Type: application/json" \
-d '{"prompt": "What is machine learning?", "max_tokens": 100}'
The code/basic/ directory also includes a standalone tokenizer service (tokenizer_service.py) that demonstrates how to build a separate tokenization layer. While vLLM handles tokenization internally, a separate service is useful for diffusion models (which need CLIP tokenization), token counting for billing, or custom backends. The service loads two tokenizers on startup: the Qwen2.5-1.5B tokenizer for LLMs and the openai/clip-vit-large-patch14 tokenizer for diffusion models like Stable Diffusion. To try it, start the service:
uvicorn tokenizer_service:app --host 0.0.0.0 --port 8001Tokenizers load vocabulary files on CPU only—no GPU required—so this service can run on any machine. With the service running, you can tokenize text for LLMs:
curl -X POST http://localhost:8001/tokenize \
-H "Content-Type: application/json" \
-d '{"model": "qwen2.5-1.5b", "text": "Hello world"}'For diffusion models like Stable Diffusion, the text prompt needs CLIP tokenization before the text encoder can process it. The same service handles this with a different model name:
curl -X POST http://localhost:8001/tokenize \
-H "Content-Type: application/json" \
-d '{"model": "stable-diffusion", "text": "a photo of a cat"}'If you only need the token count—say, for billing or enforcing input length limits—the /count endpoint returns just the number without the full token list:
curl -X POST http://localhost:8001/count \
-H "Content-Type: application/json" \
-d '{"model": "qwen2.5-1.5b", "text": "How many tokens is this?"}'The monitoring layer is not included in this basic example—we’ll cover observability patterns in Section Deploying LLM serving on Kubernetes.
Request routing and traffic management
In production systems, you often need to serve multiple models simultaneously, route requests intelligently, and balance load across instances. Beyond basic routing, you also need strategies for safely rolling out new model versions and running experiments. This section covers the complete traffic management picture: routing, load balancing, canary deployments, and A/B testing.
Routing strategies
There are three common approaches to routing requests in multi-model deployments:
Feature-based routing examines the request content to determine which model is best suited. For example, code-related prompts might route to Code Llama, while general chat goes to a conversational model. This approach works well when different models have distinct strengths, but requires careful keyword matching or classification logic.
A/B traffic splits use consistent hashing to assign users to model variants. The key insight is using the user ID (or session ID) as the hash input, ensuring the same user always gets the same model. This consistency is crucial for meaningful A/B comparisons—if users bounced between models randomly, you couldn’t attribute performance differences to the model itself.
Dynamic model selection considers runtime factors like current load, latency budgets, and cost constraints. A cost-sensitive request might route to a smaller, cheaper model, while a latency-critical request goes to the fastest available option. This approach requires tracking model performance metrics in real-time.
The implementation of all three strategies is available in code/basic/routing.py. The FeatureBasedRouter, ABRouter, and DynamicRouter classes demonstrate these patterns.
🎬 Engineering Distributed AI Systems
Join Henry (Fuheng) Wu for a free live session on how AI systems scale from a single GPU to large clusters.
🗓️ Sat 5 Dec, 11 AM ET · Free live webinar
Load balancing
Once you’ve decided which model handles a request, you need to choose which instance of that model receives it. The three standard approaches are:
Round-robin distributes requests evenly across instances by cycling through them in order. It’s simple and works well when instances have similar capacity and requests have similar cost.
Least connections routes to the instance with the fewest active requests. This naturally handles varying request durations—slow requests don’t cause one instance to fall behind while others sit idle.
Weighted balancing assigns different capacities to instances, useful when you have heterogeneous hardware (e.g., some instances on A100s, others on H100s).
All three balancers, plus a health checker that integrates with them, are implemented in code/basic/load_balancer.py and code/basic/health_check.py.
Canary deployments and A/B testing
Beyond routing to existing models, you need strategies for safely introducing new model versions. Canary deployments allow you to gradually roll out new models while monitoring for issues. A/B testing enables comparing model performance in production. Both techniques are essential for safe, data-driven model updates.
Canary Deployment. The idea behind canary deployment is simple: instead of switching all traffic to a new model at once, you start by sending a small percentage (say, 10%) to the new “canary” model while the rest continues to the stable version. You monitor both versions, comparing error rates, and latency. If the canary performs well, you gradually increase its traffic share. If it performs poorly, you roll back immediately with minimal user impact. The key metrics to track are error rate and latency—a reasonable promotion policy might allow the canary to have up to 10% higher error rate and 20% higher latency than the stable version, with rollback triggered if the canary’s error rate exceeds twice the stable version’s rate.
Traffic Shifting. This is the mechanism for gradually moving users from stable to canary. A typical progression might be: 10% → 25% → 50% → 75% → 100%. At each step, you wait for enough requests to accumulate (statistical significance) before deciding whether to proceed or roll back.
A/B Testing. A/B testing differs from canary deployment in its goal: canaries are about safe rollouts, while A/B tests are about comparing alternatives to make data-driven decisions. An A/B test might compare two different models, two different prompt templates, or two different inference configurations. The critical requirement is consistent assignment—the same user must always see the same variant, achieved through consistent hashing of the user ID.
A sample implementation lives in code/basic/canary.py. The imports below assume your working directory is code/basic/:
from canary import CanaryDeployment, TrafficShifter, ABTestFramework, ABTestConfig
# Example 1: Canary deployment for a new model version
canary = CanaryDeployment(
stable_model="llama-2-7b-v1",
canary_model="llama-2-7b-v2",
traffic_percent=0.1 # Start with 10% to canary
)
# Route a request
model = canary.route({"prompt": "Hello"}) # Returns stable or canary model
# After getting response, record metrics
canary.record_metrics(model, latency=0.15, error=False)
# Check if canary should be promoted or rolled back
if canary.should_promote():
print("Canary performing well, increase traffic")
elif canary.should_rollback():
print("Canary failing, rolling back")
# Example 2: Gradual traffic shifting
shifter = TrafficShifter("model-v1", "model-v2")
shifter.increase_traffic() # 0% -> 10%
shifter.increase_traffic() # 10% -> 25%
# ... continue based on metrics
# Example 3: A/B testing two models
ab = ABTestFramework()
ab.register_test(ABTestConfig(
test_name="model_comparison",
variants={"llama-7b": 0.5, "mistral-7b": 0.5},
metrics=["latency", "quality_score"]
))
# Assign user to variant (consistent across requests)
variant = ab.assign_variant("model_comparison", user_id="user123")
# Record metrics after serving
ab.record_metric("model_comparison", variant, "latency", 0.12)
# Get aggregated results
results = ab.get_results("model_comparison")These patterns integrate with the API gateway—in production, you’d wire the routing logic into your request-handling pipeline.
Operations: observability, reliability, and cost
Beyond traffic management, production systems require operational capabilities: monitoring system health, handling failures gracefully, and optimizing costs. These cross-cutting concerns apply to every component in the serving stack.
Join Free Webinar with Henry (Fuheng) Wu
Observability
In a distributed LLM serving system, a single request might touch the API gateway, tokenizer service, and model runner—without proper observability, debugging issues becomes nearly impossible. Production LLM serving requires three types of observability:
Distributed tracing with OpenTelemetry tracks requests as they flow through multiple services. Each service creates “spans” that record timing and metadata, linked together by a trace ID that propagates through HTTP headers. When a request is slow, you can see exactly which service contributed the latency.
Metrics collection with Prometheus tracks aggregate statistics: request counts, latency histograms, error rates, and resource utilization. Unlike traces (which are sampled), metrics capture every request, making them essential for alerting and SLO monitoring. Key metrics for LLM serving include requests per second by model, latency percentiles (p50, p95, p99), active request count, and GPU utilization.
Structured logging captures detailed information about individual requests in a machine-parseable format (typically JSON). Unlike traditional logs, structured logs can be queried and aggregated—for example, finding all requests for a specific user that took longer than 5 seconds.
A sample implementation of all three is available in code/basic/observability.py.
Reliability and fault tolerance
Cold start mitigation. LLM inference has significant cold start latency—loading a model and warming up the GPU can take 30-60 seconds. Two strategies help: warmup on startup (sending dummy requests through the model immediately after loading) and keep-alive requests (periodic dummy requests to prevent the model from going cold during idle periods).
Autoscaling. Request-based autoscaling adjusts replica count based on traffic. Key parameters include target RPS, scale-up threshold (typically 120% of target), scale-down threshold (typically 50% of target), and cooldown period. For LLM serving, be conservative with scale-down—spinning up a new GPU instance takes minutes, so it’s better to have slightly excess capacity than to be caught short.
Backpressure. When traffic exceeds capacity, a bounded request queue provides backpressure—when the queue is full, new requests are rejected immediately with a 503 error rather than timing out after a long wait. This gives clients a clear signal to retry later or route to a different backend.
Cost optimization
GPU instances are expensive, so cost optimization matters. Spot instances (or preemptible VMs) cost 60-90% less than on-demand but can be terminated with short notice—a typical strategy uses 50% spot instances for baseline capacity, with on-demand instances absorbing traffic when spot instances are preempted. Model selection routes cost-sensitive requests to smaller, cheaper models; a 7B model might cost half as much per token as a 13B model, and for many use cases the quality difference doesn’t justify the cost.
A sample implementation of warmup, autoscaling, request queuing, and cost-optimized routing is available in code/basic/fault_tolerance.py.
Deploying LLM serving on kubernetes
The concepts we’ve covered so far—routing, load balancing, canary deployments, observability, and fault tolerance—are platform-agnostic patterns. You could implement them on bare metal servers, with Docker Compose, or on any cloud platform. However, Kubernetes (K8s) has emerged as the dominant platform for production LLM serving.
Kubernetes (Kubernetes official site: https://kubernetes.io/) is an open-source container orchestration system originally developed by Google and now maintained by the Cloud Native Computing Foundation (CNCF). At its core, Kubernetes manages containerized workloads across a cluster of machines, handling scheduling, scaling, networking, and storage. You describe your desired state in YAML manifests—how many replicas of a service you want, how much CPU and memory each needs, how they should be exposed to the network—and Kubernetes continuously works to make the actual state match your desired state. This declarative model, combined with self-healing capabilities (automatically restarting failed containers, rescheduling workloads when nodes die), makes Kubernetes well-suited for production systems that need high availability.
For LLM serving specifically, Kubernetes provides native primitives for many of the patterns we’ve discussed:
Figure 9.2 illustrates how these primitives fit together in a typical setup. External traffic enters through an Ingress, which routes to a Service that load-balances across Deployments. Each Deployment manages multiple Pods running vLLM, with the Horizontal Pod Autoscaler (HPA) scaling replicas based on demand. The two Deployments (model-v1 and model-v2) enable canary deployments with weighted traffic splitting (90%/10%). At the bottom, GPU nodes schedule workloads using the NVIDIA device plugin.
Rather than implementing these patterns from scratch, Kubernetes lets you declare your desired state and handles the implementation details. This declarative approach—combined with a rich ecosystem of operators and tools—is why production LLM serving stacks like vLLM Production Stack and llm-d are built on Kubernetes.
We’ll explore Kubernetes-based LLM serving in two steps. First, we’ll set up a local development environment using k3d (to run k3s (Rancher Labs’ minimal Kubernetes distribution) in docker: https://k3d.io/), a lightweight Kubernetes distribution that runs entirely in Docker. This gives us a safe playground to experiment with configurations before deploying to production. Then, we’ll deploy llm-d (Production LLM Serving on Kubernetes: https://llm-d.ai/), a production-ready serving stack that implements all the patterns we’ve discussed—routing, autoscaling, observability, and fault tolerance—as Kubernetes-native resources.
Local development with k3d
k3d wraps k3s (Lightweight Kubernetes: https://k3s.io/), a lightweight Kubernetes distribution, inside Docker containers, giving you a fully functional Kubernetes cluster in minutes. It’s lightweight (no VMs needed), supports GPU passthrough, and produces manifests that work unchanged on production clusters. This makes it ideal for developing and testing LLM serving configurations before deploying to production.
The complete k3d setup scripts are available in code/k3d/. The setup involves three main steps: installing prerequisites, building a custom GPU-enabled k3s image, and creating the cluster.
cd code/k3d
# Step 1: Install prerequisites (NVIDIA Container Toolkit, k3d)
./install-prerequisites.sh
# Step 2: Build custom k3s-cuda image
./build.sh
# Step 3: Create cluster with GPU support
./create-cluster.shThe install-prerequisites.sh script checks for NVIDIA drivers, installs the NVIDIA Container Toolkit, and installs k3d. The build.sh script creates a custom k3s image with CUDA and NVIDIA runtime support—necessary because the default k3s image doesn’t include GPU support.
The custom image combines k3s with CUDA and the NVIDIA Container Toolkit. The key files are code/k3d/Dockerfile and code/k3d/device-plugin-daemonset.yaml. The Dockerfile uses a multi-stage build to copy k3s binaries into an NVIDIA CUDA base image, then installs the container toolkit and configures containerd to use the NVIDIA runtime. The device plugin manifest is automatically deployed when the cluster starts, making GPUs visible to Kubernetes as nvidia.com/gpu resources.
The build.sh script auto-detects your local CUDA version and fetches the latest k3s release, so in most cases you can simply run it without arguments. If you need a specific version, override with environment variables:
# Use specific versions (check hub.docker.com/r/rancher/k3s and hub.docker.com/r/nvidia/cuda)
K3S_TAG=v1.32.0-k3s1 CUDA_TAG=13.0.0-base-ubuntu24.04 ./build.shThe CUDA version must be compatible with your NVIDIA driver. Run nvidia-smi to see the maximum CUDA version your driver supports—you can use any version up to that number.
Figure 9.3 shows the architecture of the resulting k3d GPU cluster. The host machine runs Docker Engine, which contains the k3d network with two nodes: a control plane (server-0) running Kubernetes control plane services, and a worker node (agent-0) running application workloads like vLLM pods. Both nodes use the custom k3s-cuda image and have GPU passthrough via --gpus=all. The NVIDIA device plugin runs as a DaemonSet, exposing physical GPUs to Kubernetes as nvidia.com/gpu resources.
After running the three setup scripts, verify the cluster is working:
kubectl get nodes
# NAME STATUS ROLES AGE VERSION
# k3d-mycluster-gpu-server-0 Ready control-plane 41s v1.35.1+k3s1
# k3d-mycluster-gpu-agent-0 Ready <none> 37s v1.35.1+k3s1Then verify that GPUs are accessible to the cluster:
kubectl describe nodes | grep nvidia.com/gpuFigure 9.4 shows a sample output from an 8-GPU A100 node (complete output available at code/k3d/kubectl_describe_node.txt). In the output, Capacity indicates total GPUs detected, Allocatable shows how many are available for pod scheduling, and Allocated displays current usage as requests/limits (zeros indicate no pods are using GPUs yet). Since k3d passes all host GPUs to each container, every node reports the same GPU count—this is expected behavior for local development.
For cluster customization options such as mounting model directories or selecting specific GPUs, refer to code/k3d/README.md.
Deploying vLLM on k3d
With the GPU cluster running, we can now deploy vLLM to serve LLM inference. The code/k3d/vllm/ directory contains ready-to-use Kubernetes manifests for several models, so you don’t need to write YAML from scratch.
Many popular models on Hugging Face are “gated,” meaning you need to accept their license terms and authenticate to download them. Llama models fall into this category. If you’re deploying a gated model, first create a Kubernetes secret using the HF_TOKEN environment variable we set earlier:
kubectl create secret generic hf-token-secret --from-literal=token="$HF_TOKEN"Now you can deploy a model. In production, model selection depends on both your available GPU memory and business requirements such as latency, throughput, and output quality. For this demonstration, we use smaller models. Phi-tiny-MoE is a lightweight option that works well for testing on smaller GPUs, while Llama-3.2-1B offers better quality but requires approximately 8GB of GPU memory:
cd code/k3d/vllm
kubectl apply -f llama-3.2-1b.yaml
# or ./deploy-phi-tiny-moe.sh for smaller GPUsThe deployment manifests handle the details you’d otherwise need to configure manually: GPU resource requests so Kubernetes schedules the pod on a node with available GPUs, health probes with appropriate timeouts for model loading, volume mounts for caching downloaded weights, and Kubernetes services for network access. Watch the deployment progress with:
kubectl get pods -l app=vllm -w
# NAME READY STATUS RESTARTS AGE
# vllm-llama-32-1b-pod-xxx 0/1 ContainerCreating 0 2m40sThe pod will initially show ContainerCreating while Kubernetes pulls the vLLM container image. This can take several minutes depending on your network speed. Once the status changes to Running, you can view the logs:
kubectl logs -l app=vllm --follow
Figure 9.5 shows typical log output during model startup. The logs display download progress if the model needs to be fetched from Hugging Face, followed by the model being loaded into GPU memory. Model loading typically takes 2-5 minutes depending on model size and whether the weights are already cached locally. Once the logs indicate “Application startup complete.”, the server is ready to accept requests.
To test the API, forward the service port to your local machine and send a request:
kubectl port-forward svc/vllm-llama-32-1b-service 8000:8000 &
curl http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "meta-llama/Llama-3.2-1B-Instruct",
"messages": [{"role": "user", "content": "Hello!"}],
"max_tokens": 50
}'Figure 9.6 shows a successful response from the vLLM server running in Kubernetes. The JSON response follows the OpenAI chat completions format, including the model name, generated content, and token usage statistics.
Looking at the deployment manifests (code/k3d/vllm/llama-3.2-1b.yaml and code/k3d/vllm/phi-tiny-moe.yaml), you’ll notice several configuration patterns worth understanding. The --gpu-memory-utilization 0.2 flag tells vLLM to reserve only 20% of GPU memory—well below the default of about 0.85. That conservative setting suits shared-GPU or multi-model clusters; for a single model where you want maximum throughput, use 0.8–0.9 instead.
The health probes deserve special attention. Kubernetes uses liveness and readiness probes to determine if a pod is healthy, but LLM models take significant time to load into GPU memory—often several minutes for larger models. The manifests set initialDelaySeconds to 120-180 seconds to give the model time to load; without that delay, Kubernetes restarts the pod in an endless loop. Allow several consecutive failures (failureThreshold of 3 or higher) so a single slow probe during GC does not look like a crash.
The volume mount at /models persists downloaded model weights across pod restarts. This is important because downloading a 7B-parameter model from Hugging Face takes considerable time and bandwidth. Once cached, subsequent pod restarts load the model directly from disk.
Shared memory at /dev/shm is easy to overlook. Docker’s default segment is only 64MB, yet tensor-parallel vLLM workers route NCCL and IPC buffers through it—too little space and collectives hang with little diagnostic output. The manifests mount a larger volume (emptyDir with medium: Memory, or an equivalent --shm-size on the container) sized for your tensor-parallel width.
For larger models that don’t fit on a single GPU, you can shard the model by setting --tensor-parallel-size to the number of GPUs and updating the resource limits accordingly. The code/k3d/README.md file provides detailed guidance on multi-GPU configurations and troubleshooting common issues.
Cleanup
When you’re done experimenting, clean up the cluster to free resources:
k3d cluster delete mycluster-gpu
docker rmi k3s-cuda:<your-tag> # optional, removes the custom imageMulti-Model and Multi-Engine serving
With a single vLLM deployment running successfully, we can now explore more sophisticated serving patterns. Production deployments rarely serve just one model—you might have different models for different tasks (a small model for simple queries, a larger one for complex reasoning), or you might want to A/B test different models or inference engines.
The code/k3d/ directory provides two management scripts that automate these deployment patterns:
manage-cluster-multi-models.sh: Deploys multiple models (Llama-3.2-1B + Phi-tiny-MoE) using a single engine (vLLM)manage-cluster-multi-engines.sh: Deploys the same model (Llama-3.2-1B) on multiple engines (vLLM + SGLang)
Multi-Model routing
The key insight is that an API gateway can route requests based on the model field in the OpenAI-compatible request body. When a client sends a request specifying "model": "meta-llama/Llama-3.2-1B-Instruct", the gateway looks up which Kubernetes service hosts that model and forwards the request accordingly. This creates a unified endpoint where clients don’t need to know which backend server handles which model.
Figure 9.7 illustrates this architecture. Client applications send requests to the API gateway, which parses the model field and forwards the request to the appropriate vLLM service. Each model runs in its own pod with a dedicated Kubernetes service.
Let’s deploy this architecture. The management script handles all the complexity—creating the namespace, deploying both models, and setting up the gateway:
cd code/k3d
./manage-cluster-multi-models.sh startWe can check deployment status by:
./manage-cluster-multi-models.sh statusThe status command shows what’s running. You should see two vLLM pods (one for each model) and their corresponding services:
==========================================
k3d Cluster Status: mycluster-gpu
==========================================
📊 Cluster list:
NAME SERVERS AGENTS LOADBALANCER
mycluster-gpu 1/1 1/1 true
Switched to context "k3d-mycluster-gpu".
📊 Kubernetes nodes:
NAME STATUS ROLES AGE VERSION
k3d-mycluster-gpu-agent-0 Ready <none> 5h32m v1.35.1+k3s1
k3d-mycluster-gpu-server-0 Ready control-plane 5h32m v1.35.1+k3s1
📊 Namespaces:
NAME STATUS AGE
multi-models Active 20m
📊 Pods in namespace multi-models:
NAME READY STATUS RESTARTS AGE
vllm-llama-32-1b-pod-76895c5cfb-vkz7w 1/1 Running 0 20m
vllm-phi-tiny-moe-pod-55b8c8c959-nvxjh 1/1 Running 0 2m33s
📊 Services in namespace multi-models:
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
vllm-llama-32-1b-service ClusterIP 10.43.178.154 <none> 8000/TCP 20m
vllm-phi-tiny-moe-service ClusterIP 10.43.55.228 <none> 8000/TCP 20mThis script creates a multi-models namespace, deploys both vLLM models (Llama-3.2-1B and Phi-tiny-MoE), and sets up the API gateway.
The routing configuration (gateway/routing-config.yaml) maps model names to Kubernetes services:
routing:
- model: "meta-llama/Llama-3.2-1B-Instruct"
service_name: "vllm-llama-32-1b-service.multi-models.svc.cluster.local"
- model: "microsoft/Phi-tiny-MoE-instruct"
service_name: "vllm-phi-tiny-moe-service.multi-models.svc.cluster.local"When the gateway receives a request with "model": "meta-llama/Llama-3.2-1B-Instruct", it looks up the service name in this table—here vllm-llama-32-1b-service.multi-models.svc.cluster.local, i.e. <service>.<namespace>.svc.cluster.local—and forwards the request without exposing backend layout to the client.
Now let’s test it. First, set up port forwarding to access the gateway from your local machine:
kubectl port-forward svc/vllm-api-gateway 8080:8000 &Then send the request and get the response to LLama:
$ curl http://localhost:8080/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model": "meta-llama/Llama-3.2-1B-Instruct",
"messages": [{"role": "user", "content": "Hello!"}]}'
{"id":"chatcmpl-8d9100935563642c","object":"chat.completion","created":...,
"model":"meta-llama/Llama-3.2-1B-Instruct","choices":
[{"index":0,"message":{
"role":"assistant","content":"Hello! How can I assist you today?"...
prompt_logprobs":null,"prompt_token_ids":null,"kv_transfer_params":nullNow send a request to the Phi model—same endpoint, different model field:
$ curl http://localhost:8080/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model": "microsoft/Phi-tiny-MoE-instruct",
"messages": [{"role": "user", "content": "Hello!"}]}'
{"id":"chatcmpl-a59b963764eb8f41","object":"chat.completion","created":...,
"model":"microsoft/Phi-tiny-MoE-instruct","choices":
[{"index":0,"message":
{"role":"assistant","content":" Hello! How can I assist you today?"...
"prompt_logprobs":null,"prompt_token_ids":null,"kv_transfer_params":null}Notice that both requests go to localhost:8080, but the gateway routes them to different backends based on the model field. This is the power of multi-model routing: clients interact with a single endpoint while the infrastructure handles model placement.
Before moving to multi-engine routing, clean up this deployment to free GPU resources:
./manage-cluster-multi-models.sh stopThis command stops the port-forward process and removes all resources in the multi-models namespace.
Multi-Engine routing
Taking this further, we can deploy the same model on different inference engines (vLLM and SGLang) and route based on an inference_server field. This is useful for benchmarking engines or gradually migrating between them.
As shown in Figure 9.8, the gateway parses both model and inference_server fields to determine routing. Use the multi-engine management script:
cd code/k3d
./manage-cluster-multi-engines.sh startThis creates a multi-engines namespace and deploys Llama-3.2-1B on both vLLM and SGLang. We can check the status of the deployment by running:
$ ./manage-cluster-multi-engines.sh status
==========================================
k3d Cluster Status: mycluster-gpu
==========================================
📊 Cluster list:
NAME SERVERS AGENTS LOADBALANCER
mycluster-gpu 1/1 1/1 true
Switched to context "k3d-mycluster-gpu".
📊 Kubernetes nodes:
NAME STATUS ROLES AGE VERSION
k3d-mycluster-gpu-agent-0 Ready <none> 6h16m v1.35.1+k3s1
k3d-mycluster-gpu-server-0 Ready control-plane 6h16m v1.35.1+k3s1
📊 Namespaces:
NAME STATUS AGE
multi-engines Active 21m
multi-models Active 64m
📊 Pods in namespace multi-engines:
NAME READY STATUS RESTARTS AGE
sglang-llama-32-1b-pod-7dc599696d-67f9r 1/1 Running 0 21m
vllm-llama-32-1b-pod-76895c5cfb-m9bbw 1/1 Running 0 21m
📊 Services in namespace multi-engines:
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
sglang-llama-32-1b-service ClusterIP 10.43.249.196 <none> 8000/TCP 21m
vllm-llama-32-1b-service ClusterIP 10.43.89.85 <none> 8000/TCP 21mThe routing configuration (code/k3d/gateway/routing-config.yaml) includes engine-specific routes, allowing clients to select their preferred inference engine:
routing:
- model: "meta-llama/Llama-3.2-1B-Instruct"
inference_server: "vllm"
service_name: "vllm-llama-32-1b-service.multi-engines.svc.cluster.local"
- model: "meta-llama/Llama-3.2-1B-Instruct"
inference_server: "sglang"
service_name: "sglang-llama-32-1b-service.multi-engines.svc.cluster.local"
- model: "meta-llama/Llama-3.2-1B-Instruct"
inference_server: null # Default to vLLM
service_name: "vllm-llama-32-1b-service.multi-engines.svc.cluster.local"The third entry with inference_server: null acts as a fallback—requests that don’t specify an engine go to vLLM by default.
Set up port forwarding and test both engines:
kubectl port-forward svc/vllm-api-gateway 8080:8000 &First, a request without specifying the engine (routes to vLLM by default):
$ curl http://localhost:8080/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model": "meta-llama/Llama-3.2-1B-Instruct",
"messages": [{"role": "user", "content": "Hello!"}]}'
{"id":"chatcmpl-9583dfa06c9b9669","object":"chat.completion","created":...,
"model":"meta-llama/Llama-3.2-1B-Instruct","choices":
[{"index":0,"message":{
"role":"assistant","content":"Hello! How can I assist you today?"...
"prompt_logprobs":null,"prompt_token_ids":null,"kv_transfer_params":null}Now explicitly route to SGLang by adding the inference_server field:
$ curl http://localhost:8080/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model": "meta-llama/Llama-3.2-1B-Instruct",
"inference_server": "sglang",
"messages": [{"role": "user", "content": "Hello!"}]}'
{"id":"e02f545aca204f...3b20","object":"chat.completion","created":...,
"model":"meta-llama/Llama-3.2-1B-Instruct","choices":
[{"index":0,"message":{
"role":"assistant","content":"Hello! How can I assist you today?"...
"usage":
{"prompt_tokens":37,"total_tokens":47,"completion_tokens":10...}The gateway also aggregates the /v1/models endpoint, returning a combined list of all available models across all backends. For production deployments, you’ll want to add authentication (API keys or OAuth tokens), rate limiting (per-client request quotas), and observability (request logging, latency metrics, error tracking). The code/k3d/gateway/api-gateway.py includes example middleware for these concerns.
Kubernetes deployment with llm-d
In the previous section, we built a local k3d cluster to experiment with vLLM deployments. While this approach offers flexibility and a deep understanding of the underlying components, production deployments at scale often benefit from standardized solutions that handle the operational complexity of distributed inference.
Several Kubernetes-native frameworks exist for LLM serving. KServe[1] provides enterprise-grade model serving with traffic governance (canary releases, A/B testing) and multi-model hosting, but requires Istio or Knative as dependencies. KubeAI[2] offers a lightweight operator with scale-from-zero and prefix-aware load balancing, requiring no external dependencies—ideal for simpler deployments. vLLM production-stack[3] is the official vLLM deployment solution with LMCache integration for KV cache sharing across instances.
This chapter focuses on llm-d[4] because it provides a “batteries-included” deployment framework that assembles well-tested components (vLLM, Envoy, NIXL) into a cohesive system, offers production-ready Helm charts with minimal configuration, and supports advanced features like disaggregated prefill/decode and high-speed data transfer over InfiniBand RDMA. The choice between these frameworks depends on your specific requirements: KServe for enterprise traffic governance, KubeAI for lightweight zero-dependency deployments, vLLM production-stack for official vLLM support with KV cache sharing, and llm-d for deployments that need disaggregated inference or high-speed interconnects. A detailed comparison between the manual k3d approach and llm-d is provided in Table 9.2.
What is llm-d?
Think of llm-d as a “batteries-included” deployment framework that assembles best-in-class open-source components into a cohesive system. At its core, llm-d uses vLLM[5] as the model server—the same engine we deployed manually in the k3d section. But llm-d adds several layers of intelligence on top: the Inference Gateway (IGW)[6] acts as a smart request scheduler, Envoy Proxy[7] handles load balancing and routing, and NIXL[8] enables high-speed data transfer over fast interconnects like InfiniBand RDMA or TPU ICI. Kubernetes orchestrates all these components, ensuring they scale and recover gracefully.
Key features
Intelligent Inference Scheduling. One of llm-d’s most valuable capabilities is its intelligent request routing. Traditional load balancers distribute requests round-robin or based on simple metrics like connection count. But LLM inference has unique characteristics: a request with a 10,000-token prompt behaves very differently from one with 100 tokens. llm-d’s IGW understands this. It can predict request latency and route accordingly, ensuring that long requests don’t block short ones. It also implements prefix-cache aware routing—if one vLLM instance already has the KV cache for a particular system prompt, subsequent requests with the same prefix get routed there, dramatically reducing time-to-first-token. For enterprise deployments, SLA-aware scheduling ensures premium customers get priority access to compute resources, while load-aware balancing distributes work based on each instance’s current capacity rather than just counting connections.
Prefill/Decode Disaggregation. Perhaps the most innovative feature of llm-d is its support for disaggregated inference. In traditional LLM serving, a single GPU handles both the prefill phase (processing the input prompt) and the decode phase (generating output tokens one by one). These phases have very different computational profiles: prefill is compute-bound and parallelizable, while decode is memory-bandwidth-bound and sequential. By separating them onto different server pools, llm-d can optimize each independently. Prefill servers can use larger batch sizes and higher GPU utilization, while decode servers can be tuned for low latency. The challenge is transferring the KV cache between them—this is where NIXL shines, using RDMA to move gigabytes of cache data in milliseconds. A sidecar container coordinates these transfers, ensuring decode servers receive the KV cache exactly when they need it.
Disaggregated Prefix Caching. Building on vLLM’s KVConnector abstraction, llm-d implements a sophisticated caching hierarchy. Independent caching (sometimes called N/S for North/South) offloads KV cache to local memory and NVMe storage, allowing a single instance to serve more concurrent requests than its GPU memory would normally allow. Shared caching (E/W for East/West) enables KV cache transfer between instances, so if one server has computed the cache for a common system prompt, others can retrieve it rather than recomputing. For the most demanding deployments, global indexing provides a cluster-wide view of cached prefixes, enabling optimal routing decisions at the cost of additional coordination overhead.
Variant Autoscaling. Traditional Kubernetes autoscaling (HPA) scales based on CPU or memory utilization, but LLM workloads need smarter scaling. llm-d’s variant autoscaler measures the actual capacity of each model server instance—how many tokens per second it can generate given current memory pressure. It then analyzes recent traffic patterns: the mix of request sizes, quality-of-service requirements, and arrival rates. Based on this analysis, it calculates the optimal mix of prefill servers, decode servers, and instances reserved for latency-tolerant batch requests. This enables true SLO-level efficiency, scaling up before latency degrades rather than after.
Hardware Support: One of llm-d’s strengths is its broad hardware compatibility. The project directly tests and validates deployments on NVIDIA GPUs (A100, L4, and newer), AMD GPUs (MI250 and newer), Google TPUs (v5e and newer), and Intel Data Center GPU Max series (Ponte Vecchio). This multi-vendor support is increasingly important as organizations seek to avoid lock-in and optimize costs across different cloud providers.
Deployment architecture
Having covered llm-d’s key features—intelligent scheduling, prefill/decode disaggregation, distributed caching, and variant autoscaling—let’s see how these components fit together in a production deployment.
Figure 9.9 illustrates the complete architecture. To understand how it works, let’s trace a request through the system.
Every production API needs a front door—something that handles the messy realities of internet traffic: TLS encryption, authentication, rate limiting, and graceful handling of misbehaving clients. In llm-d, this role falls to Envoy Proxy[7], a high-performance edge proxy widely used in cloud-native deployments. You may already have Envoy in your infrastructure (it powers Istio[9] service mesh and many API gateways); llm-d simply leverages it as the entry point for all inference requests.
From Envoy, requests flow to the Inference Gateway (IGW)[6]—the “brain” of llm-d. While Envoy handles generic HTTP concerns, the IGW understands LLM inference. It examines each request’s characteristics: How long is the prompt? Which model is requested? Does any backend already have the relevant prefix cached? Based on this analysis, the IGW routes the request to the optimal model server. This is fundamentally different from traditional load balancers that distribute requests round-robin or based on connection counts—the IGW makes routing decisions based on the actual computational cost of each request.
Behind the IGW sit the model servers that perform inference. In standard mode, each server handles the complete inference pipeline. But llm-d also supports disaggregated mode, where servers specialize: prefill servers process input prompts (compute-intensive, parallelizable), while decode servers generate output tokens (memory-bandwidth-bound, latency-sensitive). When a prefill server finishes processing a prompt, a NIXL[8] sidecar transfers the KV cache to the assigned decode server using RDMA[10], often completing in milliseconds even for large caches. This separation allows each server type to be optimized independently—prefill servers can batch aggressively for throughput, while decode servers tune for minimal latency.
For deployments that serve many requests with shared prefixes (common system prompts, few-shot examples), llm-d can optionally store KV cache on shared NVMe[11] storage. This enables cluster-wide prefix caching: when one server computes the cache for a popular prefix, other servers can retrieve it rather than recomputing, dramatically reducing redundant work across the fleet.
Getting started with llm-d
Deploying llm-d requires a production-grade Kubernetes cluster running version 1.29 or later. Unlike our local k3d experiments, llm-d is designed for environments with serious hardware: you’ll need accelerators capable of running large models (think A100s or newer for 70B+ parameter models), and ideally fast interconnects like NVLink within nodes and InfiniBand or RoCE RDMA between nodes. For Google Cloud deployments, TPU ICI and DCN provide similar high-bandwidth connectivity.
The installation process leverages Helm, Kubernetes’ package manager. After adding the llm-d repository, a single helm install command deploys the entire stack—vLLM model servers, the Inference Gateway, Envoy proxy, and all the supporting infrastructure. The beauty of Helm is that complex configurations become simple key-value pairs: enabling the Inference Gateway, specifying which model to serve, setting tensor parallelism for multi-GPU inference.
Configuration happens through a values.yaml file that reads almost like a specification document. You declare what you want—two IGW replicas with cache-aware routing, vLLM serving Llama 3.1 70B across four GPUs at 90% memory utilization, separate prefill and decode server pools with their own replica counts and GPU allocations—and Helm translates this into the dozens of Kubernetes resources needed to make it happen. The autoscaling section is particularly elegant: rather than scaling on CPU utilization (which means little for GPU workloads), you specify target queries per second, and llm-d’s variant autoscaler handles the rest.
The accompanying code directory (code/llmd/) contains complete, tested deployment configurations. The llm-d-multi-engine/ subdirectory demonstrates deploying the same model (Qwen2.5-0.5B-Instruct) with both vLLM and SGLang backends, showcasing llm-d’s engine-agnostic routing. The llm-d-multi-model/ subdirectory shows multi-model deployments with different Llama variants. Each directory includes deployment scripts, Helm values files, and troubleshooting guides—everything you need to replicate these setups in your own environment.
Well-Lit paths
The llm-d project uses the term “well-lit paths” to describe deployment patterns that have been thoroughly tested and benchmarked. Rather than leaving users to figure out optimal configurations through trial and error, these paths represent battle-tested recipes for common scenarios.
Intelligent Inference Scheduling is the starting point for most deployments. By placing vLLM behind the Inference Gateway, you immediately gain access to smarter load balancing than round-robin. The IGW predicts request latency based on prompt length and routes accordingly, preventing long requests from blocking short ones. It also tracks which vLLM instances have which prefixes cached, routing repeat requests to instances that can serve them faster. For teams just beginning their production LLM journey, this path offers the best balance of simplicity and performance improvement.
Prefill/Decode Disaggregation becomes valuable when serving large models with long prompts. Consider a 70B parameter model processing a 10,000-token document: the prefill phase (computing attention over all input tokens) is compute-intensive and parallelizable, while the decode phase (generating output tokens one by one) is memory-bandwidth-bound and sequential. By separating these onto different server pools, each can be optimized independently. Prefill servers can batch aggressively for throughput; decode servers can be tuned for minimal latency. The result is reduced time-to-first-token (TTFT) and more predictable time-per-output-token (TPOT). The catch is that KV cache must be transferred between servers, which requires fast interconnects—this path shines with InfiniBand or NVLink, but may not be worth the complexity on slower networks.
Wide Expert-Parallelism targets Mixture-of-Experts (MoE) models like Mixtral or DeepSeek. These models activate only a subset of parameters for each token, making them efficient at inference time but challenging to deploy. Expert parallelism distributes different experts across different GPUs, while data parallelism handles multiple requests simultaneously. llm-d coordinates this complex dance, routing tokens to the right experts while maximizing accelerator utilization. For organizations deploying MoE models at scale, this path can dramatically reduce latency and increase throughput.
Monitoring and observability
Production LLM serving demands visibility into system behavior. llm-d integrates with standard Kubernetes monitoring stacks—Prometheus for metrics collection, Grafana for visualization. Beyond generic metrics like CPU and memory, llm-d exposes LLM-specific telemetry: request latency distributions, tokens-per-second throughput, GPU utilization across the fleet, and crucially, KV cache hit rates. This last metric is particularly telling: high hit rates indicate that the prefix-aware routing is working effectively, while low hit rates suggest you might need cache warming strategies or routing policy adjustments.
Choosing Your Path
For teams new to production LLM serving, the intelligent inference scheduling path offers the gentlest learning curve with immediate benefits. You can deploy it with minimal configuration changes from a basic vLLM setup, yet gain meaningful latency and throughput improvements from smarter routing.
As your deployment matures and you encounter specific bottlenecks, the other paths become relevant. If users complain about slow time-to-first-token on long documents, prefill/decode disaggregation can help—but only if you have the network bandwidth to transfer the KV cache efficiently. If you’re deploying MoE models and seeing suboptimal GPU utilization, expert parallelism may be the answer.
The key is to monitor your metrics and let them guide your evolution. Watch KV cache hit rates to assess routing effectiveness. Track TTFT and TPOT separately to understand where latency comes from. Monitor GPU utilization to identify underutilized capacity. And tune autoscaling parameters based on actual traffic patterns rather than theoretical estimates—set minimum replicas high enough to handle baseline load without cold starts, maximum replicas to accommodate peaks, and target QPS based on observed capacity per instance.
Multi-Model serving
Just as we deployed multiple models with k3d, llm-d supports multi-model serving with production-grade infrastructure. The code/llmd/llm-d-multi-model/ directory contains deployment configurations for serving Llama-3.2-1B and Qwen2.5-0.5B on vLLM.
Figure 9.10 shows llm-d’s multi-model architecture. Each model gets its own ModelService, and the InferencePool automatically discovers and routes requests based on the model field—no manual service mapping required. This is the key difference from our k3d setup: instead of manually configuring routing rules, llm-d discovers ModelService instances and builds the routing table automatically.
The llm-d-multi-model/ directory provides a management script that handles all the complexity. Deploy both models with:
cd code/llmd/llm-d-multi-model
./manage-cluster-multi-models.sh startThe script pins vLLM v0.14.1 to match llm-d v0.5.0—often a release or two behind the standalone code/basic/ stack (0.15.1 in the install command above), because llm-d tests against its own image matrix. It also requires a custom k3s-cuda image (the default k3s lacks NVIDIA container toolkit support). Build one for your CUDA version—run nvidia-smi, then cd code/k3d && ./build.sh. vLLM and llm-d move quickly; update image tags in the deployment files as needed (see the README). Check cluster status with ./manage-cluster-multi-models.sh status.
The script creates the cluster, installs the NVIDIA device plugin, sets up llm-d, and deploys both models. Check deployment status:
$ kubectl get pods
NAME READY STATUS AGE
vllm-llama-32-1b 1/1 Running 5m
vllm-qwen2-5-0-5b 1/1 Running 3mEach model is configured through a Helm values file (llama-3.2-1b-values.yaml, qwen2.5-0.5b-values.yaml) that specifies the model artifact location, GPU requirements, and replica count. The key configuration is the modelArtifacts section that tells llm-d where to fetch the model:
modelArtifacts:
uri: "hf://meta-llama/Llama-3.2-1B-Instruct"
name: "meta-llama/Llama-3.2-1B-Instruct"Test the deployments by port-forwarding to each service:
kubectl port-forward svc/vllm-llama-32-1b 8001:8000 &
kubectl port-forward svc/vllm-qwen2-5-0-5b 8002:8000 &
# Request Llama model
$ curl http://localhost:8001/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model": "meta-llama/Llama-3.2-1B-Instruct",
"messages": [{"role": "user", "content": "Hello!"}]}'
{"id":"chatcmpl-...","object":"chat.completion","created":...,
"model":"meta-llama/Llama-3.2-1B-Instruct","choices":[{"index":0,
"message":{"role":"assistant","content":"Hello! How can I help you today?"}...
# Request Qwen model
$ curl http://localhost:8002/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model": "Qwen/Qwen2.5-0.5B-Instruct",
"messages": [{"role": "user", "content": "Hello!"}]}'
{"id":"chatcmpl-...","object":"chat.completion","created":...,
"model":"Qwen/Qwen2.5-0.5B-Instruct","choices":[{"index":0,
"message":{"role":"assistant","content":"Hello! How can I assist you?"}...The example above uses the simplest setup—direct service access without the Inference Gateway. This requires separate port-forwards for each model, similar to accessing raw vLLM pods. For production deployments, llm-d provides the Inference Gateway that routes requests to the correct model based on the model field in the request body. Let’s add it:
./manage-cluster-multi-models.sh start --with-gatewayThis deploys the Gateway API CRDs and an Envoy-based gateway that routes requests based on the model field in the request body. Now you can access both models through a single endpoint:
$ kubectl port-forward svc/llm-gateway 8000:8000 &
Forwarding from 127.0.0.1:8000 -> 8000
# Request Llama model
$ curl http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model": "meta-llama/Llama-3.2-1B-Instruct",
"messages": [{"role": "user", "content": "Hello!"}]}'
{"id":"chatcmpl-...","model":"meta-llama/Llama-3.2-1B-Instruct",
"choices":[{"message":{"role":"assistant",
"content":"Hello! How can I assist you today?"}...
# Request Qwen model (same port, different model)
$ curl http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model": "Qwen/Qwen2.5-0.5B-Instruct",
"messages": [{"role": "user", "content": "Hello!"}]}'
{"id":"chatcmpl-...","model":"Qwen/Qwen2.5-0.5B-Instruct",
"choices":[{"message":{"role":"assistant",
"content":"Hello! How can I assist you today?"}...The gateway extracts the model name from the request body and routes it to the appropriate vLLM service. A complete example log showing the deployment and testing is available in code/llmd/llm-d-multi-model/example.log.
Unlike our manual k3d setup where we built a custom API gateway, llm-d’s Inference Gateway handles routing automatically using the Kubernetes Gateway API Inference Extension. It also adds intelligence: tracking prefix cache state across instances and routing repeat requests to servers that can serve them faster.
Note llm-d follows a “vLLM-first” design philosophy. The Inference Gateway’s intelligent features—prefix-cache aware routing, NIXL-based KV cache transfer, and the inference scheduler—are tightly integrated with vLLM’s internals. SGLang support is under active development (tracked in GitHub issue #403[12]), but as of this writing, llm-d’s native routing doesn’t support engine selection. For readers interested in multi-engine deployments, the
code/llmd/llm-d-multi-engine/directory provides a workaround using a custom API gateway layer—see the README for details.
Comparing k3d and llm-d approaches
Table 9.2 summarizes the key differences between our manual k3d setup and llm-d’s production stack. The most significant differences are in routing and load balancing: while our k3d setup uses a custom API gateway with basic round-robin distribution, llm-d’s Inference Gateway is Kubernetes-native and prefix-cache aware—it routes requests to pods that already have relevant KV cache entries, reducing redundant computation. For multi-model deployments, k3d requires manual service mapping in the gateway configuration, whereas llm-d automatically discovers ModelService instances and builds the routing table. The monitoring story is similar: k3d requires manual Prometheus/Grafana setup, while llm-d includes pre-configured dashboards out of the box.
The k3d approach we explored earlier is valuable for learning and local development—you understand exactly what each component does because you built it yourself. But for production deployments serving real traffic, llm-d’s battle-tested configurations and intelligent routing provide a more robust foundation. The transition is straightforward: the concepts are identical, only the implementation details change.
Summary
Serving LLMs in production involves far more than loading weights and accepting requests. We explored inference internals—tokenization, attention, KV caching—to understand why frameworks like vLLM and SGLang handle the complex orchestration of batching and memory management for us.
We built a multi-model stack from scratch using k3d, gaining hands-on insight into services, routing, and API gateways. We then contrasted this with llm-d, where the same concepts—InferencePools, model-aware routing, health checks—are packaged into production-ready Helm charts with automatic model discovery.
Production systems demand more than correctness: observability for debugging, canary deployments for safe rollouts, and cost optimization through autoscaling. The journey from laptop to millions of requests is substantial, but the patterns remain consistent: understand your workload, measure everything, and automate what you can.
With serving infrastructure in place, a natural question arises: how well is it performing? The next chapter addresses this directly—benchmarking throughput, latency, and scaling efficiency with tools like genai-bench and PyTorch profiler.
Code summary
fastapi.responses.StreamingResponse: Stream generated tokens to clients over SSEfastapi.FastAPI: HTTP layer for inference gateways and model runnersuvicorn: ASGI server to launch gateway, model runner, and tokenizer serviceshttpx.AsyncClient: Async forwarding from API gateway to model runnerspydantic.BaseModel: Validated request and response schemas for inference APIstransformers.AutoTokenizer: Standalone tokenization for billing, validation, and custom backendsprometheus_client: TTFT, latency percentiles, and throughput metricsopentelemetry.trace: Distributed tracing spans across serving componentskubectl: Deploy, inspect, and debug vLLM and SGLang workloads on Kubernetes
Useful links
LLM Serving Frameworks
vLLM GitHub: https://github.com/vllm-project/vllm
vLLM Production Stack: https://github.com/vllm-project/production-stack
SGLang GitHub: https://github.com/sgl-project/sglang
Kubernetes and llm-d
Llm-d GitHub: https://github.com/llm-d/llm-d
Llm-d Documentation: https://www.llm-d.ai
Inference Gateway: https://github.com/kserve/inference-gateway
k3d (k3s in Docker): https://k3d.io/
NVIDIA Device Plugin for Kubernetes: https://github.com/NVIDIA/k8s-device-plugin
Observability and Monitoring
OpenTelemetry: https://opentelemetry.io/
Prometheus: https://prometheus.io/
Grafana: https://grafana.com/
API Gateway and Routing
Envoy Proxy: https://www.envoyproxy.io/
FastAPI: https://fastapi.tiangolo.com/
Kubernetes Gateway API: https://gateway-api.sigs.k8s.io/
Tutorials and Guides
vLLM Kubernetes Deployment: https://docs.vllm.ai/en/stable/deployment/k8s/
NVIDIA Container Toolkit: https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/
References
KubeAI: https://www.kubeai.org/
vLLM production-stack: https://docs.vllm.ai/en/stable/deployment/integrations/production-stack.html
llm-d project: https://github.com/llm-d/llm-d
vLLM inference engine: https://github.com/vllm-project/vllm
Inference Gateway (IGW): https://github.com/kubernetes-sigs/gateway-api-inference-extension
Envoy Proxy: https://www.envoyproxy.io/
NIXL (NVIDIA Inference Xfer Library): https://github.com/ai-dynamo/nixl
Istio service mesh: https://istio.io/
Remote Direct Memory Access (RDMA) allows direct memory access between computers without involving the CPU or operating system
Non-Volatile Memory Express (NVMe) is a high-speed storage interface protocol designed for SSDs
Exercises
Build an API gateway with model routing
Implement an API gateway that routes requests to different model backends based on the model field in the request body.
Requirements:
Function signature:
class ModelRouter: def __init__(self, model_endpoints: dict[str, str]): """Initialize with mapping of model names to backend URLs.""" pass async def route_request(self, request: dict) -> dict: """Route request to appropriate backend based on model field.""" pass
Parse the
modelfield from incoming requestsForward requests to the correct backend URL
Handle cases where the requested model is not available (return 404)
Add basic health checking for backends
Support both
/v1/chat/completionsand/v1/completionsendpoints
Test your implementation:
import asyncio
import httpx
# Initialize router with model endpoints
router = ModelRouter({
"llama-3.2-1b": "http://localhost:8001",
"qwen-0.5b": "http://localhost:8002",
})
# Test routing
request = {
"model": "llama-3.2-1b",
"messages": [{"role": "user", "content": "Hello!"}],
"max_tokens": 50
}
response = asyncio.run(router.route_request(request))
print(f"Response from {request['model']}: {response}")
# Test unknown model
unknown_request = {"model": "unknown-model", "messages": []}
try:
asyncio.run(router.route_request(unknown_request))
except Exception as e:
print(f"Expected error: {e}")Implement rate limiting middleware
Create a rate limiting middleware that enforces per-client request quotas.
Requirements:
Class signature:
class RateLimiter:
def __init__(self, requests_per_minute: int, burst_size: int = 5):
"""Initialize rate limiter with limits."""
pass
async def check_rate_limit(self, client_id: str) -> bool:
"""Return True if request is allowed, False if rate limited."""
pass
def get_remaining_requests(self, client_id: str) -> int:
"""Return number of remaining requests for client."""
passUse token bucket algorithm for rate limiting
Track requests per client (identified by API key or IP)
Support burst capacity for handling traffic spikes
Return appropriate headers (
X-RateLimit-Remaining,X-RateLimit-Reset)Clean up stale client entries to prevent memory leaks
Test your implementation:
import asyncio
import time
limiter = RateLimiter(requests_per_minute=10, burst_size=5)
async def test_rate_limiting():
client_id = "test-client-123"
# Should allow burst of requests
for i in range(5):
allowed = await limiter.check_rate_limit(client_id)
remaining = limiter.get_remaining_requests(client_id)
print(f"Request {i+1}: allowed={allowed}, remaining={remaining}")
# Should start rate limiting
for i in range(10):
allowed = await limiter.check_rate_limit(client_id)
if not allowed:
print(f"Rate limited after {i+5} requests")
break
asyncio.run(test_rate_limiting())Implement canary deployment with automated rollback
Create a canary deployment system that gradually shifts traffic and automatically rolls back on errors.
Requirements:
Class signature:
class CanaryDeployment:
def __init__(self, stable_endpoint: str, canary_endpoint: str):
"""Initialize with stable and canary endpoints."""
pass
def set_canary_percentage(self, percentage: float):
"""Set percentage of traffic to route to canary (0-100)."""
pass
@property
def canary_percentage(self) -> float:
"""Current canary traffic percentage (0-100)."""
pass
async def route_request(self, request: dict) -> dict:
"""Route request to stable or canary based on percentage."""
pass
def record_result(self, is_canary: bool, success: bool, latency_ms: float):
"""Record request result for monitoring."""
pass
def should_rollback(self, error_threshold: float = 0.05) -> bool:
"""Return True if canary error rate exceeds threshold."""
passRoute traffic based on configured percentage
Track success/failure rates for both stable and canary
Calculate error rate difference between canary and stable
Trigger rollback when canary error rate exceeds threshold
Support gradual traffic increase (10% -> 25% -> 50% -> 100%)
Test your implementation:
import asyncio
import random
canary = CanaryDeployment(
stable_endpoint="http://localhost:8001",
canary_endpoint="http://localhost:8002"
)
# Start with 10% canary traffic
canary.set_canary_percentage(10)
# Simulate requests
for i in range(100):
request = {"model": "test", "messages": []}
# Simulate response (canary has higher error rate)
is_canary = random.random() < 0.1
success = random.random() > (0.1 if is_canary else 0.02)
latency = random.uniform(50, 200)
canary.record_result(is_canary, success, latency)
if canary.should_rollback(error_threshold=0.05):
print(f"Rollback triggered after {i+1} requests!")
canary.set_canary_percentage(0)
break
print(f"Final canary percentage: {canary.canary_percentage}%")Add distributed tracing with OpenTelemetry
Instrument a multi-service LLM serving system with OpenTelemetry for end-to-end request tracing.
Requirements:
Create spans for each stage of request processing:
gateway.receive: Request received at gatewaygateway.route: Routing decisiontokenizer.encode: Tokenizationmodel.inference: Model inferencetokenizer.decode: Detokenizationgateway.respond: Response sent
Add attributes to spans:
model.name: Name of the modelrequest.tokens: Number of input tokensresponse.tokens: Number of output tokenslatency.ttft_ms: Time to first tokenlatency.total_ms: Total latency
Propagate trace context across service boundaries
Export traces to console or Jaeger
Test your implementation:
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
# Setup tracing
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("llm-serving")
async def process_request(request: dict):
with tracer.start_as_current_span("gateway.receive") as span:
span.set_attribute("model.name", request.get("model", "unknown"))
with tracer.start_as_current_span("tokenizer.encode"):
tokens = tokenize(request["messages"])
span.set_attribute("request.tokens", len(tokens))
with tracer.start_as_current_span("model.inference"):
output = await model.generate(tokens)
with tracer.start_as_current_span("tokenizer.decode"):
response = detokenize(output)
span.set_attribute("response.tokens", len(output))
return response
# Test with sample request
request = {
"model": "llama-3.2-1b",
"messages": [{"role": "user", "content": "What is machine learning?"}]
}
response = asyncio.run(process_request(request))Deploy multi-model serving on k3d
Deploy a multi-model LLM serving system on a local k3d cluster with GPU support.
Requirements:
Create a k3d cluster with GPU passthrough:
k3d cluster create llm-serving \ --gpus=all \ --volume /path/to/models:/models \ --port "8080:80@loadbalancer"
Deploy two vLLM instances serving different models:
Model 1:
Qwen/Qwen2.5-0.5B-Instructon port 8001Model 2:
meta-llama/Llama-3.2-1B-Instructon port 8002
Create an API gateway deployment that routes based on model name
Verify the deployment:
# List available models
curl http://localhost:8080/v1/models
# Test Model 1
curl http://localhost:8080/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model": "Qwen/Qwen2.5-0.5B-Instruct", "messages": [{"role": "user", "content": "Hello!"}]}'
# Test Model 2
curl http://localhost:8080/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model": "meta-llama/Llama-3.2-1B-Instruct", "messages": [{"role": "user", "content": "Hello!"}]}'Deliverables:
Kubernetes YAML files for vLLM deployments
API gateway deployment and service YAML
ConfigMap for model-to-service routing
Shell script to deploy and test the system
Expected learning outcomes
After completing these exercises, you should be able to:
Build API gateways that route requests to multiple model backends
Implement rate limiting to protect services from overload
Deploy canary releases with automated rollback capabilities
Instrument distributed systems with OpenTelemetry for observability
Deploy and manage LLM serving infrastructure on Kubernetes
Design production-ready serving systems with proper monitoring and fault tolerance
















Error rate and latency gates catch a broken deploy. A model swap that regresses quality still returns 200s at normal latency, so that canary would promote at every step from 10% to 100%. I'd gate each step on a sampled eval of the canary slice too, even something as cheap as refusal rate and output length drift.
A fixed initialDelaySeconds has to cover the worst case (a cold weight download on a fresh node), and it holds every warm restart out of rotation just as long. A startupProbe with failureThreshold × periodSeconds sized for that worst case lets cached restarts go Ready as soon as the server is up, then liveness takes over.