Autoscaling LLM Inference on Kubernetes: Scale on Queue Depth, Not CPU

Khimananda Oli 9 min read AI and Machine Learning
Autoscaling LLM Inference on Kubernetes: Scale on Queue Depth, Not CPU

By Khimananda Oli | Last reviewed: November 2026

Most teams deploying large language models hit a wall when they apply standard web app scaling logic to GPU workloads. Autoscaling LLM inference on Kubernetes: Scale on Queue Depth, Not CPU is the operational shift required to prevent both massive tail latency during traffic bursts and wasted spend during idle periods. Traditional Horizontal Pod Autoscalers (HPA) relying on CPU or memory fail because LLM servers like vLLM or TGI saturate compute differently; you must trigger scaling decisions based on pending request queues to match actual user demand.

If you are familiar with horizontal pod autoscaling in Kubernetes, you know HPA works brilliantly for stateless microservices where CPU correlates linearly with throughput. For generative AI, that correlation breaks completely. A single long-context generation request can pin a GPU at 100% while the queue fills up behind it, yet the aggregate cluster CPU might look deceptively low. Conversely, batched prefill operations can spike CPU without indicating true GPU saturation. The solution is aligning your autoscaler directly with the business signal: how many requests are waiting.

CPU-Based Scaling (Broken)Traffic SpikeGPU SaturatedCPU: 40% (Low)No Scale-UpQueue OverflowsP99 Latency > 30sQueue-Depth Scaling (Correct)Traffic SpikeQueue Depth: 12Threshold: 8KEDA TriggersNew GPU Pod ReadyLatency Stable
CPU metrics lag behind actual LLM demand, while queue-depth triggers anticipate load before users suffer.

Why does autoscaling LLM inference on Kubernetes require queue depth instead of CPU?

Large language model serving is fundamentally different from REST API serving due to batching dynamics and hardware constraints. Modern inference engines like vLLM use continuous batching, meaning they pack multiple requests into a single forward pass. This maximizes GPU throughput but decouples resource utilization from individual request latency.

When you rely on CPU utilization for autoscaling LLM inference on Kubernetes: Scale on Queue Depth, Not CPU, you encounter three specific failure modes:

  • The Batch Masking Effect: A GPU running at 95% utilization processing a batch of 32 requests looks identical to one processing a single request. CPU metrics cannot distinguish between healthy throughput and overloaded saturation.
  • Prefill vs. Decode Asymmetry: The prefill phase (processing input tokens) is compute-bound and may spike CPU/GPU briefly. The decode phase (generating output tokens) is memory-bandwidth bound. Average utilization smooths out these phases, hiding the moment when decode latency starts climbing.
  • Cold Start Misalignment: Loading a 70B parameter model takes minutes. By the time CPU metrics register sustained high usage and HPA triggers a scale-up, users have already timed out. Queue depth rises immediately when capacity is insufficient, providing the earliest possible signal.

In my experience helping Nepal-based startups and global enterprises optimize their AI infrastructure, the teams that succeed treat LLM serving as a queuing problem, not a compute problem. Your SLO isn't "keep GPU under 80%"; it's "serve tokens within 2 seconds." Only queue depth maps directly to that SLO.

How do you expose queue depth metrics from vLLM for Kubernetes autoscaling?

Before KEDA can scale anything, your inference server must emit reliable queue metrics. Most production-grade serving frameworks expose these via Prometheus endpoints natively.

Configuring vLLM Metric Export

vLLM exposes critical metrics at /metrics by default. The key metric for autoscaling is vllm:num_requests_waiting, which tracks requests queued but not yet scheduled. You also want vllm:gpu_cache_usage_perc as a secondary guardrail.

# Deployment annotation for Prometheus scraping
metadata:
  annotations:
    prometheus.io/scrape: "true"
    prometheus.io/port: "8000"
    prometheus.io/path: "/metrics"

# Verify metrics are exposed
curl -s http://vllm-service:8000/metrics | grep vllm:num_requests_waiting
# HELP vllm:num_requests_waiting Number of requests waiting to be processed.
# TYPE vllm:num_requests_waiting gauge
vllm:num_requests_waiting 4.0

A common mistake is scraping only aggregate metrics when running multi-model deployments. If you serve multiple LoRAs or models on one pod, ensure metrics include model labels so KEDA scales based on the specific workload experiencing pressure. Without proper Prometheus metrics fundamentals, your autoscaler will react to noise rather than signal.

Validating Metric Freshness

Queue depth changes in milliseconds. If your Prometheus scrape interval is 30 seconds, KEDA sees stale data. For LLM workloads, set scrape intervals to 5–10 seconds. Also verify that your Prometheus retention and query range align with KEDA’s polling frequency. I recommend testing with a synthetic load generator like Locust to confirm metric responsiveness before trusting production traffic to the autoscaler.

