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

Architecting Cost-Efficient LLM Inference at Scale: Leveraging vLLM and Custom Kubernetes Autoscalers

Discover how to dramatically cut cloud GPU expenditure while maintaining sub-second latency for large language model inference using vLLM and dynamic Kubernetes pod autoscaling. This deep dive provides actionable architecture patterns and benchmarking data for engineering teams running LLMs in production.

In the current generative AI boom, the true bottleneck for tech companies isn't fine-tuning models—it's running them in production at scale without going broke. Deploying Large Language Models (LLMs) like Llama 3 70B or Mistral 8x22B presents a brutal infrastructural trade-off: over-provision expensive GPU nodes to handle unpredictable traffic spikes, or risk degrading latency SLAs to unacceptable levels during peak load.

At Ecstaticloud, we recently overhauled an enterprise client's LLM inference pipeline. By moving away from naive HuggingFace Transformers/Triton setups running on static compute to an optimized vLLM engine coupled with KEDA-driven Kubernetes autoscaling, we slashed their monthly cloud GPU bill by 68% while maintaining a Time To First Token (TTFT) under 120ms and P99 latency SLA under 800ms.

This deep dive exposes the precise architectural blueprint, code manifests, and metrics required to reproduce these results in your production environment.


1. The Bottlenecks of Naive LLM Inference

Understanding why traditional autoscaling fails requires dissecting how LLMs utilize GPU hardware. Standard microservices scale on CPU/Memory thresholds or request rates. However, LLM inference is fundamentally bounded by two distinct factors:

  1. Compute-bound (Prefill Phase): Processing the input prompt to generate the first token (TTFT).
  2. Memory-Bandwidth-bound (Decode Phase): Generating subsequent tokens one by one (Time Per Output Token - TPOT).
   +-----------------------------------------------------------------------+
   |                        LLM Inference Pipeline                         |
   +-----------------------------------------------------------------------+
   |  [ Input Prompt ]                                                     |
   |         │                                                             |
   |         ▼                                                             |
   |   Prefill Phase  ──► Compute-Bound  ──► Generates First Token (TTFT)  |
   |         │                                                             |
   |         ▼                                                             |
   |   Decode Phase   ──► Memory-Bound   ──► Generates Token Stream (TPOT) |
   |         │            (KV Cache)                                       |
   |         ▼                                                             |
   |  [ Output Stream ]                                                    |
   +-----------------------------------------------------------------------+

When using naive serving frameworks, the Key-Value (KV) cache for a request is allocated in contiguous GPU memory blocks upfront based on the maximum context length (e.g., 4096 or 8192 tokens). This leads to severe internal memory fragmentation—often up to 60-80% wasted VRAM. Because VRAM is fully reserved even when idle, traditional metrics like container_gpu_utilization or container_memory_usage_bytes sit at ~95%+ constantly, rendering default Kubernetes Horizontal Pod Autoscalers (HPA) completely blind.


2. Core Engine: High-Throughput Serving via vLLM

To maximize token throughput per dollar, we swap standard inference runtimes for vLLM. vLLM addresses GPU memory inefficiency using three primary innovations:

PagedAttention

Inspired by virtual memory paging in operating systems, PagedAttention breaks the KV cache into small physical memory blocks. Tokens do not need to be stored in contiguous physical memory space.

Logical Blocks (Sequence KV Cache):
[ Block 0 ] [ Block 1 ] [ Block 2 ]
     │           │           │
     ▼           ▼           ▼
Physical GPU Memory Pages (Non-contiguous):
[ Page 14 ] ... [ Page 02 ] ... [ Page 89 ]

This reduces KV cache memory waste to under 4%, allowing you to scale up batch sizes dramatically without running into Out-Of-Memory (OOM) crashes.

Continuous Batching (Iteration-Level Scheduling)

Instead of processing requests in static batch sizes where fast requests wait for slow ones to complete, vLLM injects arriving requests into the running engine iteration by iteration. As soon as a sequence emits an end-of-sequence (<eos>) token, its memory pages are evicted, and a queued request takes its place immediately.

Quantization Efficiency

Running vLLM with FP8 or AWQ (Activation-aware Weight Quantization) yields up to 2.5x higher token throughput compared to FP16 with negligible drop in perplexity, enabling larger models to run on single-GPU hardware (e.g., running Llama 3 70B across 2x A100-80GB instead of 4x A100-80GB via Tensor Parallelism).


3. Kubernetes Infrastructure Architecture

