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

Optimizing LLM Inference Latency: A Deep Dive into Dynamic GPU Batching on Kubernetes

Discover how to slash GenAI operational costs and reduce P99 inference latency by implementing dynamic GPU batching on auto-scaling Kubernetes clusters. We unpack the end-to-end technical architecture for zero-downtime model deployments using vLLM, Triton, and custom Prometheus metrics.

In the realm of Generative AI, serving Large Language Models (LLMs) like Llama-3, Mistral, or custom fine-tuned Transformer models presents a fundamentally different engineering challenge compared to traditional stateless microservices. Standard HTTP services scale predictably on CPU and memory thresholds. In contrast, LLM inference is severely bound by GPU VRAM capacity, memory bandwidth during the autoregressive decoding phase, and massive compute costs during the prefill phase.

If you deploy an LLM using naive static batching or single-request inference endpoints, you face a painful trade-off: either accept astronomical cloud bills to keep P99 latency low, or saturate GPUs and watch P99 latency explode as request queues back up.

At Ecstaticloud, we recently re-engineered our client inference platform on Kubernetes, transitioning from standard request-level queuing to iteration-level continuous dynamic batching paired with metric-driven autoscaling. The result? A 68% drop in P99 latency and a 42% reduction in compute costs.

In this technical deep dive, we unpack the architecture, configuration manifests, and custom autoscaling topologies required to achieve these results in production.


1. The Bottleneck: Static Batching vs. Iteration-Level Dynamic Batching

To understand why dynamic batching is essential, we must examine how LLMs generate tokens.

An LLM inference request consists of two distinct phases:

  1. Prefill Phase: The model processes the entire prompt in parallel to build the initial Key-Value (KV) cache. This phase is compute-bound.
  2. Decode Phase: The model generates tokens one by one autoregressively. Each new token requires reading the entire KV cache from VRAM. This phase is memory bandwidth-bound.

Static Batching

Traditional web servers bundle $N$ incoming requests into a single tensor, pad sequences to match the longest prompt in the batch, and execute the forward pass.

Request 1: [Prompt: 50 tokens ] [Gen: 10 tokens] [PAD PAD PAD PAD PAD PAD]
Request 2: [Prompt: 10 tokens ] [Gen: 60 tokens]
Request 3: [Prompt: 200 tokens] [Gen: 5 tokens ] [PAD PAD PAD PAD]
  • Flaw 1 (Padding Overhead): Short requests are padded with useless tokens, wasting precious GPU compute cycles and VRAM.
  • Flaw 2 (Early Completion Lock-in): If Request 3 finishes after 5 tokens, its GPU memory remains locked until Request 2 finishes generating all 60 tokens.
  • Flaw 3 (Queue Delays): Incoming requests must wait until the entire running static batch completes.

Dynamic Continuous Batching (Iteration-Level Scheduling)

Popularized by frameworks like vLLM (via PagedAttention) and Triton Inference Server, continuous batching operates at the iteration level (per-token generation cycle) rather than the request level.

Iteration t:   [Req 1 - Step 4] [Req 2 - Step 12] [Req 3 - Prefill]
Iteration t+1: [Req 1 - Step 5] [Req 2 - Step 13] [Req 4 - Prefill]  <-- Req 3 completed, Req 4 inserted seamlessly!

As soon as a request finishes token generation, its VRAM (allocated in logical blocks via PagedAttention) is reclaimed immediately. New requests are scheduled into the execution engine on the very next token iteration without waiting for the running batch to exit.


2. High-Level Architecture on Kubernetes

To implement continuous batching reliably at scale, the architecture relies on five primary components:

  1. Ingress Controller / API Gateway: Traefik or Envoy handling client streaming connections (Server-Sent Events / SSE) with gRPC/HTTP2 multiplexing.
  2. Inference Pods (vLLM Engine): Optimized containers running on dedicated GPU node groups (e.g., NVIDIA A10G, L4, or H100 instances).
  3. NVIDIA GPU Operator: Manages CUDA drivers, container toolkits, and dynamic device plugin allocations within EKS/GKE.
  4. Prometheus Operator: Scrapes fine-grained vLLM metrics (num_requests_waiting, gpu_cache_usage_factor).
  5. KEDA (Kubernetes Event-driven Autoscaling): Scales GPU deployment pods based on custom queue-depth metrics rather than misleading CPU/GPU utilization percentages.
                      +-------------------+
                      |   Client Application   |
                      +---------+---------+
                                | (HTTP/SSE or gRPC)
                                v
                      +-------------------+
                      | Envoy API Gateway |
                      +---------+---------+
                                |
             +------------------+------------------+
             |                                     |
             v                                     v
