Ecstaticloud
Initializing0%
Ecstaticloud Logo
Back to all insights
Enterprise AI & LLMOpsNovember 1, 2026• 8 min read

Scaling vLLM Inference on Kubernetes: A Guide to Zero-Waste GPU Autoscaling

Discover how to optimize deep learning inference costs by dynamically scaling GPU workloads on Kubernetes using vLLM and KEDA. We dive deep into custom metrics, cold-start mitigation, and architectural patterns for resilient enterprise AI deployments.

Deploying Large Language Models (LLMs) in enterprise production environments introduces a stark reality: GPUs are astonishingly expensive, and static provisioning is financial suicide.

If you run an NVIDIA H100 or A10G cluster 24/7 at 15% average utilization to accommodate unpredictable traffic spikes, you are burning capital. However, standard Kubernetes Horizontal Pod Autoscalers (HPA) driven by CPU or memory metrics are entirely blind to LLM serving bottlenecks. Even naive GPU utilization metrics (container_gpu_utilization) fall short because an LLM worker can be fully saturated in VRAM while registering low compute activity.

In this guide, we will design and deploy a Zero-Waste GPU Autoscaling Architecture on Kubernetes using vLLM as the high-throughput inference engine, KEDA (Kubernetes Event-driven Autoscaling) for metric-driven scaling, and Karpenter for rapid just-in-time GPU node provisioning.


Architecture Overview

Achieving scale-to-zero and sub-second reactive scaling for multi-billion parameter models requires tight coordination across the entire infrastructure stack:

                  [ Incoming API Requests ]
                              │
                              ▼
                  [ Ingress Controller / Gateway ]
                              │
       ┌──────────────────────┴──────────────────────┐
       │                                             │
       ▼                                             ▼
[ Prometheus ] ◄── (Scrapes Metrics) ─── [ vLLM Inference Pods ]
       │                                             ▲
       ▼                                             │
[ KEDA Operator ] ── (Scales Deployments) ───────────┘
       │
       ▼ (Creates Pending Pods)
[ Kubernetes Scheduler ]
       │
       ▼ (Triggers Node Provisioning)
[ Karpenter Controller ] ──► [ Provision AWS EC2 g5/p4 Node ]

Components Breakdown:

  1. vLLM Engine: Serves model weights using PagedAttention, exposes custom Prometheus metrics (queue size, KV cache usage, request latency).
  2. Prometheus: Aggregates real-time engine telemetry.
  3. KEDA: Evaluates custom PromQL triggers to scale vLLM Deployment replicas (including Scale-to-Zero).
  4. Karpenter: Intercepts un-schedulable GPU pod events and provisions exact-fit cloud instances (e.g., g5.2xlarge or p4d.24xlarge) in under 45 seconds.

Why Standard Metrics Fail for LLM Autoscaling

Standard Kubernetes HPA relies on metrics like CPU utilization or system memory. LLM inference workloads break this paradigm for three key reasons:

1. VRAM Allocation vs. Compute Activity

When vLLM initializes, it pre-allocates almost all available GPU VRAM to store model weights and manage the KV Cache pool. A standard system metric tool reports ~95% GPU memory consumption even when zero requests are processing.

2. The Illusion of GPU Compute Utilization

GPU compute (NVIDIA SMI utilization.gpu) fluctuates violently depending on batch sizes and decoding steps. During the autoregressive generation phase, execution moves rapidly between memory-bound token generation and compute-bound prefill phases. Scaling on GPU compute percent leads to severe thrashing (flapping).

3. Queue Saturation as the Golden Signal

The true health of an LLM worker is determined by two custom metrics exposed by vLLM:

  • vllm:num_requests_waiting: Requests queued because the KV cache is full or max batch size is reached.
  • vllm:gpu_cache_usage_perc: Percentage of allocated KV cache blocks currently occupied.

If vllm:num_requests_waiting > 0, your system is degrading; latency is increasing linearly for incoming callers. This is your primary scaling signal.


Step 1: Deploying vLLM with Custom Metrics

First, let's deploy vLLM. We will configure it to expose metrics on port 8000 and optimize its engine flags for enterprise throughput.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: vllm-llama3-8b
  namespace: llm-serving
  labels:
    app: vllm-llama3-8b
