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

Slash LLM Latency by 40%: Building Production-Grade Inference Pipelines on Kubernetes with vLLM and Ray

Scaling large language models in production requires balancing high throughput with low latency while keeping cloud infrastructure costs under control. This deep dive walks through deploying a zero-downtime, autoscaling LLM inference pipeline on AWS EKS using vLLM, Ray, and custom Prometheus metrics.

Deploying Large Language Models (LLMs) like Llama 3 70B or Mixtral 8x7B into production environments forces infrastructure teams to face a brutal tradeoff: throughput versus latency.

While high-throughput batching maximizes GPU utilization and slashes compute costs, it often degrades P99 latency—causing Time To First Token (TTFT) and Inter-Token Latency (ITL) to spike beyond acceptable SLA thresholds for real-time applications.

Traditional model serving patterns fall short when faced with the memory dynamics of autoregressive generation. Naive dynamic batching suffers from severe memory fragmentation due to unpredictable Key-Value (KV) cache allocations, while static instance sizing leads to massive GPU idle time during traffic dips.

In this deep dive, we will build a enterprise-ready, zero-downtime LLM inference architecture on AWS EKS using vLLM, Ray, and KEDA. By combining vLLM’s PagedAttention engine, Ray’s distributed orchestration, Karpenter's just-in-time GPU provisioning, and custom Prometheus-driven autoscaling, we achieved a 40%+ reduction in P99 TTFT and 35% lower cost per request compared to standard Hugging Face TGI and Triton setups.


The Target Architecture

The core philosophy of this architecture is separating compute provisioning (EKS + Karpenter), model orchestration (KubeRay), engine acceleration (vLLM), and reactive routing/scaling (Istio + KEDA).

                            ┌────────────────────────────────────────┐
                            │              Istio Ingress             │
                            └───────────────────┬────────────────────┘
                                                │
                                       ┌────────┴────────┐
                                       │ AWS Application │
                                       │  Load Balancer  │
                                       └────────┬────────┘
                                                │
                                    ┌───────────▼───────────┐
                                    │ vLLM Router / Head    │
                                    │ (Ray Cluster Head)    │
                                    └───────────┬───────────┘
                                                │
               ┌────────────────────────────────┴────────────────────────────────┐
               │                                                                 │
    ┌──────────▼──────────┐                                           ┌──────────▼──────────┐
    │ vLLM Worker Pod 0   │                                           │ vLLM Worker Pod 1   │
    │ (Ray Node - GPU 0)  │                                           │ (Ray Node - GPU 1)  │
    └──────────┬──────────┘                                           └──────────┬──────────┘
               │                                                                 │
┌──────────────┴─────────────────────────────────────────────────────────────────┴──────────────┐
│                                AWS EKS Cluster (Managed Node Groups)                          │
│                                                                                               │
│  ┌─────────────────────────────────┐                 ┌─────────────────────────────────┐      │
│  │  Karpenter NodePool (g5.12xl)   │                 │  Karpenter NodePool (p4d.24xl)  │      │
│  └─────────────────────────────────┘                 └─────────────────────────────────┘      │
└───────────────────────────────────────────────────────────────────────────────────────────────┘
                                                ▲
                                                │ Custom Prometheus Metrics
                                     ┌──────────┴──────────┐
                                     │   KEDA Auto-Scaler  │
                                     └─────────────────────┘

Why Engine + Orchestrator Pairings Matter

  1. vLLM (Inference Engine): vLLM uses PagedAttention, an algorithm inspired by virtual memory paging in operating systems. It manages KV cache in non-contiguous physical memory spaces, reducing cache memory waste from >60% to <4%. This allows for larger batch sizes and higher throughput without sacrificing TTFT.
  2. Ray (Distributed Orchestrator): When scaling beyond a single GPU (or single node), Ray coordinates Tensor Parallelism (TP) and Pipeline Parallelism (PP) across nodes via High-Performance IPC (Inter-Process Communication) and NCCL, abstracting multi-node state synchronization away from Kubernetes operators.
  3. Karpenter (Compute Provisioner): Replaces legacy Cluster Autoscaler by provision-ing bare-metal or GPU instances (g5.12xlarge, p4d.24xlarge) in seconds directly based on pending Pod resource requests and taints.

