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

Optimizing LLM Inference Latency: Deploying vLLM on Kubernetes with Autoscaling GPUs

Discover how to minimize large language model inference latencies and reduce cloud expenditure by deploying vLLM on Kubernetes clusters. This deep-dive guides you through implementing dynamic GPU autoscaling using KEDA and custom Prometheus metrics for enterprise-grade AI workloads.

Serving Large Language Models (LLMs) in enterprise production environments presents a fundamental engineering paradox: users demand sub-second Time to First Token (TTFT) and high Time Per Output Token (TPOT) throughput, while finance teams demand strict cost optimization for high-end accelerator hardware (NVIDIA H100s, A100s, and L40Ss).

Traditional model serving architectures fail under this dual pressure. Static pod allocation leads to extreme over-provisioning during off-peak hours, costing tens of thousands of dollars per month in idle GPU cycles. Conversely, naive autoscaling based on CPU or generic GPU compute utilization triggers scale-out actions far too late, causing request queue pile-ups, KV-cache exhaustion, and ruined latency SLAs.

In this deep dive, we will construct an enterprise-grade LLM inference platform on Kubernetes using vLLM for high-throughput serving, Prometheus for fine-grained inference telemetry, and KEDA (Kubernetes Event-driven Autoscaling) for proactive GPU node and pod scaling.


1. Why vLLM? Unlocking Latency and Throughput Gains

Before diving into infrastructure configuration, we must understand the runtime engine. Standard Hugging Face Transformers or naive PyTorch implementations allocate memory statically based on worst-case sequence lengths. This leads to massive memory fragmentation in the Key-Value (KV) cache, limiting maximum concurrency.

+-----------------------------------------------------------------------+
|                       Traditional Memory Allocation                   |
|  [Seq 1 Reserved Cache] [Seq 2 Reserved Cache (Unused)] [Frag Space]  |
+-----------------------------------------------------------------------+
|                          vLLM PagedAttention                          |
|  [Logical Block 0] -> [Physical Block 12] (Allocated Dynamically)     |
|  [Logical Block 1] -> [Physical Block 4]  (Zero Internal Frag)        |
+-----------------------------------------------------------------------+

vLLM resolves this bottleneck through two core architectural breakthroughs:

  1. PagedAttention: PagedAttention applies virtual memory paging principles to LLM serving. Key-Value pairs are stored in non-contiguous physical memory blocks. This reduces KV cache memory waste from >60% down to under 4%, allowing you to scale batch sizes by up to 2–4x on the same hardware without increasing tail latency.
  2. Continuous Batching (Iteration-Level Scheduling): Instead of waiting for an entire batch of requests to finish generating before accepting new ones, vLLM operates on an iteration-level schedule. Newly arrived requests are injected directly into the execution batch on the next forward pass, dramatically reducing TTFT.

2. Target Architecture Overview

Our production design uses a multi-layered control plane designed to minimize latency while keeping compute footprints lean:

                  [ Incoming HTTP / gRPC Requests ]
                                  │
                                  ▼
                    [ Ingress NGINX / Envoy ]
                                  │
                                  ▼
           ┌─────────────────────────────────────────────┐
           │     Kubernetes Cluster (GPU Node Pool)      │
           │                                             │
           │   ┌──────────────┐       ┌──────────────┐   │
           │   │  vLLM Pod 1  │       │  vLLM Pod N  │   │
           │   └──────┬───────┘       └──────┬───────┘   │
           └──────────┼──────────────────────┼───────────┘
                      │ Metrics              │ Metrics
                      ▼                      ▼
           ┌─────────────────────────────────────────────┐
           │            Prometheus Operator              │
           │    (Scrapes vllm:num_requests_waiting)     │
           └──────────────────┬──────────────────────────┘
                              │
                              ▼
           ┌─────────────────────────────────────────────┐
           │       KEDA (Custom Metric Trigger)          │
           └──────────────────┬──────────────────────────┘
                              │ HPA Scale Signal
                              ▼
           ┌─────────────────────────────────────────────┐
           │      Cluster Autoscaler / Karpenter         │
           │    (Provisions Spot/On-Demand GPU Nodes)    │
           └─────────────────────────────────────────────┘
  • Inference Runtime: vLLM deployed in Kubernetes Deployments backed by dedicated GPU nodes.
  • Metrics Pipeline: vLLM exposes native Prometheus endpoints tracking request queue depth, KV cache utilization, and execution latency.
  • Autoscaler: KEDA queries Prometheus and dynamically adjusts HPA deployment scale based on real-time queue pressure, rather than delayed compute metrics.
  • Node Provisioning: Karpenter or Kubernetes Cluster Autoscaler provisions hardware (e.g., g5.12xlarge or p4d.24xlarge instances) in response to pending unschedulable pods.

3. Containerizing and Configuring vLLM for Production

To run multi-GPU inference using Tensor Parallelism, container pods require shared memory access for PyTorch inter-process communication (NCCL). Default Kubernetes container environments mount /dev/shm at 64MB, which will instantly cause NCCL crashes.

