Kubernetes Tutorial · Operating Kubernetes · Lesson 23 of 26

Horizontal Pod Autoscaling

Scale replicas with load using the HorizontalPodAutoscaler, and what it needs to work.

Create a free account to save this page, take notes and track your progress. Sign in

How the HPA decides

The HorizontalPodAutoscaler periodically compares a metric with a target and sets replicas:

desired = ceil(current replicas × current metric / target)

For CPU, the metric is usage as a percentage of the request, so pods need CPU requests. It needs a metrics source (metrics-server for CPU and memory; Prometheus adapters or KEDA for custom and event-driven metrics). behavior settings slow down scale-down to avoid flapping.

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata: {name: api}
spec:
  scaleTargetRef: {apiVersion: apps/v1, kind: Deployment, name: api}
  minReplicas: 2
  maxReplicas: 10
  metrics:
    - type: Resource
      resource: {name: cpu, target: {type: Utilization, averageUtilization: 70}}
Create an HPA and apply its formula
kubectl create namespace demo-hpa > /dev/null
trap 'kubectl delete namespace demo-hpa --wait=false > /dev/null' EXIT
kubectl -n demo-hpa create deployment api --image=busybox:1.37 -- sleep 3600 > /dev/null
kubectl -n demo-hpa set resources deployment api --requests=cpu=100m > /dev/null
kubectl -n demo-hpa autoscale deployment api --min=2 --max=10 --cpu-percent=70 > /dev/null
kubectl -n demo-hpa get hpa api -o custom-columns=MIN:.spec.minReplicas,MAX:.spec.maxReplicas,TARGET:.spec.metrics[0].resource.target.averageUtilization
python3 -c '
import math
for replicas, usage in [(2, 140), (4, 35), (3, 70)]:
    print(f"{replicas} pods at {usage}% of request -> desired {math.ceil(replicas * usage / 70)}")'

Output

MIN   MAX   TARGET
2     10    70
2 pods at 140% of request -> desired 4
4 pods at 35% of request -> desired 2
3 pods at 70% of request -> desired 3

Run this on your computer — see “Get Started” for setup.

Test yourself

Why must pods have CPU requests for a CPU-based HPA?

  1. Requests make pods faster
  2. Utilization is measured as a percentage of the request
  3. The HPA reads limits only
  4. It doesn't matter
Show answer

Answer: Utilization is measured as a percentage of the request

Without requests there's nothing to compute a percentage from.

Was this page helpful?