Keeping a fixed replica count is a losing game: you over-provision for peaks you rarely hit, or you wake up to a crashed service when traffic surges. A kubernetes hpa autoscaling setup hands that job to the cluster itself. The HorizontalPodAutoscaler reads live resource metrics and adds or removes pods to hold a target, like 70 percent CPU utilization. In this guide you will install metrics-server, point HPA at a sample Deployment, generate load to watch it react, and tune scaling behaviour so it does not flap.
Prerequisites
You need a running cluster you can reach with kubectl, and permission to create Deployments and HorizontalPodAutoscalers in one namespace. Any recent Kubernetes version works, because everything below uses the stable autoscaling/v2 API. If the moving parts (controllers, Deployments, Services) are still fuzzy, start with our practical guide to what Kubernetes is and come back; HPA makes little sense until the Deployment it scales does. HPA objects also live inside a single namespace and scale one target in it, so the boundaries covered in our Kubernetes namespaces isolation guide decide how far an autoscaler can reach.
How HPA makes scaling decisions
The HPA controller runs a control loop, checking metrics roughly every 15 seconds. It compares the current value against your target, computes a desired replica count from the ratio, and updates the Deployment. The formula from the Kubernetes documentation is simple:
desiredReplicas = ceil[currentReplicas × (currentMetricValue / desiredMetricValue)]
So if four pods are running at 140 percent of a 70 percent CPU target, the controller asks for ceil(4 × 140/70) = 8 pods. A built-in tolerance means ratios close to 1.0 (within about 10 percent) trigger no change, which prevents endless small adjustments. CPU utilization is the default target, expressed as a percentage of the requested CPU. That detail is the one most setups get wrong: without a CPU request, the controller has no denominator and cannot compute a percentage. Memory works the same way. You can target several metrics at once, and HPA scales to satisfy the highest resulting replica count.
Step 1: metrics-server install
Out of the box, kubectl top returns nothing because no metrics pipeline exists. The metrics-server install fills that gap. It collects resource usage from each node’s kubelet and exposes it through the metrics API that HPA reads. Apply the official components manifest:
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
On clusters with self-signed kubelets, common in local setups, patch the deployment to add --kubelet-insecure-tls. Give it about a minute to start collecting, then verify:
kubectl top nodes
kubectl top pods
kubectl get apiservice v1beta1.metrics.k8s.io
If both top commands return numbers and the API service shows as available, the pipeline works and HPA can read from it. If top still errors, the problem is almost always the kubelet TLS flag above or metrics-server’s own pods not running; check them in the kube-system namespace before touching any HPA object.
Kubernetes HPA autoscaling setup for a Deployment
Create a Deployment that declares CPU requests. HPA cannot work without them:
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
spec:
replicas: 2
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
containers:
- name: web
image: nginx:1.27
resources:
requests:
cpu: "250m"
memory: "128Mi"
limits:
cpu: "500m"
memory: "256Mi"
Then create the HPA:
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
kubectl apply -f web.yaml -f hpa.yaml
kubectl describe hpa web-hpa
The describe output shows current utilization and the replica count. That readout is the fastest way to confirm your kubernetes hpa autoscaling setup is live. The sample web Deployment is a plain nginx container; in production it usually sits behind an ingress controller or a reverse proxy, and our tutorial on building a zero-downtime Nginx reverse proxy covers that layer.
Create it fast with kubectl autoscale
If you dislike YAML, one command creates an equivalent autoscaler:
kubectl autoscale deployment web --cpu-percent=70 --min=2 --max=10
The kubectl autoscale deployment shortcut is convenient, but it only supports CPU targets. For memory, custom metrics, or behaviour tuning, keep the manifest.
Add a memory target alongside CPU
CPU is the common trigger, but plenty of workloads (caches, JVM services, image processing) strain memory first. Add a second metric and HPA will scale for whichever one demands more pods:
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80
Keep memory targets conservative. Unlike CPU, which throttles, memory pressure ends in OOM kills, so a memory target is a safety net rather than the primary scaling signal for most web workloads.
Put it under load and watch it react
Generate traffic with a loop from a temporary pod:
kubectl run -i --tty load-generator --rm --image=busybox --restart=Never -- /bin/sh -c "while true; do wget -q -O- http://web; done"
In another terminal, watch:
kubectl get hpa web-hpa --watch
Within a minute or two you should see utilization climb past 70 and the replica count rise toward the cap. Stop the load generator and the count drifts back down to minReplicas. That closed loop is the whole point: the cluster reacts before you would have had time to page someone. If replicas rise but stay pending, the cluster itself is out of room; HPA adds pods, not nodes, so node capacity (or a cluster autoscaler) is a separate concern.
Tune scaling with an hpa stabilization window
Default HPA can flap: a brief spike scales up, then it scales straight back down. The behaviour field fixes that with stabilization windows:
behavior:
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Percent
value: 50
periodSeconds: 60
scaleUp:
stabilizationWindowSeconds: 0
The hpa stabilization window for scale-down tells the controller to look back over five minutes of recommendations and take the highest, smoothing over brief dips. scaleUp stays aggressive at zero seconds, because slow scale-up during a real surge hurts users. Match these to your workload: batch jobs tolerate slow scale-up, user-facing APIs do not.
HPA vs VPA vs KEDA
HPA changes pod count. The Vertical Pod Autoscaler (VPA) changes pod size, adjusting requests and limits, and it restarts pods to apply them. They solve different problems, and running both on the same metric fights itself, so pick one per workload. KEDA sits in front of HPA: it adds event-driven triggers such as queue length or cron schedules, and it supports scale-to-zero.
| Tool | What it changes | Trigger | Scale to zero |
|---|---|---|---|
| HPA | Replica count | CPU, memory, custom metrics | No (minimum 1 replica) |
| VPA | CPU and memory requests per pod | Observed usage history | No |
| KEDA | Replica count, driven through HPA | Queues, events, schedules, external sources | Yes |
A common pattern is KEDA for event sources plus HPA for CPU, which covers both bursty traffic and idle periods.
Common mistakes
Most broken autoscalers fail for one of four reasons. First, missing resource requests, which leaves utilization undefined and shows up as <unknown> in the HPA status. Second, a target set at 95 percent or higher, which leaves no headroom: by the time new pods start, the old ones are already saturated. Third, limits set barely above requests, so pods throttle long before the target looks dangerous. Fourth, expecting HPA to fix a slow application; it adds copies of the workload, and if each copy is slow because of a database bottleneck, you now have ten pods queueing on the same database. Fix the bottleneck, then autoscale.
FAQ
Does HPA work without metrics-server?
For CPU and memory targets, no. metrics-server is the pipeline those targets read from. Custom and external metrics need a separate adapter, commonly the Prometheus adapter.
Why does kubectl describe hpa show unknown utilization?
Either metrics-server is not running, or your pods lack CPU requests. Fix both and wait one collection cycle.
Can HPA scale a Deployment to zero?
No. minReplicas must be at least 1. If you need scale-to-zero, look at KEDA.
Should I use HPA and VPA together?
Not on the same metric. HPA adjusts count, VPA adjusts size, and combining both on CPU leads to oscillation.
Where this leaves your cluster
A working autoscaler needs three things: a metrics pipeline, honest resource requests, and a target that matches real capacity. Get those right, test with real load instead of guessing, and tune the stabilization windows to your traffic shape. Then delete the runbook step where someone manually bumps replicas. If the cluster underneath is still hand-built, the natural next step is to codify it; our first Terraform module tutorial is a gentle place to start.