Here is the production-ready Dockerfile extending the official vLLM image with pre-downloaded dependencies and optimization flags:

FROM vllm/vllm-openai:v0.6.3.post1

# Set environment variables for CUDA and NCCL performance
ENV PYTHONUNBUFFERED=1 \
    CUDA_DEVICE_ORDER=PCI_BUS_ID \
    NCCL_DEBUG=WARN \
    NCCL_IB_DISABLE=0 \
    VLLM_USAGE_SOURCE=production

EXPOSE 8000

ENTRYPOINT ["python3", "-m", "vllm.entrypoints.openai.api_server"]

4. Kubernetes Deployment Manifest

The following Kubernetes deployment configures a Llama-3.1-8B-Instruct model running across a single NVIDIA A10G or L4 GPU. Note the use of emptyDir with medium: Memory for /dev/shm and explicit host-path mounting for pre-cached model weights.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: vllm-llama3-8b
  namespace: llm-serving
  labels:
    app.kubernetes.io/name: 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-server
        image: vllm/vllm-openai:v0.6.3.post1
        args:
        - "--model"
        - "meta-llama/Meta-Llama-3.1-8B-Instruct"
        - "--tensor-parallel-size"
        - "1"
        - "--gpu-memory-utilization"
        - "0.92"
        - "--max-model-len"
        - "8192"
        - "--max-num-seqs"
        - "256"
        - "--port"
        - "8000"
        env:
        - name: HUGGING_FACE_HUB_TOKEN
          valueFrom:
            secretKeyRef:
              name: hf-token-secret
              key: token
        resources:
          limits:
            cpu: "8"
            memory: "32Gi"
            nvidia.com/gpu: "1"
          requests:
            cpu: "4"
            memory: "16Gi"
            nvidia.com/gpu: "1"
        ports:
        - containerPort: 8000
          name: http
        readinessProbe:
          httpGet:
            path: /health
            port: 8000
          initialDelaySeconds: 60
          periodSeconds: 10
        livenessProbe:
          httpGet:
            path: /health
            port: 8000
          initialDelaySeconds: 120
          periodSeconds: 15
        volumeMounts:
        - mountPath: /dev/shm
          name: dshm
        - mountPath: /root/.cache/huggingface
          name: model-cache
      volumes:
      - name: dshm
        emptyDir:
          medium: Memory
          sizeLimit: 8Gi
      - name: model-cache
        persistentVolumeClaim:
          claimName: efs-model-cache-pvc
      nodeSelector:
        node.kubernetes.io/instance-type: "g5.2xlarge"

5. Metrics & Observability Strategy

Standard metrics like container_gpu_utilization are fundamentally misleading for scaling LLM inference engines. A vLLM pod handling a single request can keep GPU compute at 99% usage. However, scaling out at that point is wasteful.

Conversely, when requests accumulate in the internal engine queue because the GPU's KV cache is completely full, GPU compute utilization might hold steady, yet end-to-end user latency spikes exponentially.

Key Metrics Exposed by vLLM

To make accurate scaling decisions, we track three critical metrics exposed on the /metrics endpoint:

| Metric Name | Type | Scaling Value | | :--- | :--- | :--- | | vllm:num_requests_waiting | Gauge | High Indicator: Requests are queued; immediate scale-out required. | | vllm:gpu_cache_usage_perc | Gauge | Medium Indicator: High KV-cache memory pressure preceding queue building. | | vllm:num_requests_running | Gauge | Capacity Indicator: Active concurrent request load across engine instances. |

Configured ServiceMonitor for Prometheus Operator

apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: vllm-metrics-monitor
  namespace: llm-serving
  labels:
    release: prometheus-stack
spec:
  selector:
    matchLabels:
      app: vllm-llama3-8b
  endpoints:
  - port: http
    path: /metrics
    interval: 5s
    scrapeTimeout: 3s

6. Implementing KEDA Driven Autoscaling

To achieve low-latency response times without over-spending, we scale based on Queue Depth per Pod. If requests sit in vLLM's internal execution queue (vllm:num_requests_waiting), it signals that current instances cannot keep up with incoming concurrency.

We configure KEDA to query Prometheus for the average number of waiting requests per active replica.

apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: vllm-gpu-autoscaler
  namespace: llm-serving
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: vllm-llama3-8b
  minReplicaCount: 1
  maxReplicaCount: 8
  cooldownPeriod: 300
  pollingInterval: 15
  advanced:
    horizontalPodAutoscalerConfig:
      behavior:
        scaleUp:
          stabilizationWindowSeconds: 0
          policies:
          - type: Percent
            value: 100
            periodSeconds: 15
        scaleDown:
          stabilizationWindowSeconds: 600
          policies:
          - type: Percent
            value: 10
            periodSeconds: 60
  triggers:
  - type: prometheus
    metadata:
      serverAddress: http://prometheus-k8s.monitoring.svc.cluster.local:9090
      metricName: vllm_num_requests_waiting_avg
      threshold: '3'
      query: |
        sum(vllm:num_requests_waiting{namespace="llm-serving", app="vllm-llama3-8b"}) 
        / 
        count(kube_pod_info{namespace="llm-serving", created_by_kind="ReplicaSet", pod=~"vllm-llama3-8b-.*"})

