Overview and What You Will Learn
The Horizontal Pod Autoscaler (HPA) is a Kubernetes controller that automatically changes the number of replicas of a Deployment or StatefulSet to keep a metric, such as average CPU utilization, near a target you set. It checks the metric every 15 seconds by default, scales out when load rises, and scales in when it falls. It needs a metrics source, usually the Metrics Server, and containers that declare resource requests.
Manual scaling is reactive: by the time someone sees CPU at 90 percent, users are already seeing timeouts. HPA closes that gap without keeping peak capacity running all day.
By the end of this guide you will be able to:
- Install and verify the Metrics Server that HPA depends on
- Create an HPA with
kubectl autoscaleand with anautoscaling/v2manifest - Scale on CPU, memory, and custom per-pod metrics
- Tune scale-up and scale-down behavior to prevent thrashing
- Understand how HPA, PodDisruptionBudgets, and node autoscaling fit together
- Diagnose an HPA stuck at
<unknown>or refusing to scale
Why This Matters in Production
Traffic is rarely flat. A food delivery platform like Swiggy sees evening peaks several times higher than its overnight baseline, and a streaming service like Hotstar sees sharp surges during live matches. Provisioning for the peak around the clock wastes money, and provisioning for the average causes outages at the peak.
HPA turns that trade-off into a policy: define the target load per pod, set a minimum and maximum, and let the cluster follow demand. It works best as the first layer, with a node autoscaler such as Cluster Autoscaler or Karpenter adding machines when new pods cannot be scheduled.
Core Principles
The HPA controller runs a loop. It reads current metric values, compares them to the target, calculates the replica count it needs, and updates the workload's scale setting. The workload controller then creates or removes pods, which changes the metric on the next pass.
The Scaling Formula
HPA multiplies the current replica count by the ratio of the observed metric to the target, then rounds up.
desiredReplicas = ceil( currentReplicas x currentMetricValue / targetMetricValue ) Example: 4 pods, average CPU 90%, target 50% ceil( 4 x 90 / 50 ) = ceil(7.2) = 8 podsIf the ratio is within about 10 percent of 1.0, HPA does nothing, which avoids constant small adjustments. The result is always clamped between minReplicas and maxReplicas.
RememberCPU and memory utilization are percentages of the container's resource request, not of the node or the limit. A pod without a CPU request has no utilization, so HPA cannot scale on it.
Metric Types
The autoscaling/v2 API supports several metric sources:
- Resource: CPU or memory averaged across pods, served by the Metrics Server.
- ContainerResource: CPU or memory of one named container, useful when sidecars would skew the average.
- Pods: a custom per-pod metric, such as requests per second, through a custom metrics adapter.
- Object: a metric of another Kubernetes object, such as requests per second on an Ingress.
- External: a metric from outside the cluster, such as queue depth in a managed service.
With several metrics, HPA computes a replica count for each and uses the highest.
TipPrefer a metric that tracks load directly, such as requests per second or queue depth, over CPU when the service is I/O bound. CPU can stay low while latency climbs.
Scaling Behavior and Stabilization
The behavior field controls how fast HPA moves. By default it scales up immediately and scales down only after a 300 second stabilization window, using the highest recommendation from that window. That asymmetry is deliberate, because adding capacity late hurts users and removing it early causes flapping. You can also limit the rate with policies, such as "remove at most 25 percent of pods per minute".
Detailed Step-by-Step Practical Lab
This lab uses the sample php-apache image from the Kubernetes documentation, which burns CPU on each request, so you can see scaling happen. Any cluster works, such as kind, minikube, or a managed cluster.
Step 1 - Install and Verify the Metrics Server
HPA reads CPU and memory from the Metrics Server. Many managed clusters include it, so check first.
kubectl top nodes# Install the Metrics Serverkubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml # Local clusters (kind, minikube) often need relaxed kubelet TLS. Lab use onlykubectl patch deployment metrics-server -n kube-system --type='json' \ -p='[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--kubelet-insecure-tls"}]' kubectl wait --for=condition=available deployment/metrics-server -n kube-system --timeout=120skubectl top pods -ASecurity
--kubelet-insecure-tlsskips certificate verification and is for local labs only. In production, fix the kubelet serving certificates instead.
Step 2 - Deploy a Sample App With Resource Requests
The CPU request is what HPA measures against, so it must be set. Leave replicas out of the manifest, because HPA owns that field once it exists.
# php-apache.yamlapiVersion: v1kind: Namespacemetadata: name: hpa-labapiVersion: apps/v1kind: Deploymentmetadata: name: php-apache namespace: hpa-labspec: selector: matchLabels: app: php-apache template: metadata: labels: app: php-apache spec: containers: - name: php-apache image: registry.k8s.io/hpa-example ports: - containerPort: 80 resources: requests: cpu: 200m memory: 128Mi limits: cpu: 500m memory: 256MiapiVersion: v1kind: Servicemetadata: name: php-apache namespace: hpa-labspec: selector: app: php-apache ports: - port: 80 targetPort: 80kubectl apply -f php-apache.yamlkubectl get pods -n hpa-labStep 3 - Create an HPA the Quick Way
kubectl autoscale creates an HPA from flags. It is fine for experiments, but manifests are better for anything you keep.
kubectl autoscale deployment php-apache -n hpa-lab --cpu-percent=50 --min=2 --max=10kubectl get hpa -n hpa-lab# NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS# php-apache Deployment/php-apache cpu: 1%/50% 2 10 2Delete it before the next step so you can manage it from a manifest:
kubectl delete hpa php-apache -n hpa-labStep 4 - Define the HPA as a Manifest With Tuned Behavior
The autoscaling/v2 manifest makes scaling policy reviewable and version controlled. This one scales up quickly and scales down gently.
# php-apache-hpa.yamlapiVersion: autoscaling/v2kind: HorizontalPodAutoscalermetadata: name: php-apache namespace: hpa-labspec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: php-apache minReplicas: 2 maxReplicas: 10 metrics: - type: Resource resource: name: cpu target: type: Utilization averageUtilization: 50 behavior: scaleUp: stabilizationWindowSeconds: 0 selectPolicy: Max policies: - type: Percent value: 100 # at most double each minute periodSeconds: 60 - type: Pods value: 4 # or add up to 4 pods each minute periodSeconds: 60 scaleDown: stabilizationWindowSeconds: 300 policies: - type: Percent value: 25 # remove at most a quarter of pods per minute periodSeconds: 60kubectl apply -f php-apache-hpa.yamlkubectl describe hpa php-apache -n hpa-labThe describe output ends with conditions that explain every decision. AbleToScale, ScalingActive, and ScalingLimited are the three to read first.
Step 5 - Generate Load and Watch It Scale
Run a load generator in one terminal and watch the HPA in another.
# Terminal 1: send continuous requests to the servicekubectl run load-generator -n hpa-lab --rm -i --tty --image=busybox:1.36 --restart=Never \ -- /bin/sh -c "while sleep 0.01; do wget -q -O- http://php-apache; done"# Terminal 2: watch utilization and replicas changekubectl get hpa php-apache -n hpa-lab --watch# php-apache Deployment/php-apache cpu: 0%/50% 2 10 2# php-apache Deployment/php-apache cpu: 248%/50% 2 10 2# php-apache Deployment/php-apache cpu: 248%/50% 2 10 8# php-apache Deployment/php-apache cpu: 61%/50% 2 10 10Stop the load with Ctrl+C. CPU drops almost immediately, but replicas stay high until the 300 second scale-down window passes, then shrink in 25 percent steps back to 2. That delay is the stabilization window doing its job.
Step 6 - Scale on a Custom Metric
For services where CPU is a poor signal, scale on a per-pod metric such as requests per second. This needs a custom metrics adapter, such as Prometheus Adapter, that exposes the metric through the Kubernetes metrics API. KEDA is a common alternative for event-driven and queue-based scaling.
metrics: - type: Pods pods: metric: name: http_requests_per_second target: type: AverageValue averageValue: "100" # aim for 100 requests per second per pod - type: Resource resource: name: cpu target: type: Utilization averageUtilization: 70 # CPU acts as a safety netVerify the adapter serves the metric before pointing an HPA at it:
kubectl get --raw "/apis/custom.metrics.k8s.io/v1beta1/namespaces/hpa-lab/pods/*/http_requests_per_second"Step 7 - Protect Availability With a PodDisruptionBudget and Good Minimums
A PodDisruptionBudget (PDB) limits voluntary evictions, such as node drains during upgrades or Cluster Autoscaler scale-down. It does not restrict HPA, which simply lowers the replica count. For HPA, protection comes from a sensible minReplicas and the scale-down policy in Step 4.
apiVersion: policy/v1kind: PodDisruptionBudgetmetadata: name: php-apache namespace: hpa-labspec: maxUnavailable: 1 selector: matchLabels: app: php-apacheCommon MistakeSetting
minAvailableequal to the replica count. Node drains then block forever because no pod may be evicted. UsemaxUnavailable: 1, or a percentage, so upgrades can proceed.
Step 8 - Troubleshoot an HPA That Will Not Scale
The most common symptom is <unknown> in the TARGETS column. Work through the cause from the conditions.
kubectl get hpa -n hpa-lab# TARGETS: <unknown>/50% kubectl describe hpa php-apache -n hpa-lab# Warning FailedGetResourceMetric failed to get cpu utilization: missing request for cpu kubectl top pods -n hpa-lab # does the Metrics Server return data?kubectl get apiservice v1beta1.metrics.k8s.io # is it Available=True?Clean up when you are done:
kubectl delete namespace hpa-labProduction Best Practices & Common Pitfalls
- Always set CPU requests. Without them, utilization cannot be computed. Set them from real measurements, since a request that is too high means HPA scales late.
- Keep
minReplicasat 2 or more for critical services. One replica has no redundancy during a node failure or rolling update. - Do not manage
replicasin Git alongside HPA. A fixedreplicasin a manifest synced by Argo CD or Flux fights the HPA. Omit the field, or configure the tool to ignore it. - Avoid scaling on memory for most apps. Many runtimes hold memory after load drops, so memory scale-down rarely happens.
- Do not drive HPA and VPA from the same metric. Vertical Pod Autoscaler changes requests, which changes utilization, and the two loops can oscillate.
- Pair HPA with a node autoscaler. New pods stay
Pendingif no node has room, so use Cluster Autoscaler or Karpenter for node capacity. - Make pods ready fast. HPA counts a pod toward capacity only once it is ready, so slow startups and readiness probes delay relief during a spike.
- Load test the policy. Verify that scale-up speed and the max replica ceiling really cover your peak, and that downstream databases can take the extra connections.
Common MistakeSetting
maxReplicastoo low. At the ceiling, HPA reportsScalingLimitedand load keeps rising with nothing to absorb it. Alert when an HPA sits at its maximum for several minutes.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
kubectl autoscale deployment <name> --cpu-percent=50 --min=2 --max=10 |
Create an HPA from flags |
kubectl get hpa -n <ns> |
Show targets and replica counts |
kubectl get hpa <name> --watch |
Watch scaling live |
kubectl describe hpa <name> |
Show conditions and scaling events |
kubectl top pods -n <ns> |
Check Metrics Server data |
kubectl get apiservice v1beta1.metrics.k8s.io |
Check the metrics API is available |
kubectl get --raw "/apis/custom.metrics.k8s.io/v1beta1" |
List custom metrics |
| Symptom | Likely Cause | Fix |
|---|---|---|
TARGETS shows <unknown> |
Metrics Server missing or no CPU request | Install it and set requests |
missing request for cpu |
Container has no resource request | Add resources.requests.cpu |
| Never scales down | Inside the 300s window, or a memory target | Wait, or lower the window |
| Replicas flip up and down | Window too short or target too tight | Lengthen scale-down stabilization |
| Stuck at max replicas | maxReplicas too low |
Raise it and check capacity |
New pods stay Pending |
No node capacity | Add Cluster Autoscaler or Karpenter |
| Replicas reset after a deploy | replicas set in the manifest |
Remove the field when using HPA |