vLLM Pod/metrics :8000num_requests_waitingScrape 5sPrometheusTSDB StorageQuery EnginePoll 10sKEDAScaledObjectTrigger LogicPatch ReplicasK8s APIDeploymentGPU Node PoolCritical: Scrape interval ≤ 10s ensures KEDA reacts before queue-induced latency violates SLOs
End-to-end metric pipeline from vLLM to Kubernetes API server enabling queue-aware autoscaling.

How do you configure KEDA ScaledObject for LLM queue depth thresholds?

KEDA (Kubernetes Event-driven Autoscaling) bridges Prometheus queries and the Kubernetes HPA controller. Unlike native HPA, KEDA supports external metrics and custom formulas essential for autoscaling LLM inference on Kubernetes: Scale on Queue Depth, Not CPU.

Defining the ScaledObject Manifest

This configuration targets an average queue depth of 8 pending requests per pod. When the average exceeds this, KEDA adds replicas. When it drops below 4 for the cooldown period, it removes them.

apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: vllm-queue-scaler
  namespace: ai-inference
spec:
  scaleTargetRef:
    name: vllm-deployment
  minReplicaCount: 1
  maxReplicaCount: 8
  cooldownPeriod: 300      # Prevent flapping after scale-down
  pollingInterval: 10       # Match Prometheus scrape cadence
  triggers:
  - type: prometheus
    metadata:
      serverAddress: http://prometheus.monitoring:9090
      metricName: vllm_queue_depth_per_pod
      query: |
        sum(vllm:num_requests_waiting{namespace="ai-inference"}) 
        / 
        count(kube_pod_status_ready{namespace="ai-inference", condition="true", pod=~"vllm.*"})
      threshold: "8"
      activationThreshold: "1"  # Don't scale from 0 until first request arrives
      authModes: "basic"

The division by ready pods is crucial. Raw queue depth alone causes oscillation: adding a pod doesn't instantly drain the queue, so raw depth stays high and triggers another scale-up prematurely. Normalizing by active replicas gives KEDA a stable per-pod pressure signal.

Tuning Thresholds for Your Model

There is no universal threshold. A 7B model handling short chat completions might tolerate 20 queued requests per GPU. A 70B model doing RAG with 8K context windows might degrade at 4. Benchmark your specific workload:

  1. Run a load test at fixed concurrency levels.
  2. Plot P95 token-time-to-first-token (TTFT) against queue depth.
  3. Set your threshold at the inflection point where TTFT exceeds your SLO.
  4. Add 20% headroom for burst absorption.

I've seen teams skip this benchmarking and pick arbitrary thresholds, then wonder why they either overspend or burn SLOs. Data beats intuition here. For deeper guidance on defining meaningful targets, see defining meaningful SLIs and SLOs.

What are the trade-offs between queue depth, GPU utilization, and hybrid autoscaling strategies?

Pure queue-depth scaling solves latency problems but can leave money on the table if not combined with guardrails. Understanding the trade-offs helps you build a resilient system for autoscaling LLM inference on Kubernetes: Scale on Queue Depth, Not CPU.

Metric StrategyLatency ResponseCost EfficiencyRisk ProfileBest For
CPU/GPU Utilization OnlyPoor (lagging indicator)High (packs tightly)SLO violations during burstsBatch offline jobs
Queue Depth OnlyExcellent (leading indicator)Moderate (may over-provision)Oscillation if unnormalizedInteractive chat APIs
Hybrid (Queue + GPU Guardrail)ExcellentOptimalComplex configProduction multi-tenant
Request Rate (RPS)Good for uniform workloadsPoor for variable-lengthFails on long-context spikesSimple embedding APIs

The hybrid approach uses queue depth as the primary scaler but caps maximum replicas based on GPU utilization ceilings. This prevents runaway scaling when a bug causes infinite retries or when metrics are temporarily corrupted. Implement this with KEDA’s fallback configuration or by chaining multiple triggers with AND/OR logic.

Autoscaling Strategy Selection MatrixCPU/GPU OnlyLatency: PoorCost: High EfficiencyQueue DepthLatency: ExcellentCost: ModerateHybrid (Recommended)Latency: ExcellentCost: OptimalRPS OnlyLatency: VariableCost: Low EfficiencyUse for: Batch ETLUse for: Chat APIsUse for: Production Multi-TenantUse for: EmbeddingsKey Insight: Queue depth predicts latency; GPU utilization confirms efficiencyCombine both signals to balance user experience with cloud spendAlways normalize queue depth by ready replica count to prevent oscillation
Strategy comparison showing hybrid queue-plus-utilization approach as optimal for production LLM serving.

How do you prevent cold start penalties and oscillation when scaling GPU pods?

Scaling LLM pods isn't like scaling nginx. Model loading takes 30–180 seconds depending on size and storage speed. During this window, the new pod accepts no traffic but counts toward replica calculations, potentially causing KEDA to over-scale.

Implementing Readiness Gates for Model Loading

Your readiness probe must verify the model is loaded and the KV cache is initialized, not just that the HTTP port responds. vLLM supports a /health endpoint that returns 200 only after model weights are in VRAM.