To run vLLM cost-effectively, the cluster infrastructure must separate stateless request routers from heavy GPU worker nodes.

                                  [ Ingress NGINX / Gateway API ]
                                                 │
                                                 ▼
                                     [ vLLM Router Service ]
                                                 │
                 ┌───────────────────────────────┴───────────────────────────────┐
                 ▼                                                               ▼
    [ GPU Node Pool 1: On-Demand ]                                 [ GPU Node Pool 2: Spot/Interruptible ]
    ┌────────────────────────────┐                                 ┌────────────────────────────────────┐
    │  Pod: vLLM-Llama3 (Primary)│                                 │  Pod: vLLM-Llama3 (Preemptible)    │
    │  Allocated: 1x L4/A10G GPU │                                 │  Allocated: 1x L4/A10G GPU         │
    └────────────────────────────┘                                 └────────────────────────────────────┘

Cluster Design Principles

  1. Heterogeneous Node Pools: Split nodes into On-Demand (baseline SLA) and Spot/Interruptible (cost optimization) pools using nodeSelector and tolerations.
  2. GPU Driver Integration: Use the NVIDIA GPU Operator for transparent driver management, persistence mode enforcement, and exporter integration.
  3. Graceful Degradation: Use PodDisruptionBudgets and long termination grace periods (terminationGracePeriodSeconds: 120) to allow vLLM to finish active requests when Spot nodes receive termination signals.

4. Designing Custom Autoscaling Logic with KEDA

Because default GPU utilization reported by NVML shows 99% usage whenever vLLM pre-allocates its GPU memory pool, we must base autoscaling on vLLM operational telemetry.

vLLM exposes rich Prometheus metrics on :8000/metrics. The two critical scaling indicators are:

  1. vllm:num_requests_waiting: The number of requests sitting in the queue because the GPU KV cache is full.
  2. vllm:gpu_cache_usage_perc: Real-time physical page utilization of the KV cache.

The Metric Trigger Strategy

  • Scale-Out Condition: When vllm:num_requests_waiting > 3 or vllm:gpu_cache_usage_perc > 0.85 for more than 30 seconds.
  • Scale-In Condition: When vllm:num_requests_waiting == 0 and vllm:gpu_cache_usage_perc < 0.30 for a sustained period (e.g., 300 seconds).

5. Production Manifests Implementation

Here is the exact production configuration to deploy a scalable vLLM deployment targeting Llama-3-8B-Instruct with KEDA metrics tracking.

Step 1: Deploy vLLM Workload

apiVersion: apps/v1
kind: Deployment
metadata:
  name: vllm-llama3-8b
  namespace: llm-serving
  labels:
    app: vllm-llama3-8b
spec:
  replicas: 2
  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:
      terminationGracePeriodSeconds: 120
      containers:
      - name: vllm-container
        image: vllm/vllm-openai:v0.4.2
        args:
        - "--model"
        - "meta-llama/Meta-Llama-3-8B-Instruct"
        - "--tensor-parallel-size"
        - "1"
        - "--max-model-len"
        - "8192"
        - "--gpu-memory-utilization"
        - "0.90"
        - "--port"
        - "8000"
        env:
        - name: HUGGING_FACE_HUB_TOKEN
          valueFrom:
            secretKeyRef:
              name: hf-token-secret
              key: token
        ports:
        - containerPort: 8000
          name: http
        resources:
          limits:
            nvidia.com/gpu: "1"
            cpu: "8"
            memory: "32Gi"
          requests:
            nvidia.com/gpu: "1"
            cpu: "4"
            memory: "16Gi"
        readinessProbe:
          httpGet:
            path: /health
            port: 8000
          initialDelaySeconds: 120
          periodSeconds: 10
        livenessProbe:
          httpGet:
            path: /health
            port: 8000
          initialDelaySeconds: 120
          periodSeconds: 15
---
apiVersion: v1
kind: Service
metadata:
  name: vllm-llama3-service
  namespace: llm-serving
  labels:
    app: vllm-llama3-8b
spec:
  type: ClusterIP
  ports:
  - port: 8000
    targetPort: 8000
    name: http
  selector:
    app: vllm-llama3-8b

Step 2: Configure KEDA ScaledObject

This manifest creates a dynamic scaler monitoring the waiting request queue depth via Prometheus.

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: 1
  maxReplicaCount: 10
  cooldownPeriod: 300
  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:
  - type: prometheus
    metadata:
      serverAddress: http://prometheus-k8s.monitoring.svc.cluster.local:9090
      metricName: vllm_num_requests_waiting_avg
      query: |
        sum(vllm:num_requests_waiting{namespace="llm-serving", app="vllm-llama3-8b"}) 
        / 
        count(vllm:num_requests_waiting{namespace="llm-serving", app="vllm-llama3-8b"})
      threshold: '3'

6. Real-Time Metrics Extraction Script

If you run a custom scaling controller or want to write a lightweight Python sidecar to collect engine parameters, here is how to extract and evaluate current engine pressure via vLLM metrics.

import requests
import re
import time
import logging

logging.basicConfig(level=logging.INFO)

