Day 10: Scaling by queue length with KEDA
Goal: Scale
zaehlerby the backlog in the stream instead of by CPU, down to zero Pods and back up, measure where more workers stop helping, find and fix the bottleneck behind it, and pre-warmkurzon a schedule · Duration: approx. 110 min · Prerequisite: Day 9
Briefing
- On Day 9, the HPA for
zaehlerdelivered a first number after 54 seconds: 2 % CPU, while 60,000 clicks were waiting. A worker that waits on I/O never looks busy. The right signal is in the stream: how many messages no worker has acknowledged yet. - KEDA (Kubernetes Event-driven Autoscaling) reads such signals from more than 70 sources – NATS, Kafka, Prometheus, Cron – and passes them as an external metric to an HPA that KEDA creates itself. On top of that it does what the HPA cannot: go from zero Pods to one and back.
- To create any backlog at all today,
zaehleris made deliberately slow: batches of 100 and a one-second pause per batch, so at most 100 clicks per second and Pod. That is how a worker behaves that calls a slow service for each message.
| Term | Meaning |
|---|---|
| ScaledObject | KEDA resource: which Deployment, which triggers, min/max |
| Trigger / scaler | Source of the signal, here nats-jetstream and
cron |
lagThreshold |
Backlog per Pod that KEDA aims for (like the target value of the HPA) |
| Activation | Switch from 0 to 1 Pod (done by KEDA itself, not the HPA) |
cooldownPeriod |
Quiet period before KEDA goes from 1 to 0 |
fallback |
Fixed Pod count when the source does not respond |
At the end of the day, zaehler runs with zero Pods when
idle and up to ten under load, and kurz is brought to four
Pods on Mondays at 8:55 a.m.
Drill 1: Installing KEDA
# on s1
# Working directory, take over codes and load script
mkdir -p ~/sdk/tag10 && cd ~/sdk/tag10
cp ../tag08/codes.txt ../tag08/klick.js .
# Helm repository of KEDA
helm repo add kedacore https://kedacore.github.io/charts
helm repo update kedacore
# Installation in the version from the style guide
helm install keda kedacore/keda --version 2.21.1 -n keda --create-namespace --wait --timeout 5m | tail -1
# three Pods: operator, metrics server for external metrics, admission webhook
kubectl -n keda get pods -o custom-columns=NAME:.metadata.name,READY:.status.containerStatuses[0].ready
# KEDA registers as a source of external metrics
kubectl get apiservice v1beta1.external.metrics.k8s.ioExpected:
- File an issue: https://github.com/kedacore/keda/issues/new/choose
NAME READY
keda-admission-webhooks-854b484d8f-282lg true
keda-operator-5d6bbf986c-m5dr2 true
keda-operator-metrics-apiserver-54dffdb987-pdfb2 true
NAME SERVICE AVAILABLE AGE
v1beta1.external.metrics.k8s.io keda/keda-operator-metrics-apiserver True 70s
Happened during testing:
helm installfirst failed withGet "http://localhost:8080/version": connection refused. In an SSH session without a login shell,KUBECONFIGfrom.bashrcis missing; k3s’skubectlfinds its file by itself, Helm does not. Fix for such a session:export KUBECONFIG=/etc/rancher/k3s/k3s.yaml.
Save your progress? Sign up for free
Drill 2: A slow worker
zaehler has two knobs from the predecessor course:
ZAEHLER_BATCH (messages per fetch) and
ZAEHLER_PAUSE (wait time per batch). The manifest from Day
8 gets both, and replicas is dropped because KEDA will set
the number shortly (the trap from Day 9: first the annotation, then
apply).
# on s1
# Manifest from Day 8 without replicas, with batch 100 and 1 s pause
sed '/^ replicas: 1$/d' ../tag08/zaehler.yaml > zaehler.yaml
sed -i '/value: nats:\/\/kurz/a\ - name: ZAEHLER_BATCH\n value: "100"\n - name: ZAEHLER_PAUSE\n value: "1s"' zaehler.yaml
diff ../tag08/zaehler.yaml zaehler.yaml
kubectl apply set-last-applied -f ../tag08/zaehler.yaml >/dev/null
kubectl apply -f zaehler.yaml && kubectl -n kurz scale deploy zaehler --replicas=1
kubectl -n kurz rollout status deploy zaehler
# zaehler reports its settings
kubectl -n kurz logs deploy/zaehler | grep BatchExpected (excerpt):
6d5
< replicas: 1
33a33,36
> - name: ZAEHLER_BATCH
> value: "100"
> - name: ZAEHLER_PAUSE
> value: "1s"
deployment "zaehler" successfully rolled out
2026/11/25 18:41:04 zaehler: Batch 100, Pause 1s
Now 1000 clicks per second for 60 seconds, and the backlog every 10 seconds:
# on s1
# 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"
# Function offen: messages that no worker has fetched yet
offen() { $N consumer info KLICKS zaehler --json | jq .num_pending; }
k6 run -q -e ZIEL=http://172.16.0.126 -e RATE=1000 -e DAUER=60s klick.js >/dev/null 2>&1 &
T0=$(date +%s); for i in $(seq 1 10); do echo "$(( $(date +%s) - T0 ))s offen=$(offen)"; sleep 10; done; waitExpected:
0s offen=0
10s offen=9043
20s offen=18085
31s offen=27637
41s offen=36958
51s offen=46346
61s offen=54404
71s offen=53504
81s offen=52504
91s offen=51504
900 more per second while load is coming in, then 100 fewer per second. On its own, the worker would need a good nine minutes for the rest.
Save your progress? Sign up for free
Drill 3: ScaledObject by backlog
The nats-jetstream scaler does not read the backlog via
the NATS protocol but via the monitoring port 8222. Only the headless
Service nats-headless offers it; the Service
nats has only 4222. Target: 500 pending messages per Pod,
between 1 and 10 Pods.
# on s1
cat > zaehler-scaler.yaml <<'EOF'
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: zaehler
namespace: kurz
spec:
scaleTargetRef:
name: zaehler
minReplicaCount: 1
maxReplicaCount: 10
triggers:
- type: nats-jetstream
metadata:
natsServerMonitoringEndpoint: nats-headless.nats.svc.cluster.local:8222
account: $G
stream: KLICKS
consumer: zaehler
lagThreshold: "500"
EOF
kubectl apply -f zaehler-scaler.yaml
# every 10 s: backlog, ready and desired Pods
T0=$(date +%s); for i in $(seq 1 14); do echo "$(( $(date +%s) - T0 ))s offen=$(offen) pods=$(kubectl -n kurz get deploy zaehler -o jsonpath='{.status.readyReplicas}/{.spec.replicas}')"; sleep 10; done
# KEDA has created an HPA
kubectl -n kurz get hpa keda-hpa-zaehlerExpected:
scaledobject.keda.sh/zaehler created
0s offen=49304 pods=1/1
11s offen=48204 pods=1/1
22s offen=45804 pods=4/4
33s offen=40804 pods=8/8
44s offen=32404 pods=8/8
56s offen=22404 pods=10/10
67s offen=18787 pods=10/10
78s offen=17558 pods=10/10
89s offen=15855 pods=10/10
100s offen=14424 pods=10/10
...
144s offen=1903 pods=10/10
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
keda-hpa-zaehler Deployment/zaehler 122400m/500 (avg) 1 10 10 2m37s
account: $G is the global account of NATS, where all
users end up as long as no separate accounts are configured (Day 8).
KEDA scales in steps of up to four Pods every 15 seconds – that is the
default rule of the HPA that KEDA creates.
But do the math: ten workers at 100 per second each should handle 1000 clicks per second. From 56 s to 144 s it is 20,500 in 88 seconds, so 233 per second. Something is slowing things down.
Save your progress? Sign up for free
Drill 4: Where more workers stop helping
A clean measurement needs fixed Pod counts. KEDA can be paused for
this: the annotation autoscaling.keda.sh/paused-replicas
sets a fixed number as long as it is present.
# on s1
# Pause the workers (0 Pods) and collect clicks for 75 s
kubectl -n kurz annotate scaledobject zaehler autoscaling.keda.sh/paused-replicas=0 --overwrite
sleep 15; k6 run -q -e ZIEL=http://172.16.0.126 -e RATE=1000 -e DAUER=75s klick.js >/dev/null 2>&1
echo "Rückstau: $(offen)"
# Function abbau: n Pods, then measure for 20 s how fast the backlog shrinks
abbau() { kubectl -n kurz annotate scaledobject zaehler autoscaling.keda.sh/paused-replicas=$1 --overwrite >/dev/null
kubectl -n kurz rollout status deploy zaehler --timeout=90s >/dev/null; sleep 5
a=$(offen); sleep 20; b=$(offen); echo "$1 Pods: $(( (a - b) / 20 )) Klicks/s (offen $b)"; }
for n in 1 2 5 8 10 12; do abbau $n; doneExpected:
scaledobject.keda.sh/zaehler annotated
Rückstau: 74744
1 Pods: 100 Klicks/s (offen 72244)
2 Pods: 200 Klicks/s (offen 67044)
5 Pods: 425 Klicks/s (offen 55644)
8 Pods: 175 Klicks/s (offen 50526)
10 Pods: 299 Klicks/s (offen 41728)
12 Pods: 353 Klicks/s (offen 32226)
Up to five Pods, throughput grows almost linearly, then it collapses. First suspicion: the consumer allows only a limited number of unacknowledged messages.
# on s1
# Limit and state of the consumer
$N consumer info KLICKS zaehler --json | jq -c '{max_ack_pending: .config.max_ack_pending, ack_pending: .num_ack_pending, waiting: .num_waiting}'Expected:
{"max_ack_pending":1000,"ack_pending":1000,"waiting":8}
Exactly at the limit, eight fetches are waiting. Raise the limit and measure again:
# on s1
# Limit to 5000 (applies until the next start of zaehler, which recreates the consumer)
$N consumer edit KLICKS zaehler --max-pending 5000 -f >/dev/null
a=$(offen); sleep 20; b=$(offen); echo "12 Pods, Grenze 5000: $(( (a - b) / 20 )) Klicks/s, unbestätigt $($N consumer info KLICKS zaehler --json | jq .num_ack_pending)"Expected:
12 Pods, Grenze 5000: 165 Klicks/s, unbestätigt 4700
(Grenze = limit, unbestätigt =
unacknowledged.) No better. The workers now fetch more, but they cannot
keep up with acknowledging. The bottleneck sits behind them:
# on s1
# what do the workers report?
kubectl -n kurz logs -l app=zaehler --tail=3 --prefix | grep -m3 deadlock
# what are the connections in the database waiting for?
P=$(kubectl -n kurz get cluster db -o jsonpath='{.status.currentPrimary}')
kubectl -n kurz exec $P -c postgres -- psql -d kurz -tAc "SELECT wait_event_type, wait_event, state, count(*) FROM pg_stat_activity WHERE datname = 'kurz' GROUP BY 1, 2, 3 ORDER BY 4 DESC"Expected:
[pod/zaehler-5ffbd546dd-vm4tv/zaehler] 2026/11/25 18:51:28 zählen: ERROR: deadlock detected (SQLSTATE 40P01)
[pod/zaehler-5ffbd546dd-vpwwm/zaehler] 2026/11/25 18:51:42 zählen: ERROR: deadlock detected (SQLSTATE 40P01)
[pod/zaehler-5ffbd546dd-vw5nx/zaehler] 2026/11/25 18:51:38 zählen: ERROR: deadlock detected (SQLSTATE 40P01)
Lock|transactionid|active|11
Client|ClientRead|idle|3
||active|1
Eleven connections are waiting for row locks, and PostgreSQL keeps
aborting transactions because of deadlocks. The reason is in the
statement of zaehler: per batch, it increments the counters
of up to 100 different codes. With 1000 codes, the batches of parallel
workers overlap constantly, and each locks the rows in the order in
which they appear in the batch. Worker A holds abc and
wants xyz, worker B holds xyz and wants
abc. An aborted batch is not acknowledged and comes back
after 30 seconds (AckWait) – nothing is lost, but the work
is done twice.
More workers means more lock conflicts here. No setting in KEDA changes that.
Save your progress? Sign up for free
Drill 5: Ordering the locks
The classic solution: everyone locks in the same order. Then nobody
can wait for a row that someone else holds while that one waits for one
of their own. An ORDER BY in the statement is enough.
# on s1
# back up the old version, change one line
cd ~/sdk && cp zaehler/main.go zaehler/main.go.1.0
sed -i 's/\tJOIN neu USING (seq) GROUP BY k.code$/\tJOIN neu USING (seq) GROUP BY k.code ORDER BY k.code/' zaehler/main.go
diff zaehler/main.go.1.0 zaehler/main.go
# Build image 1.1 and push it to the registry
sudo docker build -q -t 172.16.0.126:5000/zaehler:1.1 zaehler && sudo docker push -q 172.16.0.126:5000/zaehler:1.1
# Manifest to 1.1, roll out
cd ~/sdk/tag10 && sed -i 's#zaehler:1.0#zaehler:1.1#' zaehler.yaml && kubectl apply -f zaehler.yamlExpected (excerpt):
31c31
< JOIN neu USING (seq) GROUP BY k.code
---
> JOIN neu USING (seq) GROUP BY k.code ORDER BY k.code
172.16.0.126:5000/zaehler:1.1
deployment.apps/zaehler configured
The same measurement as in Drill 4, with a new backlog. The restart has recreated the consumer with the default limit of 1000.
# on s1
kubectl -n kurz annotate scaledobject zaehler autoscaling.keda.sh/paused-replicas=0 --overwrite >/dev/null
sleep 20; k6 run -q -e ZIEL=http://172.16.0.126 -e RATE=1000 -e DAUER=90s klick.js >/dev/null 2>&1
for n in 5 10 15; do abbau $n; done
# Deadlocks since the switch
kubectl -n kurz logs -l app=zaehler --tail=200 | grep -c deadlockExpected:
5 Pods: 495 Klicks/s (offen 87400)
10 Pods: 960 Klicks/s (offen 61300)
15 Pods: 670 Klicks/s (offen 42075)
0
| Pods | zaehler:1.0 |
zaehler:1.1 |
|---|---|---|
| 5 | 425/s | 495/s |
| 10 | 299/s | 960/s |
| 15 | – | 670/s |
No more deadlocks, and up to ten Pods throughput grows linearly. At
15 Pods the consumer’s limit now really kicks in: 15 × 100 messages per
batch are 1500 unacknowledged, 1000 are allowed. This gives a rule for
maxReplicaCount: at most
max_ack_pending / batch, here 10.
# on s1
# let KEDA take control again
kubectl -n kurz annotate scaledobject zaehler autoscaling.keda.sh/paused-replicas-Save your progress? Sign up for free
Drill 6: To zero and back
With minReplicaCount: 0, KEDA handles the step between
zero and one Pod itself; the HPA cannot do that (Day 9, Drill 7).
cooldownPeriod is the quiet period before shutting
down.
# on s1
# Minimum 0, 60 s of quiet until shutdown, polling every 5 s
sed -e 's/minReplicaCount: 1/minReplicaCount: 0/' -e 's/ maxReplicaCount: 10/ maxReplicaCount: 10\n pollingInterval: 5\n cooldownPeriod: 60/' zaehler-scaler.yaml > zaehler-scaler-null.yaml
kubectl apply -f zaehler-scaler-null.yaml
T0=$(date +%s); for i in $(seq 1 30); do r=$(kubectl -n kurz get deploy zaehler -o jsonpath='{.spec.replicas}'); echo "$(( $(date +%s) - T0 ))s pods=$r"; [ "$r" = 0 ] && break; sleep 10; doneExpected:
scaledobject.keda.sh/zaehler configured
1s pods=10
...
43s pods=10
53s pods=0
From ten straight to zero as soon as the backlog has been empty for 60 seconds. Now the way back, with a test of “exactly once”: clear the counters, note the position of the stream, 30 seconds of 200 clicks per second.
# on s1
P=$(kubectl -n kurz get cluster db -o jsonpath='{.status.currentPrimary}')
kubectl -n kurz exec $P -c postgres -- psql -d kurz -qc 'TRUNCATE klicks'
A=$($N stream info KLICKS --json | jq .state.last_seq)
k6 run -q -e ZIEL=http://172.16.0.126 -e RATE=200 -e DAUER=30s klick.js >/dev/null 2>&1 &
T0=$(date +%s); for i in $(seq 1 24); do echo "$(( $(date +%s) - T0 ))s offen=$(offen) pods=$(kubectl -n kurz get deploy zaehler -o jsonpath='{.status.readyReplicas}/{.spec.replicas}')"; sleep 5; done; wait
B=$($N stream info KLICKS --json | jq .state.last_seq)
echo "Stream: $((B - A)) neue Nachrichten, DB: $(kubectl -n kurz exec $P -c postgres -- psql -d kurz -tAc 'SELECT sum(anzahl) FROM klicks')"Expected (abridged):
0s offen=0 pods=/0
6s offen=1170 pods=3/4
13s offen=0 pods=4/4
20s offen=0 pods=4/8
26s offen=0 pods=8/8
38s offen=0 pods=10/10
...
87s offen=0 pods=10/10
93s offen=0 pods=/0
Stream: 6001 neue Nachrichten, DB: 6001
Two things stand out. First: from zero to four Pods in six seconds, and not a single click was lost – the stream holds the messages until someone fetches them. Second: for 200 clicks per second, two workers are enough, but KEDA started ten. What does KEDA see?
# on s1
# the value KEDA delivers to the HPA, next to the consumer's counters
M="/apis/external.metrics.k8s.io/v1beta1/namespaces/kurz/s0-nats-jetstream-KLICKS?labelSelector=scaledobject.keda.sh%2Fname%3Dzaehler"
k6 run -q -e ZIEL=http://172.16.0.126 -e RATE=200 -e DAUER=40s klick.js >/dev/null 2>&1 &
T0=$(date +%s); for i in $(seq 1 9); do C=$($N consumer info KLICKS zaehler --json)
echo "$(( $(date +%s) - T0 ))s pending=$(echo $C | jq .num_pending) ack_pending=$(echo $C | jq .num_ack_pending) keda=$(kubectl get --raw "$M" | jq -r '.items[0].value') pods=$(kubectl -n kurz get deploy zaehler -o jsonpath='{.spec.replicas}')"; sleep 5; done; waitExpected:
0s pending=0 ack_pending=0 keda=108 pods=0
7s pending=555 ack_pending=400 keda=772 pods=4
13s pending=0 ack_pending=253 keda=258 pods=4
20s pending=0 ack_pending=312 keda=250 pods=7
26s pending=0 ack_pending=281 keda=336 pods=7
32s pending=0 ack_pending=321 keda=352 pods=7
38s pending=113 ack_pending=448 keda=579 pods=2
KEDA’s value is around num_pending + num_ack_pending:
messages that a worker has already fetched and is processing also count
as backlog. On waking up from zero, everything also piles up in the
first seconds until the first Pod is running. The desired value jumps
up, and the HPA behind it adds up to four Pods at once.
A brake on scaling up helps against this. KEDA passes it through to the HPA:
# on s1
# at most 2 Pods added per 15 s, smooth the desired value over 15 s
sed 's/ cooldownPeriod: 60/ cooldownPeriod: 60\n advanced:\n horizontalPodAutoscalerConfig:\n behavior:\n scaleUp:\n stabilizationWindowSeconds: 15\n policies:\n - type: Pods\n value: 2\n periodSeconds: 15/' zaehler-scaler-null.yaml > zaehler-scaler-bremse.yaml
kubectl apply -f zaehler-scaler-bremse.yaml
# wait until KEDA is at 0, then 60 s each at 200/s and 1000/s: highest Pod count and history
until [ "$(kubectl -n kurz get deploy zaehler -o jsonpath='{.spec.replicas}')" = 0 ]; do sleep 10; done
for rate in 200 1000; do k6 run -q -e ZIEL=http://172.16.0.126 -e RATE=$rate -e DAUER=60s klick.js >/dev/null 2>&1 &
T0=$(date +%s); max=0; s=""; for i in $(seq 1 14); do p=$(kubectl -n kurz get deploy zaehler -o jsonpath='{.spec.replicas}')
s="$s $(( $(date +%s) - T0 ))s:$p/$(offen)"; [ "$p" -gt "$max" ] && max=$p; sleep 5; done; wait; echo "$rate/s: max $max Pods |$s"; doneExpected:
200/s: max 3 Pods | 0s:0/96 6s:1/954 12s:3/1087 18s:3/543 23s:3/29 29s:3/0 ...
1000/s: max 10 Pods | 1s:3/11 7s:5/4489 13s:5/7674 19s:7/10645 24s:7/13192 30s:7/15541 36s:9/17756 42s:9/20057 48s:9/21329 54s:10/22370 59s:10/23352 65s:10/18854 71s:10/13254 76s:10/7854
At 200 per second, three Pods instead of ten. The price shows at 1000 per second: 54 seconds to full strength, and the backlog grows to 23,000 before it shrinks. For clicks that does not matter – they are counted a little later. For work with a promise (“order confirmation within 30 seconds”) it would be too slow. That is the trade-off you make here: resources versus delay.
Save your progress? Sign up for free
Drill 7: When the source goes silent
What does KEDA do when it cannot read the backlog? Test with the
wrong Service (nats instead of nats-headless,
without port 8222) and a fallback:
# on s1
# wrong endpoint, fallback: 4 Pods after 3 failures
sed -e 's/nats-headless.nats/nats.nats/' -e 's/ cooldownPeriod: 60/ cooldownPeriod: 60\n fallback:\n failureThreshold: 3\n replicas: 4/' zaehler-scaler-bremse.yaml > zaehler-scaler-falsch.yaml
kubectl apply -f zaehler-scaler-falsch.yaml
T0=$(date +%s); for i in $(seq 1 10); do echo "$(( $(date +%s) - T0 ))s pods=$(kubectl -n kurz get deploy zaehler -o jsonpath='{.spec.replicas}') fallback=$(kubectl -n kurz get scaledobject zaehler -o jsonpath='{.status.conditions[?(@.type=="Fallback")].status}')"; sleep 10; doneExpected:
scaledobject.keda.sh/zaehler configured
0s pods=0 fallback=False
22s pods=0 fallback=False
33s pods=1 fallback=True
44s pods=3 fallback=True
66s pods=4 fallback=True
99s pods=4 fallback=True
After three failed queries, KEDA switches to the fallback count.
Without fallback, it would stay at the last Pod count –
here zero. So a worker with minReplicaCount: 0 and no
fallback silently stops working when NATS monitoring fails, and the
stream fills up (Day 8, Exercise 3).
# on s1
# correct endpoint, brake and fallback stay: this is the final state
sed 's/nats.nats.svc/nats-headless.nats.svc/' zaehler-scaler-falsch.yaml > zaehler-scaler-ende.yaml
kubectl apply -f zaehler-scaler-ende.yamlSave your progress? Sign up for free
Exercise: Speed drills
- Which ScaledObjects exist, are they ready, active, in fallback? Target time: 1 min
- Which value does KEDA currently deliver for
zaehler, and how many Pods does that give withlagThreshold: 500? Target time: 2 min - A colleague sets
maxReplicaCount: 50, andzaehlerfetches batches of 200. What happens from which Pod onward? Target time: 2 min
Solution
# on s1
# 1: overview
kubectl -n kurz get scaledobjects
# 2: external value, from it ceil(value / 500) Pods
kubectl get --raw "$M" | jq -r '.items[0].value'Expected (when idle, after the Challenge):
NAME SCALETARGETKIND SCALETARGETNAME MIN MAX READY ACTIVE FALLBACK PAUSED TRIGGERS AUTHENTICATIONS AGE
kurz apps/v1.Deployment kurz 2 6 True False False False cpu,cron 12m
zaehler apps/v1.Deployment zaehler 0 10 True False False False nats-jetstream 41m
0
On 3: max_ack_pending is 1000. With batches of 200, from
the sixth Pod onward more messages are in flight than the consumer
allows. Additional Pods wait for fetches and bring nothing; KEDA starts
them anyway because the backlog stays large. Either
maxReplicaCount: 5 or raise the consumer’s limit
permanently – in the code of zaehler
(MaxAckPending in the ConsumerConfig), because
a change via the CLI is overwritten by zaehler at its next
start.
Save your progress? Sign up for free
Challenge
The pre-warming from Day 9 – four Pods for kurz on
Mondays from 8:55 to 9:20 a.m. – without a separate CronJob, using KEDA.
The CPU target from Day 9 (200 %) should continue to apply. Test the
schedule with a window that starts in two minutes.
Solution
A ScaledObject with two triggers: cpu takes over the HPA
from Day 9, cron sets a minimum count within the time
window. KEDA takes the higher of the two desired values.
# on s1
cat > kurz-scaler.yaml <<'EOF'
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: kurz
namespace: kurz
spec:
scaleTargetRef:
name: kurz
minReplicaCount: 2
maxReplicaCount: 6
triggers:
- type: cpu
metricType: Utilization
metadata:
value: "200"
- type: cron
metadata:
timezone: Europe/Berlin
start: 55 8 * * 1
end: 20 9 * * 1
desiredReplicas: "4"
EOF
kubectl apply -f kurz-scaler.yamlExpected:
Error from server (Forbidden): error when creating "kurz-scaler.yaml": admission webhook "vscaledobject.kb.io" denied the request: the workload 'kurz' of type 'apps/v1.Deployment' is already managed by the hpa 'kurz'
KEDA’s webhook prevents two controllers from fighting over the same Deployment. The HPA from Day 9 has to go first:
# on s1
kubectl -n kurz delete hpa kurz
kubectl apply -f kurz-scaler.yaml
# Test: window starting in 2 min for 3 min, every day
S=$(TZ=Europe/Berlin date -d '+2 min' '+%M %H'); E=$(TZ=Europe/Berlin date -d '+5 min' '+%M %H')
sed -e "s/start: 55 8 \* \* 1/start: $S * * */" -e "s/end: 20 9 \* \* 1/end: $E * * */" kurz-scaler.yaml > kurz-scaler-probe.yaml
kubectl apply -f kurz-scaler-probe.yaml
for i in $(seq 1 13); do echo "$(TZ=Europe/Berlin date +%H:%M:%S) pods=$(kubectl -n kurz get deploy kurz -o jsonpath='{.spec.replicas}')"; sleep 30; doneExpected (window 20:14–20:17):
horizontalpodautoscaler.autoscaling "kurz" deleted from kurz namespace
scaledobject.keda.sh/kurz created
scaledobject.keda.sh/kurz configured
20:12:04 pods=2
20:13:37 pods=2
20:14:08 pods=4
...
20:17:45 pods=4
20:18:16 pods=4
Right on time to four – but after the window it stays there. The HPA
that KEDA creates has the five-minute stabilization window for scaling
down (Day 9): at 20:22:01 it was back to two Pods. So plan the end of
the window five minutes earlier, or give kurz its own
behavior as in Drill 6. Afterwards apply the real schedule
again:
# on s1
kubectl apply -f kurz-scaler.yamlSave your progress? Sign up for free
Checkpoint
# on s1
# KEDA is running, external metrics available
kubectl get apiservice v1beta1.external.metrics.k8s.io -o jsonpath='{.status.conditions[0].status}{"\n"}'
# two ScaledObjects, both ready
kubectl -n kurz get scaledobjects -o custom-columns=NAME:.metadata.name,MIN:.spec.minReplicaCount,MAX:.spec.maxReplicaCount,TRIGGER:.spec.triggers[*].type
# no separate HPA anymore, only KEDA's
kubectl -n kurz get hpa -o custom-columns=NAME:.metadata.name
# zaehler 1.1 with batch 100
kubectl -n kurz get deploy zaehler -o jsonpath='{.spec.template.spec.containers[0].image}{"\n"}'
# fallback configured
kubectl -n kurz get scaledobject zaehler -o jsonpath='{.spec.fallback}{"\n"}'Expected:
True
NAME MIN MAX TRIGGER
kurz 2 6 cpu,cron
zaehler 0 10 nats-jetstream
NAME
keda-hpa-kurz
keda-hpa-zaehler
172.16.0.126:5000/zaehler:1.1
{"behavior":"static","failureThreshold":3,"replicas":4}
Interview note
- Scale workers by work, not by CPU. Backlog is the signal that directly tells you whether workers are missing. KEDA translates it into an HPA and can additionally go to zero.
- More workers are only as good as what lies behind
them. Here throughput fell from 425 to 175 clicks per second
when five workers became eight – because of deadlocks on hot rows. One
ORDER BYline brought ten workers to 960 per second. - Queue limits belong in the calculation:
max_ack_pending / batchis the sensible upper bound for workers on one consumer. - Scale-to-zero costs reaction time and needs a plan for
failures of the metric source (
fallback), otherwise you are left with zero workers.
Enterprise note
- KEDA is a CNCF project (graduated) and in many platforms the standard for workers. Important in operations: the metric source (here NATS monitoring) becomes part of the control loop and needs the same availability as the worker itself.
- A ScaledObject takes over the Deployment completely.
replicasdoes not belong in the manifest, and in GitOps/spec/replicasbelongs on the ignore list (Day 9). A second HPA is rejected by the webhook – that is intended. - For batch work that needs one Pod per message (video conversion,
reports), there is
ScaledJobinstead ofScaledObject: KEDA starts Jobs instead of Pods of a Deployment. - Pre-warming on a schedule is cheap and reliable when the spike can be planned. For unpredictable spikes, all that remains is headroom or faster starts (small images, fast readiness).