spec:
  replicas: 1
  selector:
    matchLabels:
      app: vllm-llama3-8b
  template:
    metadata:
      labels:
        app: vllm-llama3-8b
      annotations:
        prometheus.io/scrape: "true"
        prometheus.io/port: "8000"
        prometheus.io/path: "/metrics"
    spec:
      containers:
      - name: vllm-engine
        image: vllm/vllm-openai:v0.4.2
        args:
        - "--model"
        - "meta-llama/Meta-Llama-3-8B-Instruct"
        - "--port"
        - "8000"
        - "--max-model-len"
        - "8192"
        - "--gpu-memory-utilization"
        - "0.90"
        - "--enable-chunked-prefill"
        env:
        - name: HUGGING_FACE_HUB_TOKEN
          valueFrom:
            secretKeyRef:
              name: hf-secret
              key: token
        ports:
        - containerPort: 8000
          name: metrics
        resources:
          limits:
            nvidia.com/gpu: "1"
            memory: 32Gi
            cpu: "8"
          requests:
            nvidia.com/gpu: "1"
            memory: 16Gi
            cpu: "4"
        readinessProbe:
          httpGet:
            path: /health
            port: 8000
          initialDelaySeconds: 60
          periodSeconds: 5
        livenessProbe:
          httpGet:
            path: /health
            port: 8000
          initialDelaySeconds: 120
          periodSeconds: 15
        volumeMounts:
        - mountPath: /root/.cache/huggingface
          name: model-cache
      volumes:
      - name: model-cache
        persistentVolumeClaim:
          claimName: llm-model-cache-pvc

Step 2: Configuring KEDA for Dynamic Metrics & Scale-to-Zero

To achieve zero-waste scaling, KEDA must perform two tasks:

  1. Scale from 0 to 1: Scale up when requests enter the system (either via an ingress HTTP proxy metric or queue proxy).
  2. Scale from 1 to N: Scale horizontally when vllm:num_requests_waiting increases or vllm:gpu_cache_usage_perc exceeds safe thresholds (e.g., 85%).

Here is the production-ready ScaledObject configuration using custom PromQL queries.

apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: vllm-llama3-autoscaler
  namespace: llm-serving
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: vllm-llama3-8b
  minReplicaCount: 0 # Zero-Waste Enablement
  maxReplicaCount: 10
  cooldownPeriod: 300 # Prevent rapid scale-down (5 mins window)
  pollingInterval: 15
  advanced:
    horizontalPodAutoscalerConfig:
      behavior:
        scaleUp:
          stabilizationWindowSeconds: 0
          policies:
          - type: Percent
            value: 100
            periodSeconds: 15
        scaleDown:
          stabilizationWindowSeconds: 300
          policies:
          - type: Percent
            value: 10
            periodSeconds: 60
  triggers:
  # Trigger 1: Queue Backlog (Scale up immediately if requests are waiting)
  - type: prometheus
    metadata:
      serverAddress: http://prometheus-k8s.monitoring.svc.cluster.local:9090
      metricName: vllm_num_requests_waiting
      query: |
        sum(vllm:num_requests_waiting{namespace="llm-serving", model_name="meta-llama/Meta-Llama-3-8B-Instruct"})
      threshold: '1'
  # Trigger 2: High KV Cache Usage (Scale up before running out of VRAM memory)
  - type: prometheus
    metadata:
      serverAddress: http://prometheus-k8s.monitoring.svc.cluster.local:9090
      metricName: vllm_gpu_cache_usage_perc
      query: |
        avg(vllm:gpu_cache_usage_perc{namespace="llm-serving", model_name="meta-llama/Meta-Llama-3-8B-Instruct"})
      threshold: '0.85'

Step 3: Mitigating Cold-Start Latency (The LLM Scale-to-Zero Challenge)

Scaling down to zero saves thousands of dollars monthly, but introduces a massive cold-start penalty. Loading an 8B parameter model (~16GB in FP16/BF16) from Hugging Face over standard Internet connections during a scale-from-zero event can take 3 to 7 minutes.

To drive cold starts down to under 20 seconds, we must optimize weight distribution across three layers:

[ Layer 1: Container Image ] ──► Pre-bakes vLLM and CUDA dependencies
[ Layer 2: Local Node Storage ] ──► Local HostPath NVMe caches model weights
[ Layer 3: High-Speed Loading ] ──► Shared ReadOnlyMany Storage (JuiceFS / EFS)

Strategy A: Shared High-Throughput Storage (JuiceFS / AWS EFS)

Mount model storage via a high-performance distributed filesystem backed by S3 with local NVMe caching.

Strategy B: Container Image Pre-warming with Node Storage (DaemonSets)

Utilize a lightweight local cache directory using node local NVMe drives (hostPath). Combine this with an initContainer that pre-fetches model weights or pre-loads them from an S3 VPC endpoint over 10 Gbps+ network links.

Here is an optimized volume design utilizing AWS S3 via high-throughput concurrent transfers:

initContainers:
- name: model-loader
  image: amazon/aws-cli:latest
  command: ["sh", "-c"]
  args:
    - |
      IF_EXISTS=$(ls -A /local-cache/Meta-Llama-3-8B-Instruct)
      if [ -z "$IF_EXISTS" ]; then
        echo "Cache miss. Fetching from high-speed S3 Bucket..."
        aws s3 sync s3://my-enterprise-llm-weights/Meta-Llama-3-8B-Instruct /local-cache/Meta-Llama-3-8B-Instruct --exact-timestamps
      else
        echo "Cache hit. Skipping fetch."
      fi
  volumeMounts:
  - mountPath: /local-cache
    name: host-nvme-cache