readinessProbe:
  httpGet:
    path: /health
    port: 8000
  initialDelaySeconds: 60     # Allow model load time
  periodSeconds: 5
  failureThreshold: 30        # 150s total tolerance
  timeoutSeconds: 3

Without this, KEDA sees the pod as ready prematurely, routes traffic to an unprepared instance, and triggers cascading failures. This is especially critical when setting resource limits and requests for GPU nodes, as scheduler placement adds additional delay.

Damping Oscillation with Cooldown and Activation Thresholds

LLM traffic is spiky. Set cooldownPeriod to at least 5 minutes for scale-down. GPU costs are dominated by provisioning overhead; keeping a warm spare for 5 extra minutes is cheaper than reloading models repeatedly. Use activationThreshold to prevent scaling from zero until genuine demand exists, avoiding test-request-triggered wakeups.

For teams managing compliance-sensitive AI workloads, remember that autoscaling behavior affects audit trails. Every scale event should be logged with the triggering metric value. This connects directly to LLMOps monitoring and guardrails practices that satisfy SOC 2 evidence requirements around capacity management.

Operationalizing Queue-Depth Autoscaling for Production LLM Workloads

Migrating to autoscaling LLM inference on Kubernetes: Scale on Queue Depth, Not CPU requires more than YAML changes—it demands a mental model shift. Start by instrumenting your current serving stack to collect baseline queue depth data without enabling autoscaling. Observe the correlation between queue depth and user-facing latency for two weeks. Only then define thresholds grounded in real SLOs, not guesses.

Test aggressively in staging with synthetic load that mimics your production token distribution. Long-tail requests matter more than averages. Monitor KEDA’s own metrics (keda_scaler_metrics_value) alongside your inference metrics to detect scaler lag or query failures early. And always maintain manual override capability; automation should accelerate ops, not replace judgment.

If you're designing GPU infrastructure for AI workloads and need help architecting autoscaling that actually survives production traffic, reach out to discuss your specific deployment. Getting this right saves thousands monthly while keeping your users happy.

Frequently Asked Questions

GPU-bound workloads often show low CPU utilization while request queues grow. Scaling on CPU causes lag spikes because new pods launch only after compute saturation, missing pending token generation requests entirely during traffic bursts.

Enable the Prometheus endpoint in vLLM using the --enable-metrics flag. KEDA then scrapes the vllm_num_requests_waiting gauge directly from the pod service to trigger scaling events based on actual pending tokens.

Use the Prometheus scaler targeting vllm_num_requests_waiting or tgi_queue_size. Configure the query to average queue depth across replicas, preventing oscillation when individual pods temporarily hold higher request counts during batch processing.

Yes. Set minReplicaCount to zero in KEDA. Cold starts take thirty to ninety seconds depending on model size and storage class, so use provisioned concurrency or keep one replica warm for latency-sensitive production endpoints.

Yes. Queue-based scaling matches replica count to actual demand rather than arbitrary resource thresholds. Teams typically see twenty to forty percent savings by eliminating idle GPUs that HPA keeps running due to misleading CPU metrics.

Configure KEDA stabilizationWindowSeconds to sixty or higher. Add readiness probes checking the /health endpoint before routing traffic. This ensures new pods finish loading weights and initializing KV caches before receiving queued requests.

Queue metrics become unreliable without per-model isolation. Deploy separate deployments with dedicated GPU resources or use MIG partitioning. Each model needs independent KEDA triggers referencing its specific queue depth metric namespace.

Continuous batching reduces effective queue depth since multiple requests process simultaneously. Set thresholds relative to max_num_seqs in your serving config. A threshold of ten may be appropriate for batch size thirty-two but too aggressive for batch size four.

Yes. Use KEDA composite scalers requiring both queue depth above threshold AND GPU memory under ninety percent. This prevents scaling into OOM conditions where new pods crash immediately, wasting resources and increasing tail latency.

Use locust or vegeta to generate synthetic token streams against a staging cluster. Monitor KEDA events via kubectl get scaledobjects and compare scale-up timing against actual queue accumulation to validate threshold configurations before going live.

Forgetting to remove existing HPA objects causes conflicting scale decisions. Also verify RBAC permissions for KEDA to read custom metrics. Test failover behavior when Prometheus becomes unavailable to ensure graceful degradation.

Never expose metrics publicly. Use Kubernetes NetworkPolicies restricting access to KEDA operator namespace only. Enable mTLS between scraper and target pods via service mesh or cert-manager to prevent metric spoofing attacks.

No. TensorRT-LLM exposes different metric names like triton_queue_depth. Update your KEDA Prometheus query accordingly. Always verify available metrics via curl against the /metrics endpoint before configuring autoscaler triggers.

Set scale-down cooldown to three hundred seconds minimum. LLM cold starts are expensive, and premature scale-down causes repeated initialization overhead. Scale-up cooldown can be shorter at sixty seconds to handle burst absorption quickly.

Yes. EKS, GKE, and AKS all support KEDA with Prometheus adapters. Ensure node autoscaler integrates with pod autoscaler to provision GPU nodes before pods schedule, avoiding pending states that delay scale-up response times significantly.