Kubernetes autoscaling looks simple on paper — you set a target CPU, the cluster adds pods when load rises — but anyone who has operated a production cluster under spiky, unpredictable traffic knows the reality is more nuanced. In my experience running multi-tenant clusters handling e-commerce peaks and asynchronous workers processing millions of events per day, the default CPU-based Horizontal Pod Autoscaler barely scratches the surface. Real autoscaling requires understanding how HPA, Vertical Pod Autoscaler (VPA), and the event-driven KEDA scaler interact, where each one breaks down, and how to wire them together without causing thrashing, OOMKills, or runaway costs. This article covers the architecture and operational patterns I use to make those three systems cooperate reliably.
HPA Control Loops, Cooldowns and Why Your Replicas Flap
At its core, HPA is a control loop inside the kube-controller-manager. Every 15 seconds by default (controlled by --horizontal-pod-autoscaler-sync-period), it queries the metrics API — either the Metrics Server for resource metrics or the custom/external metrics APIs — and calculates a desired replica count using desiredReplicas = ceil[currentReplicas * (currentMetricValue / desiredMetricValue)]. That formula is straightforward, but the edge cases around it cause most production issues I see.
The first problem is metric volatility. CPU reported from cAdvisor can swing 20-30% within a single sync period, especially for bursty languages like Node.js or Java after GC pauses. Without stabilization, HPA will scale up and down rapidly, creating replica flap that confuses readiness probes and downstream services. That is why the behavior field introduced in HPA v2 is essential. I never deploy an HPA to production without explicit scaleUp and scaleDown policies.
Tuning Stabilization Windows and Scaling Policies
In my experience, a scaleDown.stabilizationWindowSeconds of 300 seconds and scaleUp.stabilizationWindowSeconds of 60 seconds is a solid starting point for web-facing services. This means HPA will consider the highest recommendation over the last five minutes before scaling down, preventing premature scale-in after a brief dip. For scaleUp, I also cap the burst with policies — for example, allowing at most 50% growth per minute or 4 pods per minute, whichever is larger, to protect downstream databases from thundering herds.
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: api-hpa
namespace: production
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: api-server
minReplicas: 8
maxReplicas: 120
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 65
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 75
behavior:
scaleUp:
stabilizationWindowSeconds: 60
policies:
- type: Percent
value: 50
periodSeconds: 60
- type: Pods
value: 8
periodSeconds: 60
selectPolicy: Max
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Percent
value: 15
periodSeconds: 60
selectPolicy: Min
This configuration also shows a common mistake: targeting both CPU and memory with HPA. HPA calculates a replica recommendation for each metric and takes the highest. If you set memory at 75%, a memory leak in one pod can drive the average up and force a scale-out that never resolves the leak. I have found that for most stateless APIs, CPU or request latency is the correct scaling signal, while memory is better handled by VPA or manual rightsizing. If you do use memory with HPA, ensure your application actually releases memory under pressure and that you have alerts on pod restarts due to OOMKilled. For exposing consistent metrics to HPA, your Service and metrics endpoint configuration matters — see Kubernetes Networking: Services, Ingress Controllers and Network Policies for how I structure internal service discovery for the metrics pipeline.
Wiring Custom and External Metrics: From Prometheus Adapter to HPA Behavior Policies
CPU alone fails for queue workers, gRPC services, and anything where latency decouples from CPU. For those workloads I route application metrics through Prometheus and the prometheus-adapter to expose them as custom metrics. The alternative is the newer Kubernetes custom metrics API with the Prometheus Adapter or the OpenTelemetry-backed adapter, but the principle is the same: your application exposes a metric like http_requests_per_second or queue_depth and HPA consumes it.
The implementation flow I use is: application exposes /metrics -> Prometheus scrapes -> adapter registers an APIService v1beta1.custom.metrics.k8s.io -> HPA queries it. The critical piece is query tuning. A raw rate(http_requests_total[1m]) is too noisy. I typically aggregate at the Deployment level and use a 2-3 minute rate with a quantile for latency.
Example: Scaling on Requests Per Second and P95 Latency
Suppose your API should maintain ~400 RPS per pod before latency degrades. Instead of scaling on CPU, you can target that RPS value directly. The HPA manifest references the custom metric by name that the adapter exposes. According to the Kubernetes Documentation on horizontal autoscaling, you can also use the ContainerResource metric type to target a specific container in a pod, which is useful if you have a sidecar that skews overall pod CPU.
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: api-rps-hpa
namespace: production
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: api-server
minReplicas: 10
maxReplicas: 150
metrics:
- type: Pods
pods:
metric:
name: http_requests_per_second
target:
type: AverageValue
averageValue: "400"
- type: Pods
pods:
metric:
name: http_request_duration_p95_seconds
target:
type: AverageValue
averageValue: "350m" # 0.35s
behavior:
scaleUp:
stabilizationWindowSeconds: 30
policies:
- type: Percent
value: 100
periodSeconds: 30
I've found that mixing RPS and latency gives better behavior than either alone. RPS handles predictable throughput, while p95 latency catches saturation from slow dependencies or GC. One operational note: make sure the prometheus-adapter has resource requests that can handle the load. I have seen adapters OOM during scale storms because they were left with default 256Mi limits while serving hundreds of HPA queries per minute. Give it at least 1 CPU and 1Gi, and monitor its own latency.
VPA Modes Demystified: Off, Initial, Auto and the Limits of Live Resizing
Vertical Pod Autoscaler solves a different problem: rightsizing requests and limits. HPA adds pods; VPA makes those pods the right size. In practice, VPA consists of three components — Recommender, Updater, and Admission Controller — that observe historical usage via the Metrics Server and Prometheus history (if configured) and recommend new CPU/memory requests.
Most teams misunderstand VPA modes. There are four, and the choice determines whether you get recommendations or disruptive restarts. In my production clusters, I run VPA in Off or Recreate mode for most services and reserve Auto for non-critical batch workers.
Choosing the Right Update Mode
Off means VPA only provides recommendations in the status field — no automatic mutation. This is ideal for integrating with CI or a rightsizing dashboard. I run a weekly job that scrapes VPA recommendations and opens PRs to adjust Helm values, which I test via Helm Chart Development: Templates, Values, Dependencies and Testing pipelines before rolling out. Initial applies recommendations only at pod creation, so rolling updates get the new size but running pods are untouched. Auto and Recreate both evict pods to apply new resources; the difference is Auto will do it automatically whenever the recommender decides, while Recreate requires the pod to be recreated for another reason. No mode today does true in-place resize for CPU/memory without restart, although the in-place resource resize KEP is in beta in Kubernetes 1.32+.
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
name: worker-vpa
namespace: production
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: image-processor
updatePolicy:
updateMode: "Recreate" # or "Off" for recommendation-only
resourcePolicy:
containerPolicies:
- containerName: processor
minAllowed:
cpu: "250m"
memory: "512Mi"
maxAllowed:
cpu: "4"
memory: "8Gi"
controlledResources: ["cpu", "memory"]
controlledValues: RequestsOnly
The controlledValues: RequestsOnly setting is critical. By default VPA can manage both requests and limits, but I almost always constrain it to requests. Managing limits with VPA risks throttling or OOM if the recommender is too aggressive. I also set tight minAllowed and maxAllowed guardrails — without them, a cold start or an idle weekend can cause VPA to recommend 25m CPU, which then creates scheduling and latency issues on Monday morning. Another lesson: never run VPA in Auto alongside HPA on the same resource metric. If both controllers react to CPU, they fight. The next section covers how to isolate them.
KEDA ScaledObjects in Action: Scaling Deployments and Jobs from Queues and Streams
KEDA — Kubernetes Event-Driven Autoscaling — extends the HPA model to sources HPA cannot understand natively: RabbitMQ queue length, Kafka consumer lag, AWS SQS approximate messages, Redis lists, Prometheus alerts, and over 60 other scalers. Architecturally, KEDA is an operator that creates and manages HPAs on your behalf. You define a ScaledObject (for Deployments/StatefulSets) or ScaledJob (for Jobs), KEDA reconciles an HPA, and that HPA drives the replica count. KEDA also adds scale-to-zero, which native HPA cannot do when minReplicas is 1.
For event-driven workers, scale-to-zero is the reason I adopt KEDA. A Deployment with 0 replicas saves significant cost for infrequent jobs like report generation or webhook processing. KEDA handles this by keeping a tiny scaler that activates the Deployment when triggers are above threshold, then hands off to the generated HPA for fine-grained scaling.
ScaledObject with Queue-Based Scaling and Authentication
Consider a worker that consumes from RabbitMQ. Scaling on CPU is meaningless; you care about queue depth and publish rate. A KEDA ScaledObject for this looks like:
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: rabbitmq-worker-scaledobject
namespace: production
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: invoice-worker
pollingInterval: 15 # how often KEDA queries the scaler
cooldownPeriod: 120 # wait before scaling to zero
idleReplicaCount: 0 # scale to zero when no messages
minReplicaCount: 0
maxReplicaCount: 80
advanced:
horizontalPodAutoscalerConfig:
behavior:
scaleDown:
stabilizationWindowSeconds: 180
triggers:
- type: rabbitmq
metadata:
protocol: amqp
queueName: invoices.pending
host: amqp://rabbitmq.production.svc.cluster.local:5672/
queueLength: "25" # 25 messages per replica target
authenticationRef:
name: keda-trigger-auth-rabbitmq
Several operational details matter here. First, queueLength is not a hard limit but a target average — KEDA computes desiredReplicas = queueLength / threshold. If you have 500 messages and threshold 25, you get 20 replicas. In my experience, you need to load-test to find the sustainable per-pod throughput; otherwise KEDA will over-scale and flood your database. Second, use TriggerAuthentication with secrets from Vault or External Secrets Operator rather than embedding credentials. KEDA supports multiple authentication sources and it is worth wiring that correctly from day one. For more on building operators like KEDA itself, I reference Kubernetes Operators: Building Custom Resources and Controllers when onboarding new engineers.
ScaledJobs for One-Shot Tasks
For jobs that should run once per message — like video transcoding — use ScaledJob. KEDA creates a Kubernetes Job per event batch rather than scaling a Deployment. This gives better isolation and lets you use ttlSecondsAfterFinished and job backoff policies for failure handling. The tradeoff is slower scale-up because Job creation has more overhead than pod scheduling, so keep your job startup time under 5 seconds if you expect high throughput.
Coordinating HPA, VPA and KEDA: Where They Conflict and How I Isolate Them
Running all three scalers together without rules is a recipe for oscillation. The most common failure I have debugged is HPA and VPA both reacting to CPU: HPA adds pods, per-pod CPU drops, VPA then recommends lower CPU, pods restart with lower requests, CPU rises again, HPA adds more pods. This loop wastes resources and causes churn.
My isolation strategy is strict: assign each workload dimension to a single scaler. HPA or KEDA owns replica count. VPA owns resource requests, but only in Off or Initial mode when HPA/KEDA is active. Never run VPA Auto on a workload that is also scaled by HPA/KEDA on CPU or memory. If you need live vertical adjustments, do it during maintenance windows or via a progressive rollout, not via the VPA updater loop.
KEDA and HPA coexistence is handled by KEDA itself — KEDA creates an HPA, so you should not create a separate HPA on the same target. Configure all horizontal behavior through the ScaledObject's advanced.horizontalPodAutoscalerConfig. If you need both queue length and CPU, add CPU as a second trigger or metric inside the ScaledObject; KEDA will merge them into one HPA that takes the maximum.
| Dimension | HPA | VPA | KEDA |
|---|---|---|---|
| Scales | Replicas (horizontal) | CPU / Memory requests/limits (vertical) | Replicas via external events (horizontal, with scale-to-zero) |
| Primary Metric Sources | Metrics Server, custom/external metrics APIs | Historical pod resource usage, recommender | 60+ scalers: queues, streams, DBs, cloud providers |
| Scale to Zero | No (minReplicas >=1) | Not applicable | Yes, with idleReplicaCount and cooldownPeriod |
| Pod Restart Required | No, creates new pods | Yes, except in-place resize beta | No for ScaledObject; Job creation for ScaledJob |
| Best Paired With | Stateless web APIs, CPU/RPS-driven services | Recommendation-only for rightsizing, Initial mode for batch | Queue workers, stream consumers, scheduled burst jobs |
| Operational Risk If Misconfigured | Flapping, throttling downstream dependencies | Eviction storms, OOM, under-provisioned restarts | Over-scaling on lag spikes, credential expiry, scaler throttling |
Namespace-level guardrails also help. I always set ResourceQuota and LimitRange so a misconfigured ScaledObject cannot scale to 500 replicas and starve other teams. For critical workloads, I also cap KEDA maxReplicaCount to about 2x expected peak and use alerting on KEDA scaler errors — KEDA exposes Prometheus metrics like keda_scaler_errors_total that you should monitor.
Production Hardening: Observability, Resource Quotas and Autoscaling Failure Modes
Autoscaling without observability is just autoscaling on hope. Before I enable any autoscaler in production, I instrument four signals: desired vs. actual replicas, pending pod time, scaling decision logs, and cost per replica hour. HPA and KEDA both emit Kubernetes Events when they scale, but Events are short-lived. I scrape kube-state-metrics and export HPA spec.desiredReplicas vs. status.currentReplicas to Prometheus and alert when they diverge for more than 10 minutes — that usually indicates insufficient quota, PodDisruptionBudget blocking, or image pull failures.
Metrics and Alerts I Require
For VPA, I track recommendation vs. actual request. A VPA recommendation that is 3x the current request is a signal the service is growing and needs a rollout, not an immediate eviction. I also watch for FailedEvictPod and FailedReschedule events when VPA Updater tries to recreate pods under tight PodDisruptionBudgets. In one incident, VPA in Auto mode evicted 40% of pods simultaneously because the PDB maxUnavailable was set too permissively — we switched that workload to Off the same day.
For KEDA, the scaler's own health is critical. If RabbitMQ or Kafka is unreachable, KEDA will fail to query and will not scale, potentially leaving queue lag to grow unbounded. I set alerts on keda_scaler_error and on the fallback behavior: configure fallback in ScaledObject to keep a minimum replica count when scaler queries fail, so at least some capacity remains.
Cost and Safety Controls
Every autoscaler needs a budget. Beyond ResourceQuota, I use cluster-autoscaler with overprovisioned pause pods cautiously — a fast HPA scale-up is useless if pending pods wait 4 minutes for a new node. I keep a small buffer of spare capacity (about 15%) on dedicated node pools for critical scalable workloads and use Karpenter consolidation policies to remove waste when load drops. Detailed in the Kubernetes Documentation on resource management, requests directly affect bin packing and cluster-autoscaler decisions, so rightsizing via VPA recommendations has a direct cost impact even when not auto-applied.
Finally, test failure modes. I run chaos experiments where I throttle the metrics API, blackhole the KEDA scaler endpoint, and artificially inflate queue depth to watch behavior. In my experience, the autoscalers themselves are robust — the failures come from surrounding constraints: insufficient IP addresses in the VPC CNI, quota exhaustion, or readiness probes that never pass under load, leaving new pods unready and HPA continuing to scale. Document your scaling limits, run load tests with your autoscaling configuration enabled, and review those thresholds every quarter as traffic patterns shift.
Frequently Asked Questions
Can I run HPA and VPA on the same workload without conflict?
Yes, but only if you separate their responsibilities. Do not let both react to CPU or memory. The safe pattern is to run VPA in Off or Initial mode to provide recommendations while HPA or KEDA controls replicas based on CPU, RPS, or queue metrics. Auto mode for VPA on the same resource that HPA targets will cause oscillation and eviction churn. If you need vertical resizing, apply VPA recommendations during controlled rollouts rather than letting the updater evict pods automatically.
When should I choose KEDA over native HPA with external metrics?
Choose KEDA when you need scale-to-zero, have many event sources, or want a cleaner abstraction for queue and stream scaling. Native HPA with external metrics can scale on Prometheus queries, but KEDA provides 60+ built-in scalers, polling optimizations, authentication handling, and fallback configuration without writing custom adapters. In my experience, KEDA is the better default for any worker that consumes from SQS, RabbitMQ, Kafka, or Redis, while native HPA is sufficient for request-driven web services scaled on CPU, RPS, or latency.
How do I prevent HPA from flapping during brief traffic spikes?
Use the behavior field to set stabilization windows and scaling policies. A scaleDown stabilization window of 180-300 seconds prevents rapid scale-in after a dip, and scaleUp policies that cap percent or pod growth per minute prevent overreaction to spikes. Also smooth your metric at the source — use a 2-3 minute rate for RPS and avoid 1-minute windows that amplify noise. Test your policy under synthetic load to confirm the replica curve is stable before promoting to production.
Does VPA support live vertical scaling without pod restarts?
As of Kubernetes 1.32, in-place resource resizing is in beta and allows CPU and memory requests to be updated without restarting the container, but it requires feature gates and runtime support and is not yet recommended for broad production use. In stable versions, any VPA update that changes requests requires pod eviction and recreation. Plan for PDB compliance and rolling disruption, or run VPA in Off mode and apply rightsizing through your normal deployment pipeline.