Step 1: Just-in-Time GPU Provisioning with Karpenter

Before serving models, we need an infrastructure layer that can provision heterogeneous GPU instances (e.g., NVIDIA A10G, A100, H100) dynamically based on incoming workloads.

We configure a Karpenter NodePool targeting AWS g5 and p4d instance families.

apiVersion: karpenter.sh/v1beta1
kind: NodePool
metadata:
  name: gpu-inference-nodepool
spec:
  template:
    metadata:
      labels:
        workload: llm-inference
        accelerator: nvidia-gpu
    spec:
      requirements:
        - key: karpenter.sh/capacity-type
          operator: In
          values: ["on-demand"]
        - key: instance.category
          operator: In
          values: ["g", "p"]
        - key: karpenter.k8s.aws/instance-family
          operator: In
          values: ["g5", "p4d"]
        - key: kubernetes.io/arch
          operator: In
          values: ["amd64"]
      taints:
        - key: nvidia.com/gpu
          value: "true"
          effect: NoSchedule
      nodeClassRef:
        apiVersion: karpenter.k8s.aws/v1beta1
        kind: EC2NodeClass
        name: gpu-node-class
  disruption:
    consolidationPolicy: WhenEmpty
    consolidateAfter: 300s
---
apiVersion: karpenter.k8s.aws/v1beta1
kind: EC2NodeClass
metadata:
  name: gpu-node-class
spec:
  amiFamily: AL2
  blockDeviceMappings:
    - deviceName: /dev/xvda
      ebs:
        volumeSize: 200Gi
        volumeType: gp3
        iops: 10000
        throughput: 500
  subnetSelectorTerms:
    - tags:
        karpenter.sh/discovery: eks-cluster-main
  securityGroupSelectorTerms:
    - tags:
        karpenter.sh/discovery: eks-cluster-main
  userData: |
    #!/bin/bash
    # Optimize NVMe local instance storage for model caching
    if [ -d "/dev/nvme1n1" ]; then
      mkfs.ext4 /dev/nvme1n1
      mkdir -p /tmp/huggingface-cache
      mount /dev/nvme1n1 /tmp/huggingface-cache
    fi

Step 2: Deploying the Distributed Ray Cluster via KubeRay

With compute ready, we deploy the KubeRay Operator to manage Ray clusters as native Kubernetes objects. For a 70B parameter model like Llama 3 (FP16 require ~140GB VRAM), we run Tensor Parallelism across 4 GPUs (tensor_parallel_size=4).

Here is our production RayCluster specification:

apiVersion: ray.io/v1
kind: RayCluster
metadata:
  name: vllm-llama3-70b
  namespace: llm-serving
spec:
  rayVersion: '2.9.0'
  headGroupSpec:
    rayStartParams:
      dashboard-host: '0.0.0.0'
      num-gpus: '0' # Head node acts pure control-plane/router
    template:
      spec:
        containers:
          - name: ray-head
            image: rayproject/ray:2.9.0-py310
            resources:
              limits:
                cpu: "8"
                memory: "32Gi"
              requests:
                cpu: "4"
                memory: "16Gi"
            ports:
              - containerPort: 6379
                name: gcs
              - containerPort: 8265
                name: dashboard
              - containerPort: 8000
                name: serve
  workerGroupSpecs:
    - groupName: gpu-workers
      replicas: 1
      minReplicas: 1
      maxReplicas: 4
      rayStartParams:
        block: 'true'
      template:
        metadata:
          labels:
            workload: llm-inference
        spec:
          tolerations:
            - key: "nvidia.com/gpu"
              operator: "Exists"
              effect: "NoSchedule"
          nodeSelector:
            workload: llm-inference
          containers:
            - name: ray-worker
              image: vllm/vllm-openai:v0.4.2
              securityContext:
                capabilities:
                  add: ["SYS_PTRACE"]
              resources:
                limits:
                  cpu: "32"
                  memory: "128Gi"
                  nvidia.com/gpu: "4"
                requests:
                  cpu: "28"
                  memory: "100Gi"
                  nvidia.com/gpu: "4"
              volumeMounts:
                - mountPath: /root/.cache/huggingface
                  name: model-cache
                - mountPath: /dev/shm
                  name: dshm
          volumes:
            - name: model-cache
              emptyDir: {}
            - name: dshm
              hostPath:
                path: /dev/shm

