Day 9: Scaling with the HPA
Goal: Scale
kurzby CPU with the Horizontal Pod Autoscaler (HPA), measure when more Pods really help and when they hurt, determine the reaction time to a load spike, and trigger the most common trap of switching to the HPA once under load · Duration: approx. 100 min · Prerequisite: Day 8
Briefing
- In the predecessor course there was only one way to get more
capacity: add another VM running
kurzbehind HAProxy. On Kubernetes, an additional Pod is a number in the Deployment, and the HPA changes that number by itself – based on a metric it queries every 15 seconds. - Today’s metric is CPU. The HPA does not count it in cores but as
utilization in percent of the request. A Pod with
requests.cpu: 250mthat uses 500m has 200 % utilization. This one definition explains almost everything that surprises you today. - An HPA can only distribute Pods, it cannot create CPU. The three
nodes of the lab have 8 cores in total, and k6, Envoy, PostgreSQL,
Valkey and NATS share them with
kurz.
| Term | Meaning |
|---|---|
| Metrics API | metrics.k8s.io, served by metrics-server; k3s ships
it |
Utilization (Utilization) |
Usage divided by request, averaged over all Pods |
| Desired value | ceil(Pods × current utilization / target utilization),
bounded by min and max |
| Stabilization window | Period whose highest desired value applies when scaling down (default 300 s) |
behavior |
Limits on how fast the HPA may scale up and down |
At the end of the day, an HPA scales kurz between 2 and
6 Pods, and you know why its target is 200 % and not 70 %.
Drill 1: What the HPA sees
The HPA does not ask the Pod but the Metrics API. It returns an average over a short window for each container.
# on s1
# Working directory, take over codes and load script from Day 8
mkdir -p ~/sdk/tag09 && cd ~/sdk/tag09
cp ../tag08/codes.txt ../tag08/klick.js .
# Raw data of the Metrics API for the kurz Pods: usage in nanocores and the measurement window
kubectl get --raw /apis/metrics.k8s.io/v1beta1/namespaces/kurz/pods \
| jq -c '.items[] | select(.metadata.name | startswith("kurz")) | {pod: .metadata.name, cpu: .containers[0].usage.cpu, window}'
# Request of the Pods: the reference value for utilization
kubectl -n kurz get deploy kurz -o jsonpath='{.spec.template.spec.containers[0].resources}{"\n"}'Expected:
{"pod":"kurz-799c87fc74-m86jp","cpu":"10346036n","window":"18.657s"}
{"pod":"kurz-799c87fc74-plffd","cpu":"7576612n","window":"18.685s"}
{"limits":{"memory":"64Mi"},"requests":{"cpu":"250m","memory":"32Mi"}}
10,346,036 nanocores are just over 10m, so 4 % of 250m. The value is an average over the last 20 seconds or so, and metrics-server fetches it anew every 15 seconds. A load spike therefore reaches the HPA after 15 to 35 seconds at the earliest. That becomes important in Drill 5.
Save your progress? Sign up for free
Drill 2: The first HPA
An HPA for kurz: at least 2 Pods, at most 6, target 70 %
utilization. That is the number found in almost every example.
# on s1
# HPA: 2 to 6 Pods, target 70 % of the CPU request
cat > hpa.yaml <<'EOF'
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: kurz
namespace: kurz
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: kurz
minReplicas: 2
maxReplicas: 6
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
EOF
kubectl apply -f hpa.yaml
# after about 30 s the first measurement appears in TARGETS
sleep 30; kubectl -n kurz get hpa kurzExpected:
horizontalpodautoscaler.autoscaling/kurz created
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
kurz Deployment/kurz cpu: 3%/70% 2 6 2 30s
Now a ramp: 30 seconds at 200 requests per second, up to 1200/s in 30 seconds, hold for three minutes, back to 200/s. Alongside, a loop records every 15 seconds what the HPA measures and wants.
# on s1
# k6: ramp with adjustable peak and plateau duration
cat > rampe.js <<'EOF'
import http from "k6/http";
import { check } from "k6";
import { SharedArray } from "k6/data";
// Rampe: 30 s Ruhe, 30 s Anstieg, Plateau, dann wieder Ruhe.
const codes = new SharedArray("codes", () => open("./codes.txt").split("\n").filter(Boolean));
const ZIEL = __ENV.ZIEL || "http://localhost:8080";
const SPITZE = Number(__ENV.SPITZE || 1200);
export const options = {
scenarios: {
rampe: {
executor: "ramping-arrival-rate",
startRate: 200, timeUnit: "1s",
preAllocatedVUs: 100, maxVUs: 600,
stages: [
{ target: 200, duration: "30s" },
{ target: SPITZE, duration: "30s" },
{ target: SPITZE, duration: __ENV.PLATEAU || "3m" },
{ target: 200, duration: "10s" },
{ target: 200, duration: "1m" },
],
},
},
};
export default function () {
const code = codes[Math.floor(Math.random() * codes.length)];
const r = http.get(`${ZIEL}/${code}`, { redirects: 0 });
check(r, { "302": (x) => x.status === 302 });
}
EOF
# Function verlauf: every 15 s utilization, desired value of the HPA and ready Pods
verlauf() { T0=$(date +%s); for i in $(seq 1 $1); do
echo "$(( $(date +%s) - T0 ))s $(kubectl -n kurz get hpa kurz -o jsonpath='{.status.currentMetrics[0].resource.current.averageUtilization}% soll={.status.desiredReplicas}') bereit=$(kubectl -n kurz get deploy kurz -o jsonpath='{.status.readyReplicas}')"
sleep 15; done; }
# Ramp in the background via the Gateway, history in the foreground
k6 run -q -e ZIEL=http://172.16.0.126 rampe.js > k6-rampe.txt 2>&1 &
verlauf 24; wait
# Summary of the ramp
grep -E 'http_req_duration\.|http_req_failed\.|http_reqs' k6-rampe.txt | sed 's/ */ /g'Expected (abridged):
0s 3% soll=2 bereit=2
32s 25% soll=2 bereit=2
49s 69% soll=2 bereit=2
65s 94% soll=3 bereit=2
81s 187% soll=6 bereit=4
98s 208% soll=6 bereit=6
131s 99% soll=6 bereit=6
...
247s 100% soll=6 bereit=6
279s 31% soll=6 bereit=6
...
376s 3% soll=6 bereit=6
http_req_duration...: avg=33.29ms min=1.65ms med=19.67ms max=353.52ms p(90)=81.01ms p(95)=108.61ms
http_req_failed.....: 0.00% 0 out of 261353
http_reqs...........: 261353 843.048769/s
(soll is the desired replica count, bereit
the ready Pods.) Check the jump at 81 s: 3 Pods × 187 % / 70 % = 8.0 –
capped at 6. On the plateau, 6 Pods run at 100 %, so above the target;
maxReplicas does not allow more. After the ramp, the HPA
stays at 6 even though utilization drops to 3 %:
# on s1
# when did the HPA scale down again?
kubectl -n kurz get events --field-selector involvedObject.kind=HorizontalPodAutoscaler \
-o custom-columns=ZEIT:.lastTimestamp,MELDUNG:.messageExpected:
ZEIT MELDUNG
2026-11-25T13:16:37Z New size: 3; reason: cpu resource utilization (percentage of request) above target
2026-11-25T13:16:52Z New size: 6; reason: cpu resource utilization (percentage of request) above target
2026-11-25T13:24:54Z New size: 3; reason: All metrics below target
2026-11-25T13:25:55Z New size: 2; reason: All metrics below target
The load dropped at 13:20:20. The HPA only scales down once no higher desired value has been calculated for five minutes (stabilization window). That protects against flapping: a short pause in the load should not immediately cost Pods that are needed again half a minute later.
Save your progress? Sign up for free
Drill 3: Do the Pods help at all?
The HPA started 6 Pods because utilization was above 70 %. Whether users benefit from that, it does not say. You measure it: HPA gone, fixed Pod count, 60 seconds at 1200/s each.
# on s1
# Remove the HPA so it does not interfere
kubectl -n kurz delete hpa kurz
# Function fest: set the Pod count, wait, measure 60 s at 1200/s
fest() { kubectl -n kurz scale deploy kurz --replicas=$1 >/dev/null
kubectl -n kurz rollout status deploy kurz >/dev/null; sleep 10
echo "== $1 Pods"; k6 run -q -e ZIEL=http://172.16.0.126 -e RATE=1200 -e DAUER=60s klick.js 2>&1 \
| grep -E 'http_req_duration\.|http_reqs' | sed 's/ */ /g'; }
# two passes in different order, so that no trend distorts the numbers
fest 2; fest 6
fest 6; fest 2; fest 4Expected (abridged to p95 and throughput):
== 2 Pods p(95)=71.46ms 1193/s
== 6 Pods p(95)=97.67ms 1193/s
== 6 Pods p(95)=89.54ms 1193/s
== 2 Pods p(95)=58.23ms 1194/s
== 4 Pods p(95)=78.35ms 1192/s
More Pods, worse response times. Two reasons:
kurzhas had no CPU limit since Day 2. A Pod takes as much CPU as the node has free. Two Pods were not at their limit, they were only above their request. 100 % utilization here means “uses 250m”, not “is full”.- The bottleneck is the node. A run at 2000/s with two Pods, with
kubectl top nodesandkubectl -n kurz top podsrunning meanwhile, shows s1 at 85 %, s2 at 94 %, s3 at 84 % – and the two Pods at 723m and 570m, almost three times their request. Every additional Pod brings its own Go runtime, its own connections to Valkey, PostgreSQL and NATS, and competes for the same cores as Envoy and k6.
So the HPA from Drill 2 reacted to a signal that did not mean overload. The fault is not in the HPA but in the target: 70 % of a request that is too small.
Save your progress? Sign up for free
Drill 4: When the Pod is the bottleneck
Many platforms enforce CPU limits, for example via a LimitRange or a
policy. Then the individual Pod really is limited, and more Pods bring
more CPU. To make the effect clear, kurz gets small Pods
here: request and limit 200m each.
# on s1
# Manifest from Day 8 with CPU request and limit 200m
sed -e '/^ limits:/a\ cpu: 200m' -e 's/^ cpu: 250m/ cpu: 200m/' \
../tag08/kurz.yaml > kurz-klein.yaml
# only the resources differ
diff ../tag08/kurz.yaml kurz-klein.yaml
kubectl apply -f kurz-klein.yaml && kubectl -n kurz rollout status deploy kurz
# 2 Pods, 1000/s, 60 s
k6 run -q -e ZIEL=http://172.16.0.126 -e RATE=1000 -e DAUER=60s klick.js 2>&1 \
| grep -E 'http_req_duration\.|http_reqs|dropped' | sed 's/ */ /g'Expected:
79c79
< cpu: 250m
---
> cpu: 200m
81a82
> cpu: 200m
...
deployment "kurz" successfully rolled out
http_req_duration...: avg=363.84ms min=4.59ms med=348.5ms max=2.34s p(90)=588.54ms p(95)=672.49ms
http_reqs...........: 57521 952.473916/s
dropped_iterations..: 2479 41.049058/s
Two Pods with 400m in total cannot handle 1000/s: p95 672 ms, and k6 cannot even send 2479 requests. Now the same HPA as in Drill 2, but up to 8 Pods, and the ramp with a peak of 1000/s.
# on s1
# HPA up to 8 Pods
sed -i 's/maxReplicas: 6/maxReplicas: 8/' hpa.yaml && kubectl apply -f hpa.yaml
sleep 30
k6 run -q -e ZIEL=http://172.16.0.126 -e SPITZE=1000 rampe.js > k6-rampe-klein.txt 2>&1 &
verlauf 22; wait
# then 60 s of steady 1000/s with the Pods the HPA has started
k6 run -q -e ZIEL=http://172.16.0.126 -e RATE=1000 -e DAUER=60s klick.js 2>&1 \
| grep -E 'http_req_duration\.|http_reqs' | sed 's/ */ /g'
kubectl -n kurz get hpa kurzExpected (abridged):
33s 53% soll=3 bereit=3
65s 89% soll=4 bereit=3
81s 98% soll=4 bereit=4
97s 99% soll=6 bereit=6
130s 96% soll=7 bereit=7
147s 97% soll=8 bereit=8
...
http_req_duration...: avg=28.71ms min=1.82ms med=18.86ms max=445.35ms p(90)=64.56ms p(95)=86.27ms
http_reqs...........: 59300 988.06338/s
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
kurz Deployment/kurz cpu: 85%/70% 2 8 8 7m37s
With 8 Pods, p95 at 1000/s drops from 672 ms to 86 ms. Here the HPA helps because it gets the right signal: a Pod at 100 % of its limit really is full.
But look at how slowly it grows: 3, 4, 6, 7, 8. With limit = request, utilization can never rise above 100 %. With a target of 70 %, the HPA grows per round by at most a factor of 100/70 ≈ 1.43, no matter how large the overload is. In Drill 2, without a limit, it saw 187 % and jumped from 3 to 6 in one step.
Save your progress? Sign up for free
Drill 5: The load spike
A 30-second ramp is friendly. Real spikes (a link in a newsletter, a post that goes viral) arrive from one second to the next. How long does the HPA take from the first increase to full capacity?
Two knobs make it faster: a lower target (50 %, so that the factor
per round is 2 instead of 1.43) and explicit rules in
behavior. When scaling down, after 60 seconds of calm it
may give up two Pods per 30 seconds.
# on s1
# HPA with target 50 % and its own behavior
cat > hpa-verhalten.yaml <<'EOF'
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: kurz
namespace: kurz
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: kurz
minReplicas: 2
maxReplicas: 8
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 50
behavior:
scaleUp:
stabilizationWindowSeconds: 0
policies:
- type: Percent
value: 100
periodSeconds: 15
scaleDown:
stabilizationWindowSeconds: 60
policies:
- type: Pods
value: 2
periodSeconds: 30
EOF
kubectl apply -f hpa-verhalten.yaml
# Watch the scale-down: from 8 to 2
for i in $(seq 1 12); do r=$(kubectl -n kurz get deploy kurz -o jsonpath='{.spec.replicas}'); echo "$(date +%T) $r"; [ "$r" = 2 ] && break; sleep 15; doneExpected:
horizontalpodautoscaler.autoscaling/kurz configured
13:56:00 8
...
13:57:02 8
13:57:18 6
13:57:33 4
13:57:49 4
13:58:04 2
Two minutes instead of six, and in steps. Now the spike: from 2 Pods straight to 1000/s, for two minutes.
# on s1
# two minutes of constant 1000/s from the first second
k6 run -q -e ZIEL=http://172.16.0.126 -e RATE=1000 -e DAUER=120s klick.js > k6-spitze.txt 2>&1 &
verlauf 9; wait
grep -E 'http_req_duration\.|http_req_failed\.|dropped' k6-spitze.txt | sed 's/ */ /g'Expected:
0s 4% soll=2 bereit=2
17s 5% soll=2 bereit=2
33s 4% soll=2 bereit=2
49s 89% soll=4 bereit=4
66s 100% soll=4 bereit=4
82s 99% soll=8 bereit=4
98s 99% soll=8 bereit=8
115s 95% soll=8 bereit=8
131s 83% soll=8 bereit=8
http_req_duration...: avg=186.75ms min=1.59ms med=72.66ms max=2.1s p(90)=543.58ms p(95)=676.3ms
http_req_failed.....: 0.00% 0 out of 117185
dropped_iterations..: 2817 23.462224/s
The timeline of the spike:
| Second | What happens |
|---|---|
| 0 | 1000/s hit 2 Pods with 200m each |
| 0–49 | the HPA still sees the old utilization (measurement window + 15 s cycle of metrics-server and HPA) |
| 49 | first new measurement, 4 Pods |
| 82 | desired value 8 |
| 98 | 8 Pods ready |
Almost 100 seconds to full capacity, and the p95 over the two
minutes, at 676 ms, is exactly where two fixed Pods were in Drill 4.
Against a spike shorter than the reaction time, the HPA does not help at
all. What helps: minReplicas high enough to carry the
expected spike, or scaling up in advance if the spike can be planned
(newsletter at 9 a.m.).
Happened during testing: The first run of this spike ended with 23.6 % errors, and the HPA showed only 27 to 41 % utilization during the overload. The Pods ran without restarts. The second run with an identical setup had 0 errors. The cause could no longer be determined. That is why the repeatable run is shown here. If you see errors, check
kubectl -n kurz get eventsand Envoy’s outlier detection from Day 4.
Save your progress? Sign up for free
Drill 6: The replicas trap
The manifest kurz-klein.yaml still contains
replicas: 2. As long as an HPA is in control, that is a
time bomb: every kubectl apply resets the number. Under
load, with 8 Pods:
# on s1
# 90 s of load; after 30 s apply the manifest again, as a pipeline would
k6 run -q -e ZIEL=http://172.16.0.126 -e RATE=1000 -e DAUER=90s klick.js > k6-falle.txt 2>&1 &
sleep 30; kubectl apply -f kurz-klein.yaml
# Desired replicas in the Deployment and ready Pods
T0=$(date +%s); for i in $(seq 1 8); do echo "$(( $(date +%s) - T0 ))s spec=$(kubectl -n kurz get deploy kurz -o jsonpath='{.spec.replicas}') bereit=$(kubectl -n kurz get deploy kurz -o jsonpath='{.status.readyReplicas}')"; sleep 7; done
wait; grep -E 'http_req_duration\.|http_req_failed\.' k6-falle.txt | sed 's/ */ /g'Expected:
configmap/kurz unchanged
deployment.apps/kurz configured
service/kurz unchanged
0s spec=2 bereit=2
9s spec=2 bereit=2
17s spec=4 bereit=3
25s spec=4 bereit=4
33s spec=8 bereit=6
42s spec=8 bereit=8
http_req_duration...: avg=72.04ms min=1.78ms med=28.87ms max=1.14s p(90)=201.49ms p(95)=300.02ms
http_req_failed.....: 0.00% 0 out of 88898
Six Pods gone at once, 40 seconds until back to full strength, p95
300 ms instead of 86 ms. The obvious fix – delete replicas
from the manifest – makes it worse:
# on s1
# Manifest without replicas
sed '/^ replicas: 2$/d' kurz-klein.yaml > kurz-hpa.yaml
kubectl -n kurz get deploy kurz -o jsonpath='vorher {.spec.replicas}{"\n"}'
kubectl apply -f kurz-hpa.yaml >/dev/null
kubectl -n kurz get deploy kurz -o jsonpath='nachher {.spec.replicas}{"\n"}'Expected:
vorher 8
nachher 1
(vorher = before, nachher = after.)
kubectl apply compares three states: the file, the object
and the annotation last-applied-configuration. That
annotation still says replicas: 2. If the field is now
missing from the file, apply concludes that you want to
remove it – and the Deployment falls back to the default of 1. The right
way is to rewrite the annotation first, without touching the object:
# on s1
# Restore the starting point: annotation with replicas: 2, HPA has scaled to 5
kubectl apply -f kurz-klein.yaml >/dev/null
kubectl -n kurz scale deploy kurz --replicas=5 >/dev/null
# 1. set only the annotation to the new file
kubectl apply set-last-applied -f kurz-hpa.yaml
# 2. then apply: replicas stays as it is
kubectl apply -f kurz-hpa.yaml >/dev/null
kubectl -n kurz get deploy kurz -o jsonpath='nachher {.spec.replicas}{"\n"}'
kubectl diff -f kurz-hpa.yaml; echo "diff: $?"Expected:
configmap/kurz configured
deployment.apps/kurz configured
service/kurz configured
nachher 5
diff: 0
Happened during testing:
set-last-appliedwith a file that differs in more thanreplicasis the next trap. For this chapter it once ran with the manifest from Day 8 (without a CPU limit) against a Deployment with a 200m limit. Afterwards the limit was no longer in the annotation,applyconsidered it foreign and left it in place – and rejected the new request:must be less than or equal to cpu limit of 200m. Always runset-last-appliedwith the file that exactly matches the current object, and only then apply the actual change.
GitOps tools have the same problem in a different form: Argo CD and
Flux see the HPA value as drift from the repository. There you leave
replicas out of the manifest or exclude the field from the
comparison.
Save your progress? Sign up for free
Drill 7: CPU is not every signal
zaehler works through the stream from Day 8. Does it
need an HPA? First of all: can it go to zero when idle?
# on s1
# HPA for zaehler, minimum 0
cat > hpa-zaehler.yaml <<'EOF'
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: zaehler
namespace: kurz
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: zaehler
minReplicas: 0
maxReplicas: 4
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
EOF
kubectl apply -f hpa-zaehler.yamlExpected:
The HorizontalPodAutoscaler "zaehler" is invalid: spec.metrics: Forbidden: must specify at least one Object or External metric to support scaling to zero replicas
A Pod that does not exist has no CPU. Only something with a metric from outside the Pod can scale to zero. A second attempt with minimum 1, this time with a backlog:
# on s1
# Minimum 1; stop zaehler and collect clicks for 60 s
sed -i 's/minReplicas: 0/minReplicas: 1/' hpa-zaehler.yaml
kubectl -n kurz scale deploy zaehler --replicas=0
k6 run -q -e ZIEL=http://172.16.0.126 -e RATE=1000 -e DAUER=60s klick.js >/dev/null 2>&1
# NATS CLI as on Day 8
N="nats -s nats://kurz:lab-nats-123@$(kubectl -n nats get svc nats -o jsonpath='{.spec.clusterIP}'):4222"
echo "Rückstau: $($N consumer info KLICKS zaehler --json | jq .num_pending)"
# Create the HPA, start one zaehler, every 10 s backlog and the HPA's view
kubectl apply -f hpa-zaehler.yaml
kubectl -n kurz scale deploy zaehler --replicas=1
T0=$(date +%s); for i in $(seq 1 7); do echo "$(( $(date +%s) - T0 ))s offen=$($N consumer info KLICKS zaehler --json | jq .num_pending) $(kubectl -n kurz get hpa zaehler -o jsonpath='{.status.currentMetrics[0].resource.current.averageUtilization}% soll={.status.desiredReplicas}')"; sleep 10; doneExpected:
Rückstau: 59604
horizontalpodautoscaler.autoscaling/zaehler created
0s offen=59604 % soll=0
11s offen=0 % soll=0
...
54s offen=0 2% soll=1
64s offen=0 2% soll=1
(Rückstau = backlog, offen = pending.) A
single zaehler booked almost 60,000 clicks in less than 11
seconds – more than 5000 per second, because it writes in batches. The
HPA had its first measurement after 54 seconds, and it showed 2 %. For a
worker, CPU is a poor signal: whether work is waiting is in the stream,
not in the process. That is exactly what KEDA reads tomorrow.
# on s1
# clean up: no HPA for zaehler, back to two replicas as on Day 8
kubectl -n kurz delete hpa zaehler
kubectl -n kurz scale deploy zaehler --replicas=2Save your progress? Sign up for free
Drill 8: The right target
Back to kurz without a CPU limit, as since Day 2. From
Drill 3 you know: at 2000/s, two Pods together used about 1.3 cores
(723m and 570m), and more Pods on the same nodes brought nothing. A
sensible target is therefore not “70 % of 250m” but what a Pod handles
well. Without a limit, the target may be above 100 %: 200 % of 250m is
500m per Pod.
# on s1
# Manifest from Day 8 without replicas
sed '/^ replicas: 2$/d' ../tag08/kurz.yaml > kurz.yaml
# Annotation first to what is currently in the cluster (kurz-hpa.yaml), then switch
kubectl apply set-last-applied -f kurz-hpa.yaml >/dev/null
kubectl diff -f kurz.yaml | grep -E '^[-+] '
kubectl apply -f kurz.yaml >/dev/null && kubectl -n kurz rollout status deploy kurz
# HPA: 2 to 6 Pods, target 200 % of the request (500m per Pod)
sed -e 's/averageUtilization: 70/averageUtilization: 200/' -e 's/maxReplicas: 8/maxReplicas: 6/' hpa.yaml > hpa-ende.yaml
kubectl apply -f hpa-ende.yaml
# Ramp up to 1800/s, plateau 2 min
sleep 60
k6 run -q -e ZIEL=http://172.16.0.126 -e SPITZE=1800 -e PLATEAU=2m rampe.js > k6-rampe-ende.txt 2>&1 &
verlauf 16; wait
grep -E 'http_req_duration\.|http_req_failed\.|http_reqs|dropped' k6-rampe-ende.txt | sed 's/ */ /g'Expected:
- generation: 107
+ generation: 108
- cpu: 200m
- cpu: 200m
+ cpu: 250m
deployment "kurz" successfully rolled out
horizontalpodautoscaler.autoscaling/kurz configured
0s 3% soll=2 bereit=2
48s 77% soll=2 bereit=2
81s 201% soll=2 bereit=2
98s 253% soll=3 bereit=3
131s 202% soll=3 bereit=3
148s 200% soll=3 bereit=3
...
213s 203% soll=3 bereit=3
229s 48% soll=3 bereit=3
http_req_duration...: avg=62.84ms min=1.43ms med=40.72ms max=570.09ms p(90)=150.13ms p(95)=192.05ms
http_req_failed.....: 0.00% 0 out of 271684
http_reqs...........: 271684 1086.686659/s
dropped_iterations..: 2309 9.235581/s
At 1800/s the HPA holds 3 Pods at 200 %, without errors, p95 192 ms – in the range of what two fixed Pods managed in Drill 3 at 2000/s (166 ms). The HPA from Drill 2 would already have started 6 Pods at 1200/s, buying worse times and reserving 750m more in requests that other services lack.
The rule behind it: the target is the usage at which a Pod still responds well, divided by the request. You measure the usage, you do not guess it. Whether the request itself fits (250m is rather the lower bound here) is a question of capacity planning on Day 14.
Save your progress? Sign up for free
Exercise: Speed drills
- Which utilization does the HPA currently see, which desired value does it calculate, and when did it last scale? Target time: 1 min
- An HPA shows
cpu: <unknown>/70%. Name two causes and check the first one. Target time: 2 min - Calculate: 4 Pods, target 70 %, measured 130 %. Which desired value does the HPA calculate? And if the Pods have a limit equal to the request – can it measure 130 % at all? Target time: 2 min
Solution
# on s1
# 1: current, desired, last scaling
kubectl -n kurz get hpa kurz -o jsonpath='{.status.currentMetrics[0].resource.current.averageUtilization}% soll={.status.desiredReplicas} zuletzt={.status.lastScaleTime}{"\n"}'
# 2: error conditions of the HPA; request in the Deployment; is metrics-server running?
kubectl -n kurz describe hpa kurz | sed -n '/Conditions/,/Events/p'
kubectl -n kurz get deploy kurz -o jsonpath='{.spec.template.spec.containers[*].resources.requests.cpu}{"\n"}'
kubectl -n kube-system get deploy metrics-serverExpected (excerpt):
3% soll=2 zuletzt=2026-11-25T14:24:24Z
Conditions:
Type Status Reason Message
---- ------ ------ -------
AbleToScale True ReadyForNewScale recommended size matches current size
ScalingActive True ValidMetricFound the HPA was able to successfully calculate a replica count from cpu resource utilization (percentage of request)
ScalingLimited True TooFewReplicas the desired replica count is less than the minimum replica count
ScaledToZero False NotScaledToZero the HPA controller did not scale the workload to zero
250m
NAME READY UP-TO-DATE AVAILABLE AGE
metrics-server 1/1 1 1 21h
On 2: the two most common causes are a missing CPU request in one
container of the Pod (including a sidecar – utilization is only defined
if every container has a request) and an unreachable Metrics API.
ScalingActive False with
FailedGetResourceMetric names the reason.
On 3: ceil(4 × 130 / 70) = ceil(7.43) = 8. With limit = request, a Pod cannot use more than 100 % of its request; the HPA sees at most 100 % and calculates ceil(4 × 100 / 70) = 6. So it scales more slowly than the load demands – Drill 4.
Save your progress? Sign up for free
Challenge
A newsletter with the link kurz/abc goes out every
Monday at 9:00 a.m.; in the first two minutes 1500 clicks per second
arrive, then the rate drops to 100/s over ten minutes. The rest of the
week is quiet. Design the scaling for kurz: what does the
HPA carry, what not, and how do you make sure that enough Pods are ready
at 9:00 a.m.? Test your design with a spike of 1500/s for 2 minutes.
Solution
From Drill 5 you know: the HPA needs about 100 seconds to reach full
capacity. For a spike of 2 minutes, that is almost the whole spike. So
the spike is not carried by the HPA but by a minimum raised in advance.
A CronJob raises minReplicas at 8:55 a.m. and lowers it
again at 9:20 a.m.; the HPA itself handles the scale-down afterwards,
slowed by its stabilization window.
# on s1
# Test: raise the minimum before the spike
kubectl -n kurz patch hpa kurz --type merge -p '{"spec":{"minReplicas":4}}'
kubectl -n kurz rollout status deploy kurz
# Spike 1500/s for 2 min
k6 run -q -e ZIEL=http://172.16.0.126 -e RATE=1500 -e DAUER=120s klick.js 2>&1 \
| grep -E 'http_req_duration\.|http_req_failed\.|dropped' | sed 's/ */ /g'
# Minimum back
kubectl -n kurz patch hpa kurz --type merge -p '{"spec":{"minReplicas":2}}'Expected:
horizontalpodautoscaler.autoscaling/kurz patched
deployment "kurz" successfully rolled out
http_req_duration...: avg=46.09ms min=1.53ms med=32.34ms max=563.37ms p(90)=102.03ms p(95)=132.37ms
http_req_failed.....: 0.00% 0 out of 178767
dropped_iterations..: 1235 10.290298/s
horizontalpodautoscaler.autoscaling/kurz patched
For comparison, the same run with minReplicas: 2: p95
146 ms and 3043 requests not sent; meanwhile the HPA went up to 3 Pods.
So pre-warming brings a measurable but small gain – because
kurz without a CPU limit already uses the free CPU of the
nodes with two Pods (Drill 3). With limited Pods as in Drill 4, the
difference would be large: there, two Pods were at 672 ms. That is the
actual answer to the Challenge: how much headroom you need depends on
whether the Pod or the node is the bottleneck, and only measurement
shows that.
In operations, the raise belongs in a CronJob with a ServiceAccount
that may only patch this one HPA:
# Ausschnitt: CronJob um 8:55 Uhr montags (Zeitzone des Clusters beachten: timeZone)
apiVersion: batch/v1
kind: CronJob
metadata:
name: kurz-vorheizen
namespace: kurz
spec:
schedule: "55 8 * * 1"
timeZone: Europe/Berlin
jobTemplate:
spec:
template:
spec:
serviceAccountName: hpa-patcher
restartPolicy: OnFailure
containers:
- name: kubectl
image: registry.k8s.io/kubectl:v1.37.2
args: ["-n", "kurz", "patch", "hpa", "kurz", "--type", "merge", "-p", '{"spec":{"minReplicas":4}}'](The comment line reads: excerpt, CronJob at 8:55 a.m. on Mondays;
mind the cluster’s time zone: timeZone.) A second CronJob
at 9:20 a.m. sets minReplicas back to 2. Tomorrow KEDA
solves the same thing without a separate CronJob: there, the cron scaler
is one line next to the scaler for the queue.
Save your progress? Sign up for free
Checkpoint
# on s1
# HPA for kurz: 2 to 6 Pods, target 200 %
kubectl -n kurz get hpa kurz -o jsonpath='{.spec.minReplicas}-{.spec.maxReplicas} {.spec.metrics[0].resource.target.averageUtilization}%{"\n"}'
# the HPA can calculate
kubectl -n kurz get hpa kurz -o jsonpath='{.status.conditions[?(@.type=="ScalingActive")].status}{"\n"}'
# kurz without CPU limit, request 250m
kubectl -n kurz get deploy kurz -o jsonpath='{.spec.template.spec.containers[0].resources}{"\n"}'
# replicas is no longer in the annotation
kubectl -n kurz get deploy kurz -o jsonpath='{.metadata.annotations.kubectl\.kubernetes\.io/last-applied-configuration}' | jq .spec.replicas
# no HPA for zaehler, two replicas
kubectl -n kurz get hpa zaehler 2>&1 | tail -1; kubectl -n kurz get deploy zaehler -o jsonpath='{.status.readyReplicas}{"\n"}'Expected:
2-6 200%
True
{"limits":{"memory":"64Mi"},"requests":{"cpu":"250m","memory":"32Mi"}}
null
Error from server (NotFound): horizontalpodautoscalers.autoscaling "zaehler" not found
2
Interview note
- What does the HPA scale? The number of Pods
according to
ceil(Pods × current / target). “Current” is percent of the request, not of the node and not of the limit. Anyone who does not know the request cannot interpret the number. - More Pods are not more capacity. Here p95 got worse with 6 instead of 2 Pods (90 instead of 58 ms) because the node was the bottleneck. Horizontal scaling only helps when the Pod is limited – then clearly (672 → 86 ms).
- Reaction time: metric window + metrics-server cycle
+ HPA cycle + start and readiness of the Pod – here almost 100 seconds.
Against shorter spikes, only headroom (
minReplicas) or planning helps. - Limit = request slows the HPA down: utilization cannot exceed 100 %, so per round it grows by at most target⁻¹ (factor 1.43 at 70 %).
- Scale workers by work, not by CPU: backlog, waiting time, queue length.
Enterprise note
- In platform teams the HPA is standard, but the number in the target is rarely justified. A good review question: “What load does one Pod carry at this target, and how do you know?” The answer is a load test as in Drills 3 and 8, not a value from an example.
- An HPA without a Cluster Autoscaler only redistributes existing cores. On-prem, without new nodes at the push of a button, the gain is: quiet services release requests that others can use. You still plan total capacity (Day 14).
replicasdoes not belong in the manifest of a Deployment with an HPA. In Helm charts this is often a switch (autoscaling.enabledomitsreplicas); in Argo CD,ignoreDifferenceson/spec/replicashelps.- The HPA can also scale on custom metrics (Pods and Object metrics via a metrics adapter, such as requests per second from Prometheus). For web services that is often a better signal than CPU, but it needs an adapter that has to be operated itself.