Strategy C: Fast Weight Initialization via safetensors

Ensure model weights are stored strictly in .safetensors format rather than legacy PyTorch .bin pickles. safetensors allows mmap (memory-mapped file I/O), allowing vLLM to read weights directly from disk into GPU VRAM using direct zero-copy operations, drastically cutting deserialization overhead.


Step 4: Rapid Node Infrastructure Provisioning with Karpenter

Autoscaling vLLM pods is useless if Kubernetes pods remain stuck in a Pending state waiting for compute nodes to launch. Native Kubernetes Cluster Autoscaler is often too slow (taking 3–5 minutes to evaluate and launch GPU nodes).

Karpenter bypasses the standard node-group abstraction and provisions instance types directly in under 45 seconds.

Karpenter NodePool Configuration for GPU Node Acceleration

apiVersion: karpenter.sh/v1beta1
kind: NodePool
metadata:
  name: gpu-node-pool
spec:
  template:
    spec:
      requirements:
        - key: kubernetes.io/arch
          operator: In
          values: ["amd64"]
        - key: kubernetes.io/os
          operator: In
          values: ["linux"]
        - key: karpenter.sh/capacity-type
          operator: In
          values: ["on-demand", "spot"] # Fall back to on-demand if spot is unavailable
        - key: karpenter.k8s.aws/instance-category
          operator: In
          values: ["g", "p"]
        - key: karpenter.k8s.aws/instance-family
          operator: In
          values: ["g5", "g6"] # EC2 instance families with NVIDIA A10G / L4 GPUs
      nodeClassRef:
        apiVersion: karpenter.k8s.aws/v1beta1
        kind: EC2NodeClass
        name: gpu-node-class
  disruption:
    consolidationPolicy: WhenEmpty
    consolidateAfter: 300s # Reclaim idle GPU nodes 5 minutes after pod deletion
---
apiVersion: karpenter.k8s.aws/v1beta1
kind: EC2NodeClass
metadata:
  name: gpu-node-class
spec:
  amiFamily: AL2 # Amazon Linux 2 with pre-installed NVIDIA CUDA Drivers
  blockDeviceMappings:
    - deviceName: /dev/xvda
      ebs:
        volumeSize: 200Gi
        volumeType: gp3
        iops: 10000
        throughput: 500
  securityGroupSelectorTerms:
    - tags:
        karpenter.sh/discovery: my-cluster
  subnetSelectorTerms:
    - tags:
        karpenter.sh/discovery: my-cluster

Step 5: Production-Ready Graceful Termination

Scaling down GPU pods prematurely causes interrupted inference streams, returning partial JSON objects or truncated responses to users.

When vLLM receives a SIGTERM, it must stop accepting new connection requests, complete ongoing active generation streams, and flush metrics.

Implementing Graceful Shutdown in Pod Lifecycle

spec:
  template:
    spec:
      terminationGracePeriodSeconds: 120 # Give active inference streams 2 minutes to drain
      containers:
      - name: vllm-engine
        lifecycle:
          preStop:
            exec:
              command:
                - "/bin/sh"
                - "-c"
                - |
                  # 1. Deregister pod from service routing or hit local drain endpoint
                  echo "Stopping incoming traffic to pod..."
                  sleep 5
                  # 2. Wait for active inference requests (num_requests_running) to reach zero
                  while [ $(curl -s http://localhost:8000/metrics | grep 'vllm:num_requests_running' | awk '{print $2}') -gt 0 ]; do
                    echo "Waiting for active LLM generation requests to finish..."
                    sleep 2
                  done
                  echo "Drain complete. Shutting down safely."

Production Observability Checklist

Before deploying this architecture to production, ensure the following dashboard rules and alerts are configured in Prometheus/Grafana:

| Metric Name | Target Threshold | Operational Meaning | | :--- | :--- | :--- | | vllm:num_requests_waiting | > 0 | Request queue forming; system is capacity-constrained. | | vllm:gpu_cache_usage_perc | > 0.85 | KV cache saturation imminent; context truncation risk. | | vllm:avg_time_to_first_token_seconds | < 0.5s | TTFT metric. Spike indicates prefill-phase bottlenecks. | | vllm:avg_time_per_output_token_seconds | < 0.05s | Inter-token latency. High value indicates memory-bandwidth bottlenecks. |


Summary

Scaling LLM infrastructure does not mean choosing between massive cloud bills or high request latencies.

By combining vLLM's internal metric primitives with KEDA's event-driven scaling, Karpenter's swift instance provisioning, and optimized model loading techniques, you establish a zero-waste deployment pattern. Your GPU infrastructure automatically shrinks to zero during low-traffic windows and dynamically expands to handle heavy production surges—optimizing both performance and infrastructure costs.

Need Help Scaling Cloud Infrastructure?

Partner with Ecstaticloud's boutique engineering architects to implement zero-trust architectures, optimize inference workloads, or eliminate cloud waste.

Talk to an Architect
Deep Dives

Related Technical Insights

View all →