Autoscaling
Traffic changes during the day; a good cluster changes with it. Kubernetes has three autoscalers that work at different levels:
| Autoscaler | Changes | Based on |
|---|---|---|
| HorizontalPodAutoscaler (HPA) | The number of Pod replicas | CPU/memory utilisation, custom or external metrics |
| VerticalPodAutoscaler (VPA) | Pods' CPU/memory requests | Observed historical usage |
| Cluster Autoscaler / Karpenter | The number of nodes | Pending Pods that don't fit / under-used nodes |
They complement each other: the HPA adds Pods, the new Pods don't fit, the cluster autoscaler adds a node.
HorizontalPodAutoscaler
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: api
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: api
minReplicas: 2
maxReplicas: 20
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 60 # % of the CPU *request*
behavior:
scaleDown:
stabilizationWindowSeconds: 300kubectl autoscale deployment api --cpu-percent=60 --min=2 --max=20 # imperative equivalent
kubectl get hpa api -wSample output:
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
api Deployment/api cpu: 90%/60% 2 20 4 6m
api Deployment/api cpu: 58%/60% 2 20 6 7mThe HPA needs metrics-server (or another metrics API) and Pods with CPU requests, because utilisation is measured as a percentage of the request.
The formula
Every 15 seconds the HPA controller computes:
desiredReplicas = ceil( currentReplicas × currentMetricValue / targetValue )then skips the change if the ratio is within a 10 % tolerance of 1.0, and clamps the result to [minReplicas, maxReplicas].
import math
def desired_replicas(current, metric, target, min_r, max_r, tolerance=0.1):
ratio = metric / target
if abs(ratio - 1.0) <= tolerance:
return current, f"ratio {ratio:.2f} within tolerance"
raw = math.ceil(current * ratio)
clamped = max(min_r, min(max_r, raw))
note = f"ceil({current} x {metric}/{target}) = {raw}"
if clamped != raw:
note += f", clamped to {clamped}"
return clamped, note
for current, cpu in [(4, 90), (6, 58), (6, 20), (10, 300), (3, 65)]:
new, why = desired_replicas(current, cpu, 60, 2, 20)
print(f"{current:2} replicas at {cpu:3}% -> {new:2} ({why})") 4 replicas at 90% -> 6 (ceil(4 x 90/60) = 6)
6 replicas at 58% -> 6 (ratio 0.97 within tolerance)
6 replicas at 20% -> 2 (ceil(6 x 20/60) = 2)
10 replicas at 300% -> 20 (ceil(10 x 300/60) = 50, clamped to 20)
3 replicas at 65% -> 3 (ratio 1.08 within tolerance)
With several metrics, the HPA computes a proposal for each and takes the largest.
Stabilisation and scale-down
Scaling down too eagerly causes "flapping" (up, down, up). The default scaleDown.stabilizationWindowSeconds: 300 makes the HPA use the highest recommendation from the last five minutes when scaling down, so a short dip doesn't remove Pods. Scale-up has no window by default.
recommendations = [8, 8, 5, 4, 4, 6, 3, 3, 3, 3, 3, 3] # one per minute
window = 5 # minutes
current = 8
for minute, rec in enumerate(recommendations):
recent = recommendations[max(0, minute - window + 1): minute + 1]
target = rec if rec > current else max(recent) # scale up at once, scale down to max of window
print(f"minute {minute:2}: recommendation {rec}, window max {max(recent)} -> replicas {target}")
current = targetminute 0: recommendation 8, window max 8 -> replicas 8
minute 1: recommendation 8, window max 8 -> replicas 8
minute 2: recommendation 5, window max 8 -> replicas 8
minute 3: recommendation 4, window max 8 -> replicas 8
minute 4: recommendation 4, window max 8 -> replicas 8
minute 5: recommendation 6, window max 8 -> replicas 8
minute 6: recommendation 3, window max 6 -> replicas 6
minute 7: recommendation 3, window max 6 -> replicas 6
minute 8: recommendation 3, window max 6 -> replicas 6
minute 9: recommendation 3, window max 6 -> replicas 6
minute 10: recommendation 3, window max 3 -> replicas 3
minute 11: recommendation 3, window max 3 -> replicas 3
Replicas only dropped from 8 once all of the last five recommendations were lower, and then step by step.
VerticalPodAutoscaler
The VPA (an add-on, not built in) watches usage over days and recommends or applies better requests. In Auto/Recreate mode it evicts Pods to resize them (newer versions can resize in place). Don't let VPA and HPA both act on the same CPU/memory metric for the same workload: they fight.
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
name: api
spec:
targetRef: {apiVersion: apps/v1, kind: Deployment, name: api}
updatePolicy:
updateMode: "Off" # recommendations only; read them with kubectl describe vpaCluster autoscaler and Karpenter
The Cluster Autoscaler watches for Pods that are Pending because no node has room, and grows a node group; it shrinks groups whose nodes have been under-used for a while (if their Pods can move elsewhere). Karpenter (AWS, Azure) picks instance types per batch of pending Pods instead of fixed groups.
import math
node_capacity = {"cpu": 4000, "memory": 16384} # one node type: 4 vCPU, 16 GiB
pending = [("api", 500, 1024)] * 6 + [("worker", 2000, 4096)] * 2
need_cpu = sum(p[1] for p in pending)
need_mem = sum(p[2] for p in pending)
nodes = max(math.ceil(need_cpu / node_capacity["cpu"]), math.ceil(need_mem / node_capacity["memory"]))
print(f"pending Pods: {len(pending)}, need {need_cpu}m CPU and {need_mem}Mi memory")
print(f"scale node group up by {nodes} node(s)")pending Pods: 8, need 7000m CPU and 14336Mi memory
scale node group up by 2 node(s)
(A real autoscaler simulates the scheduler and bin-packs Pods one by one, but the estimate is the same idea.)
Tip: Autoscaling only works well if requests are realistic and the app starts quickly. Combine it with readiness probes and PodDisruptionBudgets so scale-downs don't drop traffic.
Test yourself
4 replicas run at 90% CPU with a 60% target. How many replicas does the HPA want?
- 4
- 5
- 6
- 9
Why does an HPA need CPU requests on the Pods?
- To pull images
- Utilisation is measured as a percentage of the request
- To choose a node
- It doesn't
Which autoscaler adds nodes when Pods are Pending for lack of capacity?
- HPA
- VPA
- Cluster Autoscaler
- kube-scheduler