Operating, scaling and debugging · 6 MIN READ
Autoscale pods on CPU with the HorizontalPodAutoscaler, VPA and cluster autoscaler
Create an autoscaling/v2 HorizontalPodAutoscaler on CPU utilization, predict its replica count from the formula, tune how fast it scales up and down, and place the Vertical Pod Autoscaler and the cluster autoscaler next to it.
Load changes faster than anyone can run kubectl scale, and a fixed replica count is either too small at the peak or wasted at night. The HorizontalPodAutoscaler adjusts a Deployment's replica count from observed metrics. It only works when the pods declare CPU requests, metrics are flowing, and its reaction speed matches how fast the service can take on load.
kubernetes · A MAP OF THE IDEA
- Set CPU requests
- Create HPA: target, min, max
- Watch get hpa and its events
- Tune behavior if needed
Useful when
- Replica count follows load without anyone running kubectl scale.
- The formula is simple enough to predict and to review.
Watch out
- Without CPU requests the HPA cannot scale at all.
- Re-applying spec.replicas from CI fights the autoscaler.
Implementation & operation cost: Accurate requests, a running metrics-server, and spare node capacity for the first minutes of a spike.
Where the numbers come from
The kubelet measures CPU and memory per container. metrics-server collects them from every kubelet, every 15 seconds by default, and serves them through the resource metrics API, metrics.k8s.io, which kubectl top and the HPA read. kind does not install metrics-server: on a real kind cluster you apply its release manifest and add --kubelet-insecure-tls, while the GopherForge lab has it enabled. CPU utilization is usage divided by the pod's CPU request: a pod requesting 100m that uses 50m is at 50%, whatever its limit. If a container in the targeted pods has no CPU request, the HPA cannot compute a percentage: TARGETS shows cpu: <unknown>/50% and a FailedGetResourceMetric event says "missing request for cpu in container web". Custom and external metrics, such as queue length, need an adapter like Prometheus Adapter or KEDA.
The formula and the 15-second loop
Every 15 seconds the controller computes desiredReplicas = ceil(currentReplicas x currentUtilization / targetUtilization) and clamps it between minReplicas and maxReplicas. One pod using 240% of its request with a 50% target gives ceil(1 x 240 / 50) = 5. Five pods at 49% give ceil(4.9) = 5, and a ratio within the 10% tolerance changes nothing anyway, which prevents flapping. Pods without metrics are treated conservatively, as fully busy when scaling down and idle when scaling up, and pods that are not ready yet count as idle when scaling up. Scaling takes time, because metrics lag a scrape and new pods must pull, start and pass readiness, so keep headroom with a target of 50 to 70%. Do not set spec.replicas in a manifest that CI re-applies to an autoscaled Deployment: every apply resets the count the HPA chose.
behavior: how fast up, how slowly down
Without a behavior field the HPA scales up at once, adding at most 100% of the current replicas or 4 pods per 15 seconds, whichever is more. It scales down only to the highest recommendation of the last 300 seconds: the scale-down stabilization window, which stops it from removing pods during a short lull. behavior overrides each direction with a stabilizationWindowSeconds and a list of policies that limit change per period; selectPolicy picks the policy allowing the most change (Max, the default), the least (Min), or Disabled to forbid that direction. A service that starts slowly wants fast scale-up and gentle scale-down; a queue consumer may want both fast.
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 60
behavior:
scaleDown:
stabilizationWindowSeconds: 120
policies:
- type: Percent
value: 50
periodSeconds: 60
scaleUp:
policies:
- type: Pods
value: 4
periodSeconds: 15This HPA keeps 2 to 10 replicas at an average of 60% of the CPU request. It scales down only after the recommendation has stayed lower for 120 seconds, and then removes at most half of the pods per minute, rounded so that 5 pods become 3, then 2. Scale-up may add 4 pods every 15 seconds with no stabilization window. kubectl autoscale creates the same object without behavior.
Vertical Pod Autoscaler
The Vertical Pod Autoscaler is a separate project in the kubernetes/autoscaler repository that you install with its own CRD. Its recommender watches usage history and computes requests for each container; its updater evicts pods whose requests are far from the recommendation; its admission webhook writes the recommended requests into pods as they are created. updateMode Off only publishes recommendations, a safe way to size requests for a new service; Initial applies them when pods are created; Recreate evicts pods to apply them; recent releases add InPlaceOrRecreate, which uses in-place pod resize, beta and enabled by default in Kubernetes 1.33 and 1.34. Do not let VPA and an HPA both act on the CPU or memory of the same pods: VPA raises requests, utilization drops, and the HPA removes pods.
Cluster autoscaler
The HPA adds pods; something must add nodes for them. The cluster autoscaler watches for pods that stay Pending because no node has room, simulates the scheduler against each node group (a cloud auto scaling group or node pool), and grows a group whose new node would fit them. It removes a node when its pods' requests stay below half of its capacity for ten minutes and every pod can move elsewhere, respecting PodDisruptionBudgets; the annotation cluster-autoscaler.kubernetes.io/safe-to-evict: "false" on a pod keeps its node. It decides from requests, never from actual usage, so pods without requests make it blind. A new node takes minutes, so an HPA on top of a cluster autoscaler needs spare capacity for the first burst. Karpenter is an alternative that picks instance types per pending pod. The lab's nodes are fixed unless you run cluster node add.
Try it in the lab terminal
Give the Deployment a CPU request, attach an HPA with a 50% target, send 400 requests per second in the background and advance the clock to watch it scale up. Then stop the traffic and advance past the 300-second stabilization window to watch it scale back down. The --cpu=50% flag replaced --cpu-percent=50, which kubectl 1.34 deprecates; both create the same autoscaling/v2 object.
kind create cluster
kubectl create deployment web --image=gopherforge/web:v2
kubectl set resources deploy/web --requests=cpu=100m,memory=64Mi --limits=memory=128Mi
kubectl expose deploy/web --port=80 --target-port=8080
kubectl autoscale deploy/web --cpu=50% --min=1 --max=8
kubectl rollout status deploy/web
kubectl get hpa
traffic start svc/web --rps 400
cluster tick 2m
kubectl get hpa
traffic status
kubectl events --for hpa/web
traffic stop all
cluster tick 6m
kubectl get hpa
kubectl events --for hpa/webBefore the load, get hpa shows cpu: 1%/50% and 1 replica. Two minutes later it shows cpu: 49%/50% and 5 replicas, and the HPA's events hold one SuccessfulRescale: "New size: 5; reason: cpu resource utilization (percentage of request) above target". traffic status counts 6533 responses with status 503 among 48000: the single pod was overloaded until the new pods became ready. Six minutes after traffic stop, get hpa is back at 1 replica and a second event reads "New size: 1; reason: ... below target", about five minutes after the load ended.
TAKE THIS WITH YOU
An HPA scales on usage as a percentage of requests, so every container needs a CPU request. It scales up within seconds and down only after a 300-second window; set behavior when those defaults do not fit the service.
Check your understanding
You add an HPA with a 50% CPU target, and kubectl get hpa keeps showing cpu: <unknown>/50%, although kubectl top pods shows usage. What is missing?
Go to the source
Progress stays in this browser. No account needed.