Running LLMs on Kubernetes: vLLM, GPUs, autoscaling with KEDA, and costs
When it's worth hosting your own model, how to expose GPUs in the cluster, serve an LLM with vLLM and its OpenAI-compatible API, scale on the request queue with KEDA, and keep cost and latency under control.
AI$ kubectl port-forward svc/vllm 8000:8000▍Calling a model provider’s API is the fastest way to put AI into production. But at some point someone asks: “what if we ran the model in our own cluster?” Sometimes that’s the right call — and when it is, Kubernetes gives you much of what you need. This guide walks through the pieces: GPUs in the cluster, vLLM as the inference server, queue-based autoscaling with KEDA, and what to watch so you don’t burn money on idle GPUs.
API or your own model?
| Criterion | Provider API | Your own model in the cluster |
|---|---|---|
| Time to production | Minutes | Days or weeks |
| Data control | Data leaves your infrastructure (check the contract and retention) | Data stays in your environment |
| Cost | Per token; great for low or irregular volume | GPU per hour; pays off with high, steady volume |
| Quality | Access to the most capable models on the market | Limited to open models |
| Customization | Prompts and, in some cases, managed fine-tuning | Full: fine-tuning, quantization, adapters |
| Operations | The provider’s | Yours: drivers, capacity, upgrades, on-call |
Rule of thumb: start with the API. Host your own model when there is a concrete reason — a data sovereignty requirement, a volume that makes per-token billing more expensive than well-utilized GPUs, or a need for deep customization.
The pieces in the cluster
GPUs visible to Kubernetes
Kubernetes doesn’t “see” GPUs on its own. A device plugin advertises the nvidia.com/gpu resource on each node, and the scheduler starts treating it like CPU and memory (see how Kubernetes works). The NVIDIA GPU Operator installs everything at once — driver, container toolkit, device plugin, and the DCGM exporter for metrics — via Helm:
helm repo add nvidia https://helm.ngc.nvidia.com/nvidia
helm repo update
helm install gpu-operator nvidia/gpu-operator \
--namespace gpu-operator --create-namespace --wait
# check that the nodes advertise GPUs
kubectl get nodes -o custom-columns='NAME:.metadata.name,GPUS:.status.allocatable.nvidia\.com/gpu'
In managed clusters, the provider may already install the driver or the device plugin; check its documentation to avoid duplicating components.
Dedicated nodes with taints
GPUs are too expensive to host ordinary pods. Create a GPU-only node pool and apply a taint (for example, nvidia.com/gpu=present:NoSchedule), so that only pods with the matching toleration get scheduled there.
Where the model lives
Model weights take up many gigabytes. Downloading them from Hugging Face for every new pod slows down startup and may hit download limits. Options:
- A shared PVC mounted on the Hugging Face cache directory;
- Object storage (S3, GCS) with the weights pre-copied, downloaded by an init container;
- A local cache on the node, pre-warmed by a DaemonSet.
vLLM: the inference server
vLLM is an open source inference server that exposes an OpenAI-compatible API (/v1/chat/completions, /v1/completions, /v1/models). In practice, vllm serve <model> starts the server, and any client that speaks that format works by pointing at it. Two ideas explain its efficiency:
- PagedAttention: during generation, the model keeps a “scratchpad” for each conversation in GPU memory, the KV cache. Instead of reserving a large contiguous block per request (and wasting whatever is left over), vLLM splits this cache into small pages, like an operating system’s virtual memory. More concurrent requests fit on the same GPU.
- Continuous batching: instead of waiting for a whole batch to finish, new requests join the batch as soon as others complete, at every generation step. The GPU stays busy all the time.
vLLM Deployment and Service
Create the namespace and the Secret with the Hugging Face token (required for gated models), reading the value from an environment variable:
kubectl create namespace llm
kubectl -n llm create secret generic hf-token --from-literal=token="$HF_TOKEN"
The manifest below sets command explicitly so it doesn’t depend on the image’s default entrypoint — check the Dockerfile for the version you use:
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: model-cache
namespace: llm
spec:
accessModes: ["ReadWriteMany"] # requires a StorageClass with RWX (NFS, EFS, Filestore...)
resources:
requests:
storage: 200Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: vllm
namespace: llm
spec:
replicas: 1
selector:
matchLabels:
app: vllm
template:
metadata:
labels:
app: vllm
spec:
tolerations:
- key: nvidia.com/gpu
operator: Exists
effect: NoSchedule
containers:
- name: vllm
image: vllm/vllm-openai:latest # pin a specific version in production
command: ["vllm", "serve"]
args:
- "your-org/your-model" # Hugging Face ID or local path
- "--port"
- "8000"
- "--max-model-len"
- "8192" # context limit: tune it for your use case
- "--gpu-memory-utilization"
- "0.90"
env:
- name: HF_TOKEN
valueFrom:
secretKeyRef:
name: hf-token
key: token
ports:
- name: http
containerPort: 8000
resources:
requests:
cpu: "4"
memory: 32Gi
nvidia.com/gpu: 1
limits:
memory: 32Gi
nvidia.com/gpu: 1
startupProbe: # downloading and loading the model takes time
httpGet:
path: /health
port: http
periodSeconds: 10
failureThreshold: 90 # up to 15 minutes
readinessProbe:
httpGet:
path: /health
port: http
periodSeconds: 10
livenessProbe:
httpGet:
path: /health
port: http
periodSeconds: 30
volumeMounts:
- name: cache
mountPath: /root/.cache/huggingface
- name: shm
mountPath: /dev/shm # shared memory used by vLLM
volumes:
- name: cache
persistentVolumeClaim:
claimName: model-cache
- name: shm
emptyDir:
medium: Memory
sizeLimit: 8Gi
---
apiVersion: v1
kind: Service
metadata:
name: vllm
namespace: llm
labels:
app: vllm
spec:
selector:
app: vllm
ports:
- name: http
port: 8000
targetPort: http
The startupProbe keeps the kubelet from killing the pod while the model is still loading; only after it succeeds do the other probes kick in.
Testing the API
kubectl -n llm port-forward svc/vllm 8000:8000
# in another terminal
curl -s http://localhost:8000/v1/models
curl -s http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "your-org/your-model",
"messages": [{"role": "user", "content": "Explain what a Pod is in one sentence."}],
"max_tokens": 100
}'
The server has no authentication by default. Before exposing it to other teams, put it behind a gateway with authentication, per-client limits, and NetworkPolicies.
Autoscaling: why CPU doesn’t work
CPU-based HPA doesn’t fit here: the heavy lifting happens on the GPU, and a pod can be saturated while its CPU is low. The right signal is the queue. vLLM exposes Prometheus-format metrics at /metrics, such as the number of running and waiting requests (vllm:num_requests_waiting) — check the names for the version you use. With Prometheus scraping that endpoint (for example, through a ServiceMonitor), KEDA scales on the queue:
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: vllm
namespace: llm
spec:
scaleTargetRef:
name: vllm
minReplicaCount: 1
maxReplicaCount: 4
pollingInterval: 15
advanced:
horizontalPodAutoscalerConfig:
behavior:
scaleDown:
stabilizationWindowSeconds: 600 # don't drop expensive replicas over a short dip
triggers:
- type: prometheus
metadata:
serverAddress: http://prometheus-operated.monitoring.svc:9090
query: sum(vllm:num_requests_waiting{namespace="llm"})
threshold: "5" # average waiting requests per replica
Remember that every new replica needs a free GPU. Combine KEDA with a node autoscaler (Cluster Autoscaler or Karpenter) and a maximum GPU limit.
The cold start problem
A new replica can take several minutes to become ready: provisioning the GPU node, pulling a large image, loading the weights into GPU memory. That’s why scaling to zero is a trade-off: it saves GPU money in development environments or rarely used internal tools, but the first request waits minutes. In production, keep at least one replica and shorten cold starts with cached weights and images pre-pulled on the nodes.
Higher-level options
If you don’t want to assemble everything by hand, some projects package these patterns: KServe (model serving with CRDs, with a vLLM-based runtime), llm-d (Kubernetes-native distributed inference built on vLLM, with cache-aware routing), and Ray Serve (serving on top of Ray, with the KubeRay operator). Evaluate maturity and fit with your team; the ecosystem moves fast.
Costs
The biggest source of waste is idle GPUs. The main levers:
- Size by memory: at 16 bits, weights take about 2 bytes per parameter, and the KV cache needs the remaining space. Pick the smallest GPU where the model and context fit with headroom.
- Quantization: 8- or 4-bit formats cut memory and cost, with some quality loss — measure before adopting.
- Share GPUs with MIG or time-slicing for small models.
- Spot for batch jobs: offline inference (classifying thousands of tickets overnight) tolerates interruptions.
The cost-per-million-tokens calculation and the spot GPU NodePool with Karpenter are in FinOps for AI and LLMs.
Observability
| Metric | What it tells you | Source |
|---|---|---|
| Tokens per second | Actual server throughput | vLLM token counters |
| TTFT (time to first token) | Perceived speed in streaming responses | vLLM histogram |
| End-to-end latency (p50/p95) | Full user experience | vLLM or gateway |
| Waiting requests | Saturation and need to scale | vLLM |
| GPU memory and KV cache usage | How close you are to capacity | DCGM exporter and vLLM |
| GPU utilization | Idleness (waste) or saturation | DCGM exporter |
These metrics show server health; answer quality requires evaluation and per-request traces, the subject of the article on LLMOps.
Checklist
- Concrete reason to host the model (data, cost at scale, or customization)
- GPU Operator or equivalent installed and
nvidia.com/gpuvisible on the nodes - GPU node pool with a taint and pods with a toleration
- Model weights cached (PVC, object storage, or local cache)
- vLLM image pinned to a version, with
/healthprobes and a startupProbe - KEDA scaling on the request queue, with a maximum GPU limit
- Dashboard with tokens/s, TTFT, latency, and GPU utilization
An idle GPU costs the same as a busy one: scale on the queue, not on CPU.