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

Zero-Downtime GPU Cluster Auto-Scaling for Distributed LLM Inference on Kubernetes

Learn how to configure Kubernetes Karpenter to dynamically scale high-density GPU workloads for generative AI models without dropping active inference connections. We explore custom metrics, node termination handlers, and eBPF-driven traffic draining strategies tailored for enterprise cloud infrastructure.

The economics of modern generative AI infrastructure are brutal. An 8-node cluster of NVIDIA H100 SXM5 instances costs tens of thousands of dollars per month. Leaving these nodes idle during off-peak traffic hours bleeds capital. However, blindly tearing down nodes using traditional Kubernetes autoscaling breaks active Server-Sent Events (SSE) and WebSocket streams, corrupting long-context LLM generation requests mid-sentence for end users.

Standard Kubernetes Horizontal Pod Autoscaler (HPA) and the legacy Cluster Autoscaler were built for stateless Web2 microservices—not for high-density GPU nodes hosting 70B+ parameter models mapped across multiple GPUs via Tensor Parallelism ($TP$) and Pipeline Parallelism ($PP$).

In this technical deep-dive, we will design and deploy an enterprise-grade, zero-downtime auto-scaling architecture for distributed LLM inference on Kubernetes. We will combine Karpenter v1.0+, KEDA, custom vLLM/DCGM metrics, and eBPF-driven socket draining to achieve rapid scale-out and non-disruptive scale-in.


End-to-End Architecture Overview

Below is the control and data plane flow for our zero-downtime auto-scaling infrastructure:

                      +-------------------+
                      | Client Ingress    |
                      | (HTTP/2 SSE)      |
                      +---------+---------+
                                |
                                v
                      +-------------------+
                      | Envoy / Cilium    | <---+
                      | Ingress Gateway   |     |
                      +---------+---------+     | (eBPF Socket Tracking)
                                |               |
              +-----------------+-----------------+
              |                                   |
              v                                   v
    +-------------------+               +-------------------+
    | Pod: vLLM (Node 1)|               | Pod: vLLM (Node 2)|
    | GPU: H100 [0..3]  |               | GPU: H100 [0..3]  |
    +---------+---------+               +---------+---------+
              |                                   |
              +-----------------+-----------------+
                                |
                                v
               +---------------------------------+
               | Prometheus / DCGM Exporter      |
               +----------------+----------------+
                                |
                                v
               +---------------------------------+
               | KEDA (ScaledObject Metric Engine)|
               +----------------+----------------+
                                |
                                v
               +---------------------------------+
               | Karpenter (NodePool Provisioner)|
               +---------------------------------+

1. Metric Signals: Beyond CPU and Memory

Autoscaling LLM inference instances based on CPU or generic GPU Utilization (DCGM_FI_DEV_GPU_UTIL) leads to severe performance degradation. GPU utilization often reports 100% even when an inference engine is processing a tiny batch, because the CUDA kernels occupy the execution units regardless of dynamic batch size.

To auto-scale accurately, you must measure KV-Cache Saturation and Pending Queue Depth.

Key Metrics for Scaling Rules

  1. vllm:num_requests_waiting: The count of pending requests in the inference engine scheduler queue. If this is $> 0$, your system is compute-bound or memory-bound, and requests are experiencing high Time-To-First-Token (TTFT) latency.
  2. vllm:gpu_cache_usage_factor: The percentage of allocated PagedAttention KV-cache memory currently in use. When this exceeds 0.85, vLLM begins preemption or swapping KV blocks to CPU memory, causing an immediate drop in Inter-Token Latency (ITL).

KEDA ScaledObject Configuration

We use KEDA (Kubernetes Event-driven Autoscaling) to trigger deployment scaling based on Prometheus queries evaluating these custom metrics.

apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: vllm-llama3-70b-scaler
  namespace: llm-inference
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: vllm-llama3-70b
  minReplicaCount: 2
  maxReplicaCount: 10
  cooldownPeriod: 300
  pollingInterval: 15
  advanced:
    horizontalPodAutoscalerConfig:
      behavior:
        scaleDown:
          stabilizationWindowSeconds: 600
          policies:
          - type: Percent
            value: 10
            periodSeconds: 60
        scaleUp:
          stabilizationWindowSeconds: 0
          policies:
          - type: Percent
            value: 100
            periodSeconds: 15
  triggers:
  - type: prometheus
    metadata:
      serverAddress: http://prometheus-k8s.monitoring.svc.cluster.local:9090
      metricName: vllm_queue_and_cache_composite
      threshold: '100'
      query: |
        sum(
          (vllm:num_requests_waiting{namespace="llm-inference"} * 50) +
          (vllm:gpu_cache_usage_factor{namespace="llm-inference"} * 100)
        )

2. Karpenter Provisioning for High-Density GPU Topologies

When KEDA scales out the vllm-llama3-70b Deployment, unschedulable Pods requesting high GPU allocations are created. Native Kubernetes Cluster Autoscaler takes up to 5 minutes to evaluate node groups and trigger cloud provider APIs. Karpenter bypasses Node Groups entirely, evaluating Pod scheduling constraints directly against available EC2/GCP/Azure instance types to launch instances within 45 seconds.

Handling Multi-GPU Topologies

For models requiring $TP=4$ or $TP=8$, inter-GPU interconnect bandwidth (NVLink / NVSwitch) is critical. Placing a $TP=8$ workload across PCIe-connected GPUs will destroy throughput.

Here is the production Karpenter NodePool and EC2NodeClass definition tuned for NVIDIA H100 (p5.48xlarge) and A100 (p4d.24xlarge) instances:

apiVersion: karpenter.sh/v1
kind: NodePool
metadata:
  name: gpu-llm-pool
spec:
  template:
    metadata:
      labels:
        workload: llm-inference
        accelerator: nvidia-h100
    spec:
      nodeClassRef:
        group: karpenter.k8s.aws
        kind: EC2NodeClass
        name: gpu-ec2-class
      requirements:
        - key: karpenter.sh/capacity-type
          operator: In
          values: ["on-demand", "spot"]
        - key: node.kubernetes.io/instance-type
          operator: In
          values: ["p5.48xlarge", "p4d.24xlarge", "g5.12xlarge"]
      taints:
        - key: nvidia.com/gpu
          value: "true"
          effect: NoSchedule
  disruption:
    consolidationPolicy: WhenEmptyOrUnderutilized
    consolidateAfter: 10m
    budgets:
      - nodes: "10%" # Limit concurrent node terminations to preserve inference capacity
---
apiVersion: karpenter.k8s.aws/v1
kind: EC2NodeClass
metadata:
  name: gpu-ec2-class
spec:
  amiSelectorTerms:
    - alias: al2023@latest # EKS Optimized AMI with NVIDIA Drivers & CUDA runtime
  subnetSelectorTerms:
    - tags:
        karpenter.sh/discovery: production-vpc
  securityGroupSelectorTerms:
    - tags:
        karpenter.sh/discovery: production-cluster
  instanceStorePolicy: RAISED # Automatically format local NVMe SSDs for model weight caching
  blockDeviceMappings:
    - deviceName: /dev/xvda
      ebs:
        volumeSize: 500Gi
        volumeType: gp3
        iops: 10000
        throughput: 1000

3. Zero-Downtime Traffic Draining Architecture

Scaling up is easy; scaling down safely without dropping active, streaming inference requests is exceptionally difficult.

An LLM token generation stream can last anywhere from 500ms to 2 minutes. If Karpenter flags a node for consolidation or an instance receives a Spot Interruption Notice (2-minute warning), standard Kubernetes pod termination (SIGTERM) followed by a hard SIGKILL after terminationGracePeriodSeconds is too blunt.

The eBPF + PreStop Connection Draining Strategy

To guarantee absolute zero downtime, we implement a three-layer draining mechanism:

  1. Traffic Isolation: Intercept the termination signal, remove the Pod from the Service Endpoint slices instantly so no new requests land on the terminating pod.
  2. eBPF-Driven Active Socket Inspection: Monitor active L7 HTTP/2 frames and L4 TCP connections at the kernel layer using eBPF probes.
  3. Graceful Engine Drain: Invoke the engine's dynamic drain API while holding the Kubernetes preStop lifecycle hook open until active streaming sockets reach zero.
