Skip to main content

Scaling Kubernetes Deployments with HPA

Configure the Kubernetes Horizontal Pod Autoscaler to scale pods on CPU, memory, and custom metrics, with tuned behavior to avoid thrashing.

52 Terms

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 autoscale and with an autoscaling/v2 manifest
  • 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.

flowchart TD A["Metrics Server or adapter"]:::green B{{"HPA controller, every 15s"}}:::blue C["Deployment scale"]:::orange D["Pods"]:::slate A -->|"current usage"| B B -->|"desired replicas"| C C --> D D -->|"new usage"| A classDef green fill:#10B981,color:#ffffff classDef blue fill:#326CE5,color:#ffffff classDef orange fill:#F97316,color:#ffffff classDef slate fill:#475569,color:#ffffff
The Scaling Formula

HPA multiplies the current replica count by the ratio of the observed metric to the target, then rounds up.

TEXT
desiredReplicas = ceil( currentReplicas x currentMetricValue / targetMetricValue )
Example: 4 pods, average CPU 90%, target 50%
ceil( 4 x 90 / 50 ) = ceil(7.2) = 8 pods

If 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.

Remember

CPU 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:

  1. Resource: CPU or memory averaged across pods, served by the Metrics Server.
  2. ContainerResource: CPU or memory of one named container, useful when sidecars would skew the average.
  3. Pods: a custom per-pod metric, such as requests per second, through a custom metrics adapter.
  4. Object: a metric of another Kubernetes object, such as requests per second on an Ingress.
  5. 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.

Tip

Prefer 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.

Bash
kubectl top nodes
Bash
# Install the Metrics Server
kubectl 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 only
kubectl 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=120s
kubectl top pods -A
Security

--kubelet-insecure-tls skips 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.

YAML
# php-apache.yaml
apiVersion: v1
kind: Namespace
metadata:
name: hpa-lab
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: php-apache
namespace: hpa-lab
spec:
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: 256Mi
---
apiVersion: v1
kind: Service
metadata:
name: php-apache
namespace: hpa-lab
spec:
selector:
app: php-apache
ports:
- port: 80
targetPort: 80
Bash
kubectl apply -f php-apache.yaml
kubectl get pods -n hpa-lab
Step 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.

Bash
kubectl autoscale deployment php-apache -n hpa-lab --cpu-percent=50 --min=2 --max=10
kubectl get hpa -n hpa-lab
# NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS
# php-apache Deployment/php-apache cpu: 1%/50% 2 10 2

Delete it before the next step so you can manage it from a manifest:

Bash
kubectl delete hpa php-apache -n hpa-lab
Step 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.

YAML
# php-apache-hpa.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: php-apache
namespace: hpa-lab
spec:
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: 60
Bash
kubectl apply -f php-apache-hpa.yaml
kubectl describe hpa php-apache -n hpa-lab

The 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.

Bash
# Terminal 1: send continuous requests to the service
kubectl 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"
Bash
# Terminal 2: watch utilization and replicas change
kubectl 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 10

Stop 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.

YAML
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 net

Verify the adapter serves the metric before pointing an HPA at it:

Bash
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.

YAML
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: php-apache
namespace: hpa-lab
spec:
maxUnavailable: 1
selector:
matchLabels:
app: php-apache
Common Mistake

Setting minAvailable equal to the replica count. Node drains then block forever because no pod may be evicted. Use maxUnavailable: 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.

Bash
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:

Bash
kubectl delete namespace hpa-lab

Production 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 minReplicas at 2 or more for critical services. One replica has no redundancy during a node failure or rolling update.
  • Do not manage replicas in Git alongside HPA. A fixed replicas in 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 Pending if 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 Mistake

Setting maxReplicas too low. At the ceiling, HPA reports ScalingLimited and 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

Resources

Velero vs etcd Snapshot: Which Do You Need?

Velero vs etcd Snapshot: Which Do You Need?

Velero and etcd snapshots protect different layers of a Kubernetes cluster. See what each backs up, what each misses, and why most DR needs both.

11 min read•Aug 2026
Istio Ambient vs Linkerd in 2026: Which Mesh?