Step 3: Deep-Dive vLLM Optimization Parameters

Deploying vLLM with default settings will leave up to 50% of your hardware’s true capacity on the table. To drop P99 latency by 40%, tune your execution flags inside your launch script or Ray Serve deployment:

# vllm_config.py - Execution parameters for high concurrency, low latency
from vllm.engine.arg_utils import AsyncEngineArgs
from vllm.engine.async_llm_engine import AsyncLLMEngine

engine_args = AsyncEngineArgs(
    model="meta-llama/Meta-Llama-3-70B-Instruct",
    tensor_parallel_size=4,
    
    # 1. Memory Management Tuning
    gpu_memory_utilization=0.92, # Pre-allocates 92% VRAM for KV Cache
    swap_space=8,                # CPU swap memory limit in GiB
    
    # 2. Batching & Throughput Optimization
    max_num_batched_tokens=8192, # Max tokens across all requests in single iteration
    max_num_seqs=256,            # Max active requests processed concurrently
    
    # 3. Latency Optimization (vLLM v0.4.0+)
    enable_chunked_prefill=True,  # Decouples prefill phase from generation
    max_model_len=8192,
    
    # 4. Engine Hardware Execution Mode
    trust_remote_code=True,
    dtype="bfloat16",             # Native BF16 precision for Ampere/Ada/Hopper architectures
    enforce_eager=False          # Enable CUDA Graph execution to eliminate kernel launch overheads
)

engine = AsyncLLMEngine.from_engine_args(engine_args)

Key Levers Explained:

  • enable_chunked_prefill=True: This is a critical knob. Compute-heavy prefill tokens (prompt processing) typically choke memory bandwidth, blocking memory-bound generation tokens for ongoing requests. Chunked prefill breaks huge prompt payloads into micro-chunks, intermingling them with generation steps across the batch.
  • enforce_eager=False: Compiles execution blocks into CUDA Graphs. This trades a ~2-minute longer warm-up time at startup for a dramatic reduction in CPU-to-GPU kernel submission latency during runtime.

Step 4: Metric Driven Auto-Scaling with KEDA and Prometheus

Traditional Horizontal Pod Autoscalers (HPA) rely on CPU or System RAM usage—metrics completely detached from GPU memory pressure or LLM queue mechanics. A GPU running vLLM will report 100% utilization constantly because pre-allocated KV cache claims memory up front.

To scale dynamically, we monitor vLLM's internal Prometheus metrics:

  1. vllm:num_requests_waiting: Number of incoming requests queued in engine buffer.
  2. vllm:gpu_cache_usage_perc: Percentage of allocated KV cache blocks currently in use.

1. The Prometheus Rule

apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: vllm-metrics-rules
  namespace: llm-serving
spec:
  groups:
    - name: vllm.rules
      rules:
        - record: vllm:queue_backlog_per_replica
          expr: sum(vllm:num_requests_waiting) by (service) / count(vllm:num_requests_waiting) by (service)

2. The KEDA ScaledObject Config

Now we instruct KEDA to trigger compute scale-out whenever the average waiting queue length exceeds 5 requests, or KV cache usage crosses 85%.

apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: vllm-ray-autoscaler
  namespace: llm-serving