[Karpenter Trigger / Spot Warning]
               |
               v
  1. Set Pod Readiness -> FALSE  (Removed from K8s EndpointSlice)
               |
               v
  2. Execute Pod Lifecycle preStop Hook
               |
               v
  3. Query eBPF Map / Socket State (Wait for active TCP streams == 0)
               |
               +---> [ Active Streams > 0 ] ---> Sleep & Loop (Max Grace Period)
               |
               +---> [ Active Streams == 0 ]
                               |
                               v
               4. Issue Engine Graceful Shutdown (SIGTERM to vLLM)

Custom eBPF Socket Monitor (C Cilium/BPF Snippet)

This light eBPF cgroup socket program tracks established, active TCP connections specifically targeted at our inference engine port (8000).

#include <linux/bpf.h>
#include <sys/socket.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_endian.h>

struct {
    __uint(type, BPF_MAP_TYPE_ARRAY);
    __uint(max_entries, 1);
    __type(key, __u32);
    __type(value, __u64);
} active_connections SEC(".maps");

SEC("sockops")
int track_inference_sockets(struct bpf_sock_ops *skops) {
    __u32 key = 0;
    __u64 *val;

    // Filter for our target LLM Engine Service Port (e.g., 8000)
    if (skops->local_port != 8000 && bpf_ntohl(skops->remote_port) != 8000) {
        return 1;
    }

    val = bpf_map_lookup_elem(&active_connections, &key);
    if (!val) return 1;

    switch (skops->op) {
        case BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB:
        case BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB:
            __sync_fetch_and_add(val, 1);
            break;
        case BPF_SOCK_OPS_STATE_CB:
            if (skops->args[1] == BPF_TCP_CLOSE || skops->args[1] == BPF_TCP_CLOSE_WAIT) {
                if (*val > 0) {
                    __sync_fetch_and_sub(val, 1);
                }
            }
            break;
    }
    return 1;
}

char _license[] SEC("license") = "GPL";

Production Pod Spec with PreStop Draining Script

Here is how we glue this logic into our Kubernetes Pod manifest using a shell script that reads sockstat/eBPF metrics inside the container before permitting container termination:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: vllm-llama3-70b
  namespace: llm-inference
spec:
  replicas: 2
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
  template:
    metadata:
      labels:
        app: vllm-llama3-70b
    spec:
      terminationGracePeriodSeconds: 300 # Allow up to 5 minutes for long streams
      containers:
      - name: vllm-engine
        image: vllm/vllm-openai:v0.6.0
        command: ["python3", "-m", "vllm.entrypoints.openai.api_server"]
        args:
          - "--model=meta-llama/Meta-Llama-3-70B-Instruct"
          - "--tensor-parallel-size=4"
          - "--gpu-memory-utilization=0.90"
          - "--max-num-seqs=256"
        ports:
          - containerPort: 8000
            name: http-inference
        readinessProbe:
          httpGet:
            path: /health
            port: 8000
          initialDelaySeconds: 120
          periodSeconds: 5
        lifecycle:
          preStop:
            exec:
              command:
                - "/bin/sh"
                - "-c"
                - |
                  # 1. Disable readiness to pull pod out of load balancer
                  touch /tmp/pod-terminating
                  echo "Pod flagged as terminating. Draining connections..."
                  
                  # 2. Loop until active TCP connections on port 8000 hit zero
                  # Uses netstat/ss to query local socket states managed by eBPF/kernel
                  while true; do
                    ACTIVE_CONNS=$(ss -Htn sport = :8000 or dport = :8000 state established | wc -l)
                    echo "Current active streaming connections: ${ACTIVE_CONNS}"
                    
                    if [ "$ACTIVE_CONNS" -eq 0 ]; then
                      echo "All active connections drained cleanly. Proceeding with SIGTERM."
                      break
                    fi
                    
                    sleep 2
                  done
        resources:
          limits:
            nvidia.com/gpu: "4"
            memory: 160Gi
            cpu: "32"
          requests:
            nvidia.com/gpu: "4"
            memory: 140Gi
            cpu: "24"