+------------------------+             +------------------------+
|   vLLM Pod 1 (GPU)     |             |   vLLM Pod 2 (GPU)     |
| Continuous Batch Engine|             | Continuous Batch Engine|
+-----------+------------+             +-----------+------------+
            |                                      |
            +------------------+-------------------+
                               | Metrics Export
                               v
                      +-------------------+
                      | Prometheus Server |
                      +---------+---------+
                                | Prometheus Query
                                v
                      +-------------------+
                      |   KEDA Controller |
                      +---------+---------+
                                | Scale Signal
                                v
                      +-------------------+
                      | K8s Deployment    |
                      +-------------------+

3. Production vLLM Deployment Manifest

Below is a production-grade Kubernetes deployment manifest for serving meta-llama/Meta-Llama-3-8B-Instruct using vLLM on a cluster equipped with NVIDIA A10G (24GB VRAM) or L4 GPUs.

Key optimizations in this setup:

  • shared memory (/dev/shm) mounting to prevent PyTorch IPC memory crashes.
  • Tensor Parallelism configured to match GPU topology.
  • PagedAttention chunked prefill enabled to balance compute and memory phases.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: vllm-llama3-8b
  namespace: llm-serving
  labels:
    app.kubernetes.io/name: 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:
      nodeSelector:
        node.kubernetes.io/instance-type: "g5.2xlarge" # AWS EC2 instance with 1x NVIDIA A10G
      tolerations:
        - key: "nvidia.com/gpu"
          operator: "Exists"
          effect: "NoSchedule"
      containers:
        - name: vllm-server
          image: vllm/vllm-openai:v0.6.0
          args:
            - "--model"
            - "meta-llama/Meta-Llama-3-8B-Instruct"
            - "--port"
            - "8000"
            - "--max-model-len"
            - "8192"
            - "--gpu-memory-utilization"
            - "0.92"
            - "--enable-chunked-prefill"
            - "true"
            - "--max-num-seqs"
            - "256"
          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"
              memory: 32Gi
              cpu: "8"
            requests:
              nvidia.com/gpu: "1"
              memory: 16Gi
              cpu: "4"
          volumeMounts:
            - mountPath: /dev/shm
              name: dshm
          readinessProbe:
            httpGet:
              path: /health
              port: 8000
            initialDelaySeconds: 120
            periodSeconds: 10
          livenessProbe:
            httpGet:
              path: /health
              port: 8000
            initialDelaySeconds: 120
            periodSeconds: 15
      volumes:
        - name: dshm
          emptyDir:
            medium: Memory
            sizeLimit: 8Gi

4. Alternative: Configuring Dynamic Batching on Triton Inference Server

If your architecture standardizes on Triton Inference Server with backend models (e.g., TensorRT-LLM or vLLM engine), dynamic batching can be tuned explicitly via Triton’s config.pbtxt.

Here is an optimized Triton declarative configuration leveraging strict dynamic batching delay windows:

name: "ensemble_llama_model"
platform: "ensemble"
max_batch_size: 128

dynamic_batching {
  # Dynamic batching window: balance processing delay vs throughput
  max_queue_delay_microseconds: 5000  # 5ms window to accumulate requests
  preferred_batch_size: [ 16, 32, 64, 128 ]
  
  # Priority queues: ensure system-critical requests execute first
  priority_levels: 2
  default_priority_level: 2
}

model_transaction_policy {
  decoupled: true # Enables streaming response protocol
}

5. Metric-Driven Autoscaling with KEDA & Prometheus

Why Standard HPA Fails for LLMs

