Lesson 58 · Section 5: Application Lifecycle Management
Lesson 58: Horizontal Pod Autoscaler: let the load decide how many Pods run
What a HorizontalPodAutoscaler is, where its numbers come from, the one formula behind every scaling decision, why it scales up fast and down slowly, and the kubectl commands and checks that make it quick in the exam. · 20 min read · 5 min video
Official competency this lesson covers
Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.
Why the Horizontal Pod Autoscaler exists
A Deployment runs exactly the number of Pods in spec.replicas. That number is a guess about the future. Guess too
low and the Pods are overloaded at the busiest hour; guess too high and the nodes carry Pods that do nothing all
night. You can correct the guess with kubectl scale, but only if someone is watching the usage at the right
moment.
The HorizontalPodAutoscaler (HPA) does the watching. You tell it which workload to scale, the smallest and
largest replica count you accept, and a target such as "average CPU at 60% of what the Pods requested". From then
on it adjusts replicas for you, up when the Pods are busier than the target and down when they are quieter.
"Horizontal" means more or fewer Pods of the same size. Giving each Pod more CPU or memory is vertical scaling, which the next lessons cover.
What an HPA is made of
An HPA is a namespaced object in the autoscaling/v2 API group. It must live in the same namespace as the workload
it scales.
| Field | Meaning | Default |
|---|---|---|
spec.scaleTargetRef | The workload to scale: apiVersion, kind and name | required |
spec.minReplicas | The HPA never goes below this | 1 |
spec.maxReplicas | The HPA never goes above this | required |
spec.metrics | What to measure and the target for each metric | 80% average CPU utilization |
spec.behavior | How fast it may scale up and down | fast up, slow down (see below) |
The target can be anything that has a scale subresource, which in practice means a Deployment, a StatefulSet or a ReplicaSet. A DaemonSet cannot be autoscaled this way, because it has no replica count: it runs one Pod per node.
The metric types
type | Measures | Typical target |
|---|---|---|
Resource | CPU or memory of the Pods, from metrics-server | averageUtilization: 60 (percent of the request) or averageValue: 200m |
ContainerResource | CPU or memory of one named container in each Pod | Same as Resource, plus container: app. Useful when a sidecar would distort the average |
Pods | A custom metric per Pod, for example requests per second | averageValue |
Object | A custom metric of another object, for example an Ingress | value or averageValue |
External | A metric from outside the cluster, for example a queue length | value or averageValue |
For the CKA, Resource on CPU is the case to know by heart. Pods, Object and External need an extra metrics
adapter (such as the Prometheus adapter) that the exam clusters normally do not have.
How it works
Parts:
- kubelet (measures containers)
- metrics-server (collects from nodes)
- API server (metrics.k8s.io)
- HPA controller (checks every 15 s)
- Deployment web (replicas: 3 → 5)
- ReplicaSet (adds 2 Pods)
- Pods (5 share the load)
Connections:
- kubelet to metrics-server: usage
- metrics-server to API server: serves
- API server to HPA controller: average CPU
- HPA controller to Deployment web: scales
- Deployment web to ReplicaSet: owns
- ReplicaSet to Pods: creates
The HPA is not a separate program you install. Its controller runs inside kube-controller-manager, next to the Deployment and ReplicaSet controllers. What you may have to install is the source of its numbers:
- The kubelet on each node measures the CPU and memory of every container.
- metrics-server, an add-on that runs as a Deployment in
kube-system, collects those numbers from every kubelet and serves them through the API server as themetrics.k8s.ioAPI.kubectl topreads the same API. - Every 15 seconds the HPA controller asks that API for the usage of the Pods matched by the target's selector.
- It computes the desired replica count and, if it differs, writes it to the target's scale subresource.
- The Deployment controller and the ReplicaSet controller add or remove Pods, the scheduler places them and the kubelet starts them.
Then the loop repeats. More Pods share the same load, the average drops, and the next calculation lands nearer the target.
The formula
Parts:
- Pod (90% of request)
- Pod (80% of request)
- Pod (100% of request)
- Average 90% (target is 60%)
- 5 replicas (ceil(3 × 90 / 60))
- Limits (min 2, max 10)
Connections:
- Pod to Average 90%
- Pod to Average 90%
- Pod to Average 90%
- Average 90% to 5 replicas: × 1.5
- 5 replicas to Limits: kept within
Every decision comes from one line:
desiredReplicas = ceil( currentReplicas × currentMetricValue / desiredMetricValue )
With three Pods at an average of 90% and a target of 60%, that is ceil(3 × 90 / 60) = ceil(4.5) = 5. With six Pods
at an average of 20% and the same target, it is ceil(6 × 20 / 60) = 2. The result is then kept between
minReplicas and maxReplicas.
Three details decide whether your mental arithmetic matches the cluster:
- The result is rounded up. 4.1 Pods means 5.
- Small differences are ignored. If current ÷ target is within 10% of 1 (between 0.9 and 1.1), nothing changes. At a 60% target, an average anywhere from 54% to 66% leaves the replica count alone.
- With several metrics, the largest answer wins. The HPA calculates a replica count for each metric and takes the highest, so the busiest dimension is always covered.
Fast up, slow down
Parts:
- Load rises (ratio above 1.1)
- Scale up now (×2 or +4 Pods per 15 s)
- Load falls (ratio below 0.9)
- Look back 5 min (keep the highest value)
- Scale down (only when all agree)
Connections:
- Load rises to Scale up now: no waiting
- Load falls to Look back 5 min
- Look back 5 min to Scale down
Load that needs more Pods should get them quickly; load that dips for a moment should not cost you Pods you will need again in a minute. The default behaviour reflects that:
| Direction | Stabilization window | Speed limit per 15 seconds |
|---|---|---|
| Scale up | 0 seconds: acts on the next check | Double the Pods or add 4, whichever is more |
| Scale down | 300 seconds | May remove all surplus Pods in one step |
The stabilization window is the reason an HPA seems slow to shrink. For a scale down, the controller looks at every recommendation it made in the last five minutes and uses the highest. Only when the load has stayed low for the whole window do Pods go away. If a task asks you to prove a scale down, expect to wait about five minutes after the load stops.
You can change both directions under spec.behavior:
spec:
behavior:
scaleDown:
stabilizationWindowSeconds: 60 # shrink after one quiet minute
policies:
- type: Pods
value: 1
periodSeconds: 60 # and remove at most one Pod a minute
scaleUp:
stabilizationWindowSeconds: 0
policies:
- type: Percent
value: 100
periodSeconds: 15
When a direction has several policies, selectPolicy chooses between them: Max (the default) allows the largest
change, Min the smallest, and Disabled switches that direction off altogether.
Under the hood · Pods that are starting, not ready or missing metrics
The average would be wrong if it counted Pods that are not really taking load, so the controller sets some aside:
- Pods that are being deleted and Pods that have failed are ignored.
- A Pod that is not ready yet is left out of a CPU calculation. When the result points to a scale up, such Pods are then counted as using 0%, which makes the scale up smaller. This stops a slow-starting application from causing a runaway scale up.
- A Pod with missing metrics is assumed to use 100% of the target for a scale down and 0% for a scale up. Both assumptions lean towards changing less.
If a metric cannot be read at all, the HPA will still scale up on the metrics that work, but it will not scale down. Missing data never removes Pods.
The intervals come from kube-controller-manager flags: --horizontal-pod-autoscaler-sync-period (15 seconds),
--horizontal-pod-autoscaler-tolerance (0.1) and --horizontal-pod-autoscaler-downscale-stabilization (5 minutes).
On a kubeadm cluster you would change them in /etc/kubernetes/manifests/kube-controller-manager.yaml.
Under the hood · autoscaling/v1 and autoscaling/v2
Both API versions exist and both are stable. autoscaling/v1 supports only CPU, through the single field
targetCPUUtilizationPercentage. autoscaling/v2 has the metrics list and behavior, and it is the one to write.
The API server converts between them, so kubectl get hpa web -o yaml shows the object in v2 even if it was created
as v1. autoscaling/v2beta1 and autoscaling/v2beta2 were removed long ago; a manifest that still uses them is
rejected, and the fix is to change the apiVersion to autoscaling/v2.
Using it
Example · Check that the metrics pipeline works
An HPA on CPU or memory is useless without metrics-server, so check that first:
kubectl -n kube-system get deployment metrics-server
kubectl top nodes
kubectl -n shop top pods
NAME CPU(cores) MEMORY(bytes)
web-6f7c9d5b8c-2xkqp 1m 7Mi
web-6f7c9d5b8c-hv9lw 1m 7Mi
If kubectl top answers Metrics API not available, metrics-server is missing or not ready. On clusters built with
kubeadm it is not installed by default.
Example · Create an HPA with one command
Keep the Deployment web in the namespace shop between 2 and 10 replicas, at 60% average CPU.
kubectl -n shop set resources deployment web --requests=cpu=200m # utilization needs a request
kubectl -n shop autoscale deployment web --min=2 --max=10 --cpu=60%
kubectl -n shop get hpa web
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
web Deployment/web cpu: 1%/60% 2 10 2 45s
TARGETS reads current/target. Right after creation it may show <unknown> for up to a minute while the first
metrics arrive. If it stays that way, something is wrong (see the tricks below).
In kubectl, --cpu=60% is the current spelling and it also accepts an absolute value such as --cpu=500m; there is
a matching --memory flag. Older kubectl versions only know --cpu-percent=60, which still works but is
deprecated. If one is refused, kubectl autoscale --help shows which your version has.
Example · Write the manifest when the task asks for more
Generate the skeleton, then add what the command cannot express, such as a second metric or a behaviour:
kubectl -n shop autoscale deployment web --min=2 --max=10 --cpu=60% \
--dry-run=client -o yaml > web-hpa.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web
namespace: shop
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 60
- type: Resource
resource:
name: memory
target:
type: AverageValue
averageValue: 200Mi
behavior:
scaleDown:
stabilizationWindowSeconds: 120
kubectl apply -f web-hpa.yaml
With two metrics the HPA works out a replica count for each and uses the larger one.
Example · Put load on it and watch it scale
Start a Pod that requests the Service in a loop, and watch the HPA from a second terminal:
kubectl -n shop run load --image=busybox:1.36 --restart=Never -- \
/bin/sh -c "while true; do wget -q -O- http://web >/dev/null; done"
kubectl -n shop get hpa web --watch
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
web Deployment/web cpu: 1%/60% 2 10 2 3m
web Deployment/web cpu: 135%/60% 2 10 2 4m
web Deployment/web cpu: 135%/60% 2 10 5 4m
web Deployment/web cpu: 58%/60% 2 10 5 5m
ceil(2 × 135 / 60) = 5, and with five Pods the average settles just under the target. Now stop the load:
kubectl -n shop delete pod load
TARGETS drops within a minute, but REPLICAS stays at 5 for about five minutes, the scale-down stabilization
window, and only then returns to 2. kubectl describe hpa web records each step:
Events:
Type Reason Age From Message
Normal SuccessfulRescale 7m horizontal-pod-autoscaler New size: 5; reason: cpu resource utilization (percentage of request) above target
Normal SuccessfulRescale 1m horizontal-pod-autoscaler New size: 2; reason: All metrics below target
Tricks
Common mistakes
- No CPU request on the containers. The most common cause of
<unknown>. Addresources.requests.cputo every container in the Pod template, sidecars included, or use aContainerResourcemetric for the one container that matters. - No metrics-server. The HPA is created without complaint and then never acts.
kubectl top podsfailing is the giveaway. - Reading utilization as a share of the limit or of the node. It is always usage divided by the request. A small request makes the percentage large and the HPA eager.
- Expecting an instant scale down. Five minutes of patience is the default. A test that stops the load and checks ten seconds later proves nothing.
- Leaving
spec.replicasin a Deployment manifest you keep applying. Eachkubectl applyresets the replica count to the value in the file and the HPA has to scale back up. Remove the field from the manifest once an HPA owns it. - A
scaleTargetRefthat does not match. A wrongkind, a typo in the name or an HPA in another namespace givesAbleToScale=False. The HPA and its target must be in the same namespace. - Two HPAs on one workload, or an HPA and a VerticalPodAutoscaler both acting on CPU. They work against each other and the replica count swings.
maxReplicaslarger than the cluster can hold. The HPA happily asks for more Pods; if no node has room they stayPending. The HPA adds Pods, not nodes.
Recap
- A HorizontalPodAutoscaler keeps a metric near a target by changing the replica count of a Deployment,
StatefulSet or ReplicaSet, between
minReplicasandmaxReplicas. - Its controller is part of kube-controller-manager and checks every 15 seconds. CPU and memory numbers come from metrics-server, and utilization is measured against the Pods' requests.
desiredReplicas = ceil(currentReplicas × current / target); differences under 10% are ignored, and with several metrics the largest result wins.- It scales up at the next check and down only after a five-minute stabilization window;
spec.behaviorchanges both. - In the exam:
kubectl autoscale deployment <name> --min --max --cpu, thenkubectl get hpaandkubectl describe hpa.<unknown>means no metrics-server or no CPU request.
Official docs
Quiz: check what you learned
5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.
Sign in to take the quiz and keep your score.
Practise: try it on a real cluster
A hands-on lab for this lesson. You get goals, not steps: any solution that reaches them passes.
Create a HorizontalPodAutoscaler for a Deployment, and give it what it needs to read a CPU percentage at all.
Build · Level 2 · standard · target 15 min
Discussion
Learners ask and answer questions here. Sign in to read and join the discussion.