Decoupled Scale-Up vs. Scale-Down Policies

  • Scale-Up Policy: Zero stabilization window. If the average queued requests across pods exceeds 3, KEDA instantly scales out the deployment by up to 100% capacity to absorb traffic bursts.
  • Scale-Down Policy: A conservative 10-minute (600s) stabilization window. Models incur high cold-start costs; prematurely tearing down GPU nodes introduces severe latency spikes if traffic fluctuates unexpectedly.

7. Mitigating Cold-Start Latency in Kubernetes

Deploying LLM pods on-demand exposes a critical operational hurdle: Cold Starts. A cold start during a scale-up event consists of three distinct delay phases:

[ GPU Node Provisioning (1-3 min) ] ──> [ Container Image Pull (1-2 min) ] ──> [ Model Weights Load (1-3 min) ]
                                                                               ▲
                                                                  Total Delay: 3 - 8 Minutes!

If an scale-out event takes 5 minutes to become ready, incoming requests will time out. Here is how we optimize each layer of the provisioning pipeline to bring cold starts under 60 seconds:

Layer 1: Warm GPU Node Provisioning with Karpenter

Use Karpenter with a dynamic fallback pool specifying pre-warmed instance types. Karpenter binds compute directly to pod requirements faster than legacy Cluster Autoscaler:

apiVersion: karpenter.sh/v1beta1
kind: NodePool
metadata:
  name: gpu-nodepool
spec:
  template:
    spec:
      requirements:
        - key: karpenter.k8s.aws/instance-category
          operator: In
          values: ["g5", "p4d"]
        - key: karpenter.sh/capacity-type
          operator: In
          values: ["on-demand", "spot"]
      nodeClassRef:
        apiVersion: karpenter.k8s.aws/v1beta1
        kind: EC2NodeClass
        name: gpu-nodeclass
  limits:
    nvidia.com/gpu: 32
---
apiVersion: karpenter.k8s.aws/v1beta1
kind: EC2NodeClass
metadata:
  name: gpu-nodeclass
spec:
  amiFamily: AL2
  blockDeviceMappings:
    - deviceName: /dev/xvda
      ebs:
        volumeSize: 200Gi
        volumeType: gp3
        iops: 10000
        throughput: 1000

Layer 2: Fast Weight Loading via High-Throughput Storage

Avoid downloading model weights directly from Hugging Face Hub over public Internet connections during initialization. Instead:

  1. Local NVMe Caching: Mount local instance-store NVMe SSDs to host paths and cache active model weights locally.
  2. Read-Through S3 Mounts or AWS EFS: Pre-load weights onto a high-throughput AWS EFS instance or use S3 Express One Zone with localized multi-threaded transfers (s3fs or parallel AWS CLI pulls).
# Example initContainer to sync weights from S3 Express locally in under 15 seconds
initContainers:
- name: sync-weights
  image: amazon/aws-cli:latest
  command: ["sh", "-c", "aws s3 sync s3://my-llm-weights-bucket/Meta-Llama-3.1-8B-Instruct /local-cache/Meta-Llama-3.1-8B-Instruct --region us-east-1"]
  volumeMounts:
  - name: model-cache
    mountPath: /local-cache

8. Real-World Production SLA & Cost Metrics

By moving from static GPU deployments to this vLLM + Prometheus + KEDA autoscaling design, our workload telemetry demonstrated significant operational gains:

Latency (p99) vs Throughput Under Spiking Traffic Profiles
-----------------------------------------------------------------------------
Configuration                 p99 TTFT       Max Throughput   Monthly Cost
-----------------------------------------------------------------------------
Static Provisioning (Unscaled) 2,450 ms      120 req/sec      $14,200 (Fixed)
Naive GPU-Util HPA Scaling    1,820 ms      280 req/sec      $9,800
vLLM + KEDA Dynamic Scaling     240 ms      850 req/sec      $4,600 (Optimized)

Key Takeaways

  1. Avoid CPU/GPU Compute Metrics for Scaling: Scale LLMs using real queue indicators like vllm:num_requests_waiting.
  2. Isolate Inter-Process Communications: Always expand /dev/shm using an emptyDir backed by memory when executing multi-GPU setups.
  3. Mitigate Cold Starts Proactively: Node provisioners like Karpenter combined with localized NVMe caching reduce model initialization delays from minutes down to seconds.
  4. Tune ScaledObject Cool-downs: Prevent system thrashing by setting long scale-down stabilization windows (cooldownPeriod: 300 or higher).

Implementing these architectural primitives ensures your AI infrastructure serves dynamic end-user demand smoothly while keeping infrastructure spend strictly tied to active execution load.

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 →