Istio Ambient vs Linkerd in 2026: Which Mesh?

Istio Ambient cuts the sidecar tax at L4, but L7 adds waypoint hops, and Linkerd stable builds now come from Buoyant. Choose with tests.

11 min read•Aug 2026
Nginx Ingress vs Traefik vs Gateway API in 2026

Nginx Ingress vs Traefik vs Gateway API in 2026

Ingress-NGINX is retired. Compare Traefik and Gateway API controllers as replacements, plus a safe migration plan that avoids outages.

10 min read•Aug 2026
OPA Gatekeeper vs Kyverno: Policy Engine in 2026

OPA Gatekeeper vs Kyverno: Policy Engine in 2026

OPA Gatekeeper vs Kyverno compared for 2026: Rego vs YAML, mutation, reporting, and operations, plus how to pick a Kubernetes policy engine.

10 min read•Aug 2026
Helm vs Kustomize in 2026: Templating vs Patching

Helm vs Kustomize in 2026: Templating vs Patching

Helm vs Kustomize compared for 2026 - templating vs patching, Helm 4's new features, and why most production teams end up running both.

5 min read•Aug 2026
Prometheus vs Datadog vs New Relic: Real Costs

Prometheus vs Datadog vs New Relic: Real Costs

Prometheus, Datadog, and New Relic compared for 2026 - real pricing at scale, hidden cost drivers, and which fits a Kubernetes-heavy stack.

5 min read•Aug 2026
Cluster Autoscaler vs Karpenter for EKS in 2026

Cluster Autoscaler vs Karpenter for EKS in 2026

Cluster Autoscaler vs Karpenter on EKS: scale-up speed, bin-packing, Spot handling, Auto Mode limits and a safe migration path, with v1 NodePool YAML.

11 min read•Aug 2026
GKE vs EKS vs AKS in 2026: Which Fits Your Team?

GKE vs EKS vs AKS in 2026: Which Fits Your Team?

GKE, EKS, and AKS compared for 2026 - control plane pricing, Autopilot vs Karpenter vs Node Auto Provisioning, and which platform actually fits your team.

5 min read•Aug 2026
K3s vs K8s vs MicroK8s: Which Distro in 2026?

K3s vs K8s vs MicroK8s: Which Distro in 2026?

Compare K3s, upstream Kubernetes and MicroK8s on footprint, datastores, HA and updates, and pick the right fit for edge, dev or production.

10 min read•Aug 2026
Canary Deployments with Argo Rollouts & Flagger

Canary Deployments with Argo Rollouts & Flagger

Ship to 5% of users first and auto-rollback on bad metrics: canary deployments on Kubernetes with Argo Rollouts, Flagger, and Gateway API.

11 min read•Jun 2026
OpenTelemetry Explained: Metrics, Logs, Traces

OpenTelemetry Explained: Metrics, Logs, Traces

OpenTelemetry in practice: instrument a Node.js service, run a production Collector, sample traces and link metrics, logs and traces in Grafana.

11 min read•Jun 2026
Kubernetes Cost Optimization Without SLO Risk

Kubernetes Cost Optimization Without SLO Risk

Kubernetes clusters average about 8% CPU use. Cut waste safely with request rightsizing, autoscaling, spot, and OpenCost, keeping SLOs.

11 min read•Jun 2026
ArgoCD vs FluxCD: GitOps for Kubernetes in 2026

ArgoCD vs FluxCD: GitOps for Kubernetes in 2026

ArgoCD vs FluxCD compared for 2026: UI, multi-tenancy, Helm, image automation and pruning risks, with a clear guide to picking your GitOps engine.

10 min read•Jun 2026

Explore More in Kubernetes Observability and Scaling

All 4 Topics

Frequently Asked Questions

Is Scaling Kubernetes Deployments with HPA free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Scaling Kubernetes Deployments with HPA topic cover?

Configure the Kubernetes Horizontal Pod Autoscaler to scale pods on CPU, memory, and custom metrics, with tuned behavior to avoid thrashing.

Found a mistake, an outdated step or a broken link?