A traffic spike does not meet one autoscaler. It meets a chain of them. Metrics have to be collected, the Horizontal Pod Autoscaler has to do its arithmetic, the scheduler has to find room, a node autoscaler has to buy a machine when there is none, the image has to arrive, and the readiness probe has to pass before a single extra request is served. This lesson follows one spike through that chain, shows where the seconds go and why the slowest link is almost never the HPA, and covers the four tools you choose between: HPA for more copies, VPA for bigger requests, KEDA for scaling on events and to zero, and Cluster Autoscaler or Karpenter for more nodes.
Difficulty: Advanced · Know this first: Lesson 86, Lesson 94, Lesson 95
This bar splits the time from the start of the spike to new capacity serving traffic, in seconds. It is a worked example, not a measurement. The HPA itself is one second of it; waiting for the metric, for a node, and for the pods to start is the rest.
Set the current replicas, the CPU utilization they are running at, and the target. The HPA computes the desired count. If the extra pods do not fit in the spare room on your nodes, a node has to be added first.
desired = ceil(current × utilization ÷ target), unchanged when the ratio is within 10 percent · a node is needed when desired − current > spare slots
Scale up to 8; the pods fit on existing nodes
Three questions. No score is saved anywhere — this is just you against the material.
Autoscaling grows in four levels: first what each autoscaler changes, then configuring the HPA and its behavior, then the right signals and the interplay with VPA, KEDA and node autoscaling, and finally designing for spikes and cost together.
At the basic level you can say what each autoscaler changes. The Horizontal Pod Autoscaler changes how many pods a Deployment runs. The Vertical Pod Autoscaler changes how much CPU and memory each pod requests. KEDA scales on events, the length of a queue, the lag of a Kafka consumer group, and can scale all the way to zero. Cluster Autoscaler and Karpenter change how many nodes there are.
Plain words: more copies (HPA), bigger copies (VPA), copies driven by work waiting (KEDA), more machines to put copies on (node autoscalers).
Terms: replicas, CPU request, utilization (usage as a percent of the request), target, Pending pod, node group.
Where it breaks: expecting the HPA to add machines. It only asks for pods; if they do not fit, they wait until a node autoscaler adds a node.
Try it: Basic
A queue worker should run zero pods when the queue is empty and up to 30 when it is long. Which tool fits?
Now do it: For one service you run, write down which of the four autoscalers it uses today, and which signal each one reads.
At the intermediate level you write an autoscaling/v2 HPA: the target, minimum and maximum replicas, and a behavior block that controls how fast it scales each way. You set CPU requests that match real usage, because the target is a percent of them.
minReplicas for the quiet hour plus one failure, not one.maxReplicas from what the database and the budget can carry, not from what the cluster can fit.Troubleshooting: kubectl describe hpa shows the metric it read, the replicas it wanted, and every scaling event with a reason. <unknown> means no metric.
Try it: Intermediate
Your HPA scales from 4 to 12 and back to 4 every few minutes. What do you change first?
Now do it: Run the hpa_sim.py drill in Go deeper and change the window from 5 to 2 samples. Watch how much sooner pods are removed, and decide if the next burst would have needed them.
At the advanced level you choose the signal. CPU is right for CPU-bound services. For a service that waits on a database, CPU stays low while latency explodes, so scale on requests per second per pod, on in-flight requests, or on queue lag, through the custom or external metrics API (Prometheus Adapter or KEDA).
updateMode: "Off" to get request recommendations without restarts, and apply them in the Deployment. Do not let VPA and HPA act on the same CPU or memory metric; they fight.ScaledObject creates and drives an HPA for you, adds scale to zero and an activation threshold, and reads dozens of event sources.Failure scenarios: scaling a service out past the database's connection limit; a VPA that evicts pods during peak; a node autoscaler blocked by a PodDisruptionBudget that never allows a drain.
Try it: Advanced
A service is waiting on a slow database. CPU is 25 percent, p95 latency is 4 seconds, and the HPA on CPU does nothing. What is the better signal?
Now do it: Write the VPA in Go deeper with updateMode Off for one Deployment and compare its recommendation with the current requests after a day.
At the master level you design the whole response: how much headroom to keep, where to keep it, and what it costs. The spike has to be absorbed by headroom for the 60 to 180 seconds the chain takes. That headroom can be spare utilization on the pods (a target of 60 instead of 80), spare room on the nodes, or low-priority overprovisioning pods that real pods preempt instantly.
Trade-off: faster reaction costs money all the time; slower reaction costs users during every spike. Measure the chain, then buy exactly the headroom it needs.
Try it: Master
Traffic can grow 50 percent in one minute, and your chain takes 2 minutes from spike to serving pods. What should the steady-state headroom cover?
Now do it: Measure your own chain once: time from a load-test spike to new pods Ready, with and without a new node. Put both numbers in the service's runbook.
The HPA's arithmetic is short enough to run by hand. This script reproduces it: utilization as a percent of the request, the replica formula with its tolerance, and the scale-down window that makes it step down slowly. Standard library only; python3 hpa_sim.py.
# hpa_sim.py - the HPA's replica math, its tolerance, and the scale-down window
import math
REQUEST_M = 500 # each pod requests 500m CPU
TARGET = 70 # HPA target: 70% of the request
MIN_R, MAX_R = 2, 20
def utilization(usage_m, request_m):
"""CPU utilization as the HPA sees it: usage as a percent of the pod's request."""
if not request_m:
return None # no request: the HPA cannot compute a percent
return round(100 * usage_m / request_m)
def desired(current, util, target=TARGET, tolerance=0.1):
"""desired = ceil(current * util / target), unless the ratio is within the tolerance."""
ratio = util / target
if abs(ratio - 1.0) <= tolerance:
return current, ratio
return min(MAX_R, max(MIN_R, math.ceil(current * ratio))), ratio
print("utilization is relative to the request:")
print(" uses 350m, requests 500m ->", utilization(350, 500), "%")
print(" uses 350m, no request ->", utilization(350, None))
print("one HPA sync, target 70% CPU:")
for current, util in [(4, 74), (4, 140), (10, 35)]:
want, ratio = desired(current, util)
print(f" {current} pods at {util}% -> ratio {ratio:.2f} -> {want} pods")
# The service needs a total amount of CPU (demand, in millicores); the pods share it.
# Scale-down stabilization: before scaling down, the HPA takes the highest
# recommendation of the last window (300 s by default; here 5 one-minute samples).
demand = [1400, 5600, 5600, 5600, 2800, 1400, 1400, 1400, 1400, 1400, 1400]
window, history, replicas = 5, [], 4
print("minute by minute, 5-minute scale-down window:")
for minute, need in enumerate(demand):
util = round(100 * need / (replicas * REQUEST_M))
want, _ = desired(replicas, util)
history = (history + [want])[-window:]
replicas = want if want >= replicas else max(history)
print(f" minute {minute:>2}: demand {need:>4}m, CPU {util:>3}% -> recommends {want:>2}, runs {replicas:>2}")
$ python3 hpa_sim.py utilization is relative to the request: uses 350m, requests 500m -> 70 % uses 350m, no request -> None one HPA sync, target 70% CPU: 4 pods at 74% -> ratio 1.06 -> 4 pods 4 pods at 140% -> ratio 2.00 -> 8 pods 10 pods at 35% -> ratio 0.50 -> 5 pods minute by minute, 5-minute scale-down window: minute 0: demand 1400m, CPU 70% -> recommends 4, runs 4 minute 1: demand 5600m, CPU 280% -> recommends 16, runs 16 minute 2: demand 5600m, CPU 70% -> recommends 16, runs 16 minute 3: demand 5600m, CPU 70% -> recommends 16, runs 16 minute 4: demand 2800m, CPU 35% -> recommends 8, runs 16 minute 5: demand 1400m, CPU 18% -> recommends 5, runs 16 minute 6: demand 1400m, CPU 18% -> recommends 5, runs 16 minute 7: demand 1400m, CPU 18% -> recommends 5, runs 16 minute 8: demand 1400m, CPU 18% -> recommends 5, runs 8 minute 9: demand 1400m, CPU 35% -> recommends 4, runs 5 minute 10: demand 1400m, CPU 56% -> recommends 4, runs 5
Read it like this: a missing request gives no utilization at all; 74 percent against 70 is inside the tolerance and changes nothing; the spike at minute 1 takes four pods to sixteen at once; and when the demand falls, the pods stay at sixteen for the length of the window, then step down. The real HPA also caps scale-up at the larger of 100 percent or 4 pods per 15 seconds, which sixteen from four fits within a minute.
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: checkout
namespace: shop
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: checkout
minReplicas: 4
maxReplicas: 30
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
behavior:
scaleUp:
stabilizationWindowSeconds: 0
policies:
- type: Percent
value: 100
periodSeconds: 15
- type: Pods
value: 4
periodSeconds: 15
selectPolicy: Max
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Pods
value: 2
periodSeconds: 60
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
name: checkout
namespace: shop
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: checkout
updatePolicy:
updateMode: "Off"
With updateMode: "Off" the VPA never evicts a pod; kubectl describe vpa checkout shows its target and upper bound for each container. Copy them into the Deployment by hand, during a normal deploy.
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: order-worker
namespace: shop
spec:
scaleTargetRef:
name: order-worker
minReplicaCount: 0
maxReplicaCount: 30
triggers:
- type: kafka
metadata:
bootstrapServers: kafka.shop.svc:9092
consumerGroup: order-worker
topic: orders
lagThreshold: "100"
activationLagThreshold: "1"
KEDA creates an HPA for this workload and feeds it the lag as an external metric: about one replica per 100 messages of lag, never more replicas than the topic has partitions to share, and zero replicas when there is no lag at all. The three manifests above were parsed as YAML and checked against the field names of autoscaling/v2, the VPA v1 API, and KEDA v2; apply them to a test cluster that has metrics-server, the VPA, and KEDA installed before you rely on them.
kubectl get hpa -n shop kubectl describe hpa checkout -n shop kubectl get --raw "/apis/metrics.k8s.io/v1beta1/namespaces/shop/pods" | head -c 400 kubectl get events -n shop --field-selector reason=FailedScheduling kubectl get nodes -L karpenter.sh/nodepool,node.kubernetes.io/instance-type
This is a composite of a failure pattern that keeps repeating; the numbers are illustrative. A payments API scaled on CPU. A marketing push doubled traffic, but the service spent its time waiting on the database, so CPU sat at 30 percent and the HPA did nothing while latency climbed.
The HPA moved from CPU to in-flight requests per pod, the signal that actually tracked the trouble, and maxReplicas was set from the database's connection budget: pods × pool size must stay under the limit with room to spare. Scaling out is only a fix when the bottleneck is inside the pods.
Design autoscaling for a checkout service that sees a 3x spike within two minutes every time a campaign email goes out, and a queue worker that processes orders from Kafka.
Is the checkout service CPU-bound, or does it wait on the database? How long does your chain take, with and without a new node? What is the database's connection limit? Are the campaigns scheduled? How many partitions does the orders topic have?
Say 6 checkout pods at 60 percent at the quiet peak, 400 database connections with 20 per pod, a 2-minute node launch, and 24 partitions on the orders topic.
Checkout: an HPA on in-flight requests per pod, minReplicas 6, maxReplicas 18 (18 × 20 = 360 connections, under 400), scale-up 100 percent per 15 s, scale-down 2 pods a minute after 300 s; a KEDA cron trigger raising the minimum 10 minutes before each campaign; overprovisioning pods holding one node of headroom. Worker: a KEDA ScaledObject on consumer lag, 0 to 24 replicas. Requests set from a week of VPA recommendations.
A lower target or spare nodes cost money every hour and make every spike painless; overprovisioning pods are the cheapest headroom but need a PriorityClass and some care. Scaling on custom metrics is more accurate and adds the adapter as a dependency. Capping replicas protects the database and means extreme spikes queue instead of failing it.