4. Mitigating Cold-Starts During Scale-Up

Auto-scaling GPU infrastructure introduces a massive operational bottleneck: Model Pull Latency. A 70B parameter model in FP16/BF16 format is roughly 140 GB. Downloading these weights from HuggingFace or S3 to a newly provisioned Node can take 5–10 minutes over standard networking, rendering rapid auto-scaling useless.

To make zero-downtime auto-scaling practical, you must solve model delivery cold-starts using a two-tier strategy:

1. Node NVMe Local Caching with Fast Read Speeds

Map host local NVMe drives (instanceStorePolicy: RAISED in Karpenter) into a persistent hostPath mount. Utilize tools like s3-mountpoint or parallelized AWS CLI streaming transfers to pull model weights at NVMe bus speeds (>4 GB/sec).

        volumeMounts:
        - mountPath: /root/.cache/huggingface
          name: model-cache
      volumes:
      - name: model-cache
        hostPath:
          path: /mnt/karpenter-nvme/huggingface
          type: DirectoryOrCreate

2. Peer-to-Peer Container Image Caching (Spegel / Dragonfly)

Instead of pulling base container images (which can be 15GB+ with CUDA runtime and PyTorch layers) repeatedly from ECR/DockerHub, deploy Spegel in your cluster. Spegel enables nodes to pull container image layers directly from sibling nodes over the local VPC network at intra-AZ speeds (up to 100 Gbps on modern AWS EC2 placement groups).


5. Architectural Verification: Scale-Down Under Load

To test this design under realistic conditions, we execute a load test using Locust sending continuous SSE streaming requests while forcing Karpenter to consolidate an underutilized GPU node.

# Force Karpenter consolidation by adjusting NodePool disruption settings
kubectl annotate node ip-10-0-42-101.ec2.internal karpenter.sh/do-not-disrupt-

# Observe the pod termination sequence in realtime
kubectl get pods -n llm-inference -w

What Happens Under the Hood:

  1. 00:00: Karpenter flags node-1 for consolidation and marks the Node as SchedulingDisabled (Cordoned).
  2. 00:01: Karpenter deletes the vllm-llama3-70b Pod on node-1.
  3. 00:01: The Pod enters the Terminating state. The preStop hook executes immediately.
  4. 00:01: EndpointSlice controller drops the Pod IP from the K8s Service. No new requests route to node-1.
  5. 00:02 - 00:42: Existing streaming inference connections continue writing generated tokens back to clients seamlessly over open TCP sockets.
  6. 00:43: The last active inference request completes its final token generation ([DONE]). The client closes the SSE connection.
  7. 00:45: The ss loop in the preStop hook detects ACTIVE_CONNS == 0 and exits with code 0.
  8. 00:46: Kubelet sends SIGTERM to the container process. vLLM releases GPU memory and CUDA contexts.
  9. 00:48: Container shuts down gracefully. Karpenter terminates the underlying EC2 instance. Client-perceived drop rate: 0.00%.

Summary Checklist for Platform Engineers

| Component | Target Configuration | Enterprise Benefit | | :--- | :--- | :--- | | Autoscaling Engine | Karpenter v1.0+ (NodePool API) | Eliminates Node Group overhead; provisions GPUs in <60 seconds. | | Scaling Metric | KV-Cache Saturation + Queue Depth | Prevents early scale-downs during active inference batches. | | Connection Draining | Custom preStop hook + eBPF/Socket Inspection | Prevents broken SSE/WebSocket token generation streams. | | Model Pre-loading | NVMe HostPath Caching + Spegel Peer-to-Peer | Drops container cold-start time from 10m to <30s. | | Disruption Safety | Karpenter Disruption Budgets + PDBs | Guarantees minimum baseline inference capacity during node drains. |

By pairing custom telemetry signals with eBPF connection state monitoring and Karpenter's high-speed provisioning engine, you can aggressively scale modern high-density GPU workloads down to zero-waste levels without sacrificing enterprise uptime guarantees.

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 →