VLLM_METRICS_URL = "http://vllm-llama3-service.llm-serving.svc.cluster.local:8000/metrics"

def fetch_vllm_telemetry():
    try:
        response = requests.get(VLLM_METRICS_URL, timeout=5)
        response.raise_for_status()
        metrics_raw = response.text

        # Parse metrics using regex
        waiting_requests = re.search(
            r'vllm:num_requests_waiting\{.*?\}\s+([\d\.]+)', metrics_raw
        )
        gpu_cache_usage = re.search(
            r'vllm:gpu_cache_usage_perc\{.*?\}\s+([\d\.]+)', metrics_raw
        )

        num_waiting = float(waiting_requests.group(1)) if waiting_requests else 0.0
        cache_perc = float(gpu_cache_usage.group(1)) if gpu_cache_usage else 0.0

        return {
            "waiting_requests": num_waiting,
            "gpu_cache_utilization": cache_perc
        }
    except Exception as e:
        logging.error(f"Failed to fetch metrics: {e}")
        return None

def evaluate_scale_action(telemetry):
    if not telemetry:
        return "HOLD"
    
    if telemetry["waiting_requests"] > 5 or telemetry["gpu_cache_utilization"] > 0.85:
        return "SCALE_OUT"
    elif telemetry["waiting_requests"] == 0 and telemetry["gpu_cache_utilization"] < 0.20:
        return "SCALE_IN"
    
    return "HOLD"

if __name__ == "__main__":
    while True:
        telemetry = fetch_vllm_telemetry()
        action = evaluate_scale_action(telemetry)
        logging.info(f"Telemetry: {telemetry} | Recommended Action: {action}")
        time.sleep(10)

7. Benchmarking & ROI Analysis

We benchmarked three architecture configurations under a variable synthetic load (simulating global enterprise traffic over a 24-hour cycle) using Llama 3 8B Instruct on NVIDIA A10G (24GB) instances on AWS (g5.xlarge).

  • Baseline Target SLA: TTFT < 200ms, TPOT < 30ms per token.
  • Peak Load: 250 Concurrent Streams.

Throughput & Latency Performance

| Engine & Deployment Model | Mean TTFT (ms) | Mean TPOT (ms) | P99 Latency (ms) | Max Throughput (tok/sec) | | :--- | :--- | :--- | :--- | :--- | | Naive HF Pipelines + Default HPA | 640ms | 85ms | 3,400ms | ~140 tok/sec | | vLLM (Static 8 Pods) | 95ms | 22ms | 510ms | ~1,250 tok/sec | | vLLM + KEDA Autoscaler (Spot/OD Mix) | 108ms | 24ms | 540ms | ~1,250 tok/sec |

Cost Breakdown (Monthly Projection)

Monthly Cost Comparison ($ USD)
========================================================================
Naive HF Pipeline (Fixed 12 Nodes On-Demand)   : $9,011 [100%]
vLLM Static Provisioning (8 Nodes On-Demand)   : $6,007 [ 66%]
vLLM + KEDA (Avg 3.2 Nodes, Spot Strategy)     : $2,883 [ 32%]  <-- 68% Savings
========================================================================
  1. Naive HF Pipeline (Fixed 12 x g5.xlarge On-Demand): High latency due to poor batching mechanics. Over-provisioned to sustain unpredictable load spikes. Cost: ~$9,011 / month.
  2. vLLM Static (Fixed 8 x g5.xlarge On-Demand): PagedAttention allows higher concurrency per card. Card count reduced from 12 to 8. Cost: ~$6,007 / month (33% savings).
  3. vLLM + KEDA Dynamic Scaling (Mixed On-Demand + Spot): Scaled dynamically between 1 and 8 pods based on vllm:num_requests_waiting. Average running node count dropped to 3.2 instances, leveraging AWS Spot pricing for non-baseline capacity. Cost: ~$2,883 / month (68% total cost reduction).

Conclusion & Architectural Key Takeaways

Scaling LLM inference cost-effectively requires abandoning classical infrastructure paradigms:

  • Discard default utilization metrics: GPU utilization percentage is a misleading indicator for inference scaling.
  • Optimize the engine first: Engine-level enhancements (PagedAttention, quantized formats, and continuous batching) yield far more throughput per dollar than scaling under-optimized containers.
  • Scale on real queue metrics: Leverage KEDA to parse custom application-layer engine telemetry (vllm:num_requests_waiting and KV cache saturation).
  • Leverage Spot nodes aggressively: Decouple state, configure generous termination periods, and handle node preemption gracefully to safely utilize cheap compute.

By combining vLLM's memory management with event-driven Kubernetes autoscaling, you transform your AI platform from a massive cost center into a resilient, self-optimizing engine capable of scaling smoothly from low-traffic troughs to sudden high-concurrency peaks.

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 →