Standard Kubernetes Horizontal Pod Autoscaler (HPA) policies rely on CPU or GPU Compute Utilization percentage. This causes critical performance issues for LLM workloads:

  1. GPU Utilization is misleading: An LLM worker pod generating tokens for a single user will register near 100% GPU compute utilization during execution loops, even if the node could handle 50 additional requests via continuous batching.
  2. Delayed Scaling: Standard CPU metrics don't reflect request queue backup, leading to high P99 latency before scaling triggers.

The Correct Autoscaling Metric: Queue Depth & KV Cache Usage

We must scale based on exposed engine runtime metrics:

  • vllm:num_requests_waiting: Requests sitting in the engine queue due to memory/compute saturation.
  • vllm:gpu_cache_usage_perc: Fraction of PagedAttention KV-cache memory currently allocated.

Here is a deployment-ready KEDA ScaledObject that scales out when the average waiting queue depth crosses 5 requests or when GPU KV-cache usage hits 85%.

apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: vllm-autoscaler
  namespace: llm-serving
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: vllm-llama3-8b
  minReplicaCount: 2
  maxReplicaCount: 10
  cooldownPeriod: 300
  pollingInterval: 15
  advanced:
    horizontalPodAutoscalerConfig:
      behavior:
        scaleUp:
          stabilizationWindowSeconds: 0
          policies:
            - type: Percent
              value: 100
              periodSeconds: 15
        scaleDown:
          stabilizationWindowSeconds: 600 # Conservative scaledown to prevent cold-starts
  triggers:
    # Trigger 1: Scale based on unserved queue requests
    - 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", app="vllm-llama3-8b"}) 
          / 
          count(kube_pod_container_status_running{namespace="llm-serving", container="vllm-server"})
        threshold: '5'
        
    # Trigger 2: Scale based on KV Cache saturation
    - 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", app="vllm-llama3-8b"})
        threshold: '0.85'

6. Real-World Benchmarks & Results

To measure performance, we ran dynamic load tests using Locust simulating 200 concurrent user streams hitting Llama-3-8B (Prompt Tokens: ~512, Generated Tokens: ~128).

| Setup Metrics | Naive Static Batching (HPA GPU%) | Continuous Dynamic Batching (vLLM + KEDA Queue Metrics) | Net Improvement | | :--- | :--- | :--- | :--- | | P50 Latency | 1,420 ms | 410 ms | 71.1% Faster | | P99 Latency | 8,950 ms | 2,820 ms | 68.5% Reduction | | Throughput (Tokens/sec) | 210 tok/s | 890 tok/s | 4.2x Increase | | Average GPU Utilization | Unstable (0% - 100% spikes) | Sustained 88% | Optimal Compute Sizing | | Monthly Compute Cost | $14,200 | $8,230 | 42% Saved |


7. Architectural Production Pitfalls to Avoid

  1. Cold Boot Latency: Large models (e.g., 70B parameters requiring multiple GPUs) take minutes to download weights from remote storage or Hugging Face.
    • Mitigation: Bake model weights into local NVMe PVs via DaemonSets, use specialized cached volumes, or deploy fluid local model proxy caches (e.g., Spegel, JuiceFS).
  2. Ignoring OOM Errors on Long Contexts: When requests send massive prompts, continuous batch memory can fragment if max model length parameters aren't explicitly bounded.
    • Mitigation: Always enforce strict --max-model-len limits and leverage --enable-chunked-prefill to slice long prefill steps into smaller execution blocks alongside decode steps.
  3. Aggressive Scale-Down Rules: GPU pods take time to initialize, load model weights into CUDA memory, and pass health checks.
    • Mitigation: Set high scale-down stabilization windows in KEDA (e.g., 600+ seconds) to avoid dropping pods prematurely during minor traffic dips.

Wrap Up

Unlocking low-latency, cost-effective LLM inference requires a shift away from legacy CPU microservice scaling patterns. By pairing iteration-level dynamic batching (vLLM/PagedAttention) with queue-depth aware metrics (KEDA + Prometheus), you can maximize hardware utilization while keeping interactive P99 response times well within strict SLA thresholds.

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 →