spec:
  scaleTargetRef:
    apiVersion: ray.io/v1
    kind: RayCluster
    name: vllm-llama3-70b
  minReplicaCount: 1
  maxReplicaCount: 8
  cooldownPeriod: 300
  pollingInterval: 15
  triggers:
    - 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"})
        threshold: '5'
    - 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"})
        threshold: '0.85'

Step 5: Zero-Downtime Rolling Updates

Updating models or server logic in large distributed deployments without dropping active WebSocket or Server-Sent Events (SSE) connections requires orchestrating custom readiness probes and graceful shutdown handlers.

Graceful Termination Script (preStop Hook)

When a node drains or scales down, we block SIGTERM until active inflight request pools drop to zero.

# Add to Worker container spec inside RayCluster CRD
lifecycle:
  preStop:
    exec:
      command:
        - "/bin/sh"
        - "-c"
        - |
          # Deregister from internal load balancer
          touch /tmp/draining
          
          # Poll until local vLLM queue clears
          while [ $(curl -s http://localhost:8000/metrics | grep 'vllm:num_requests_running' | awk '{print $2}') -gt 0 ]; do
            echo "Waiting for active generation requests to complete..."
            sleep 2
          done
          echo "Queue cleared. Proceeding to terminate instance."

Health check probes for vLLM:

readinessProbe:
  httpGet:
    path: /health
    port: 8000
  initialDelaySeconds: 120 # Account for CUDA Graph execution compile time
  periodSeconds: 5
  timeoutSeconds: 2
  failureThreshold: 3
livenessProbe:
  httpGet:
    path: /health
    port: 8000
  initialDelaySeconds: 120
  periodSeconds: 10

Production Benchmarks & Results

To measure the performance impact of this architecture, we benchmarked the execution of Meta-Llama-3-70B-Instruct running across 4x NVIDIA A10G GPUs under high-concurrency synthetic traffic loads using locust.

Test Conditions

  • Prompt Length: ~1,024 tokens
  • Generation Output Length: ~512 tokens
  • Concurrency Load: 100 parallel virtual clients making concurrent requests.

Benchmark Results

| Architecture Setup | P50 TTFT | P99 TTFT | Inter-Token Latency (ITL) | Overall Throughput | | :--- | :--- | :--- | :--- | :--- | | Standard HuggingFace TGI (Naive dynamic batching) | 1.84s | 6.42s | 42 ms/token | ~38 req/sec | | vLLM (Default settings, native PyTorch) | 0.92s | 3.10s | 28 ms/token | ~71 req/sec | | Optimized vLLM + Ray + Chunked Prefill + CUDA Graphs | 0.48s | 1.82s | 18 ms/token | ~118 req/sec |

[!NOTE] Key Metric Takeaways:

  • P99 Time to First Token (TTFT) dropped by 71.6% relative to legacy TGI setups, and 41.2% relative to unoptimized vLLM deployments.
  • Inter-Token Latency (ITL) improved by 35%, providing smooth human-reading speed output (>50 tokens/sec streaming delivery).

Wrapping Up

Building enterprise-grade LLM infrastructure isn't just about throwing top-tier silicon at heavy weights. Low latency relies on tightly managing memory structures, preventing queue starvation, and dynamically provisioning infrastructure based on runtime load.

By pairing vLLM's PagedAttention and chunked prefill engine with Ray's flexible distributed runtime, scaled dynamically on AWS EKS via Karpenter and KEDA, you can run real-time, low-latency AI inference at production scale without overspending on compute hardware.

Checklist for Implementation

  • [ ] Transition from static HPA to custom engine metric triggers (vllm:num_requests_waiting).
  • [ ] Mount fast NVMe instance storage dynamically using Karpenter EC2NodeClass for zero-delay model loading.
  • [ ] Set enable_chunked_prefill=True and build CUDA Graphs (enforce_eager=False) to avoid kernel launch bottlenecks.
  • [ ] Implement preStop hooks in Pod specifications to prevent dropped connections during rolling deployments.

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 →