Day 2: Availability and scaling
Goal: A service spreads across the nodes, grows under load with the HPA, survives the draining of a node thanks to a PodDisruptionBudget, and platform services get priority · Duration: approx. 60 min · Prerequisite: Day 1
Briefing
- Four tools decide whether a service survives maintenance and load:
| Tool | Question | Who acts |
|---|---|---|
| Topology Spread | Where do the replicas run? | Scheduler at creation time |
| HorizontalPodAutoscaler | How many replicas? | HPA controller, every 15 s |
| PodDisruptionBudget | How many may be missing at the same time? | Eviction API (drain, upgrades) |
| PriorityClass | Who gets space when it is scarce? | Scheduler, by preemption if necessary |
- A platform gives teams guardrails for this instead of freedom: every service with more than one replica gets a PDB, every scaled service a spread rule. Day 13 enforces this with Kyverno.
- Today you see two errors that are common in real clusters and that the cluster does not report to you as errors – only as pods that do not start.
Drill 1: A distributed service
The service api is a small PHP program from the
Kubernetes docs that consumes CPU on every call – ideal for watching the
HPA at work.
# on cp1
mkdir -p ~/cnpe/tag02 && cd ~/cnpe/tag02
cat > api.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
name: api
namespace: team-blue
spec:
replicas: 2
selector:
matchLabels: {app: api}
template:
metadata:
labels: {app: api}
spec:
topologySpreadConstraints:
- maxSkew: 1 # difference of at most 1 pod between domains
topologyKey: kubernetes.io/hostname # domain = node
whenUnsatisfiable: DoNotSchedule # rather not start than distribute unevenly
labelSelector:
matchLabels: {app: api} # pods with this label are counted
containers:
- name: api
image: registry.k8s.io/hpa-example
ports: [{containerPort: 80}]
resources:
requests: {cpu: 100m, memory: 64Mi} # basis for the HPA's percentage calculation
limits: {cpu: 300m, memory: 128Mi}
---
apiVersion: v1
kind: Service
metadata:
name: api
namespace: team-blue
spec:
selector: {app: api}
ports: [{port: 80}]
EOF
k apply -f api.yaml
k -n team-blue rollout status deploy/api --timeout=120s
k -n team-blue get pods -l app=api -o wideExpected (abridged):
deployment.apps/api created
service/api created
deployment "api" successfully rolled out
NAME READY STATUS ... NODE
api-589fc4fbcb-9t9dd 1/1 Running ... worker2
api-589fc4fbcb-ct5m8 1/1 Running ... worker1
Save your progress? Sign up for free
Drill 2: The HPA under load
# on cp1
# HPA: target 50 % CPU utilisation (measured against the request), 2 to 6 replicas
# --cpu=50% target value; --min/--max limits of the replica count
k -n team-blue autoscale deployment api --cpu=50% --min=2 --max=6
# load generator: a pod that calls the service in a loop
k -n team-blue run last --image=busybox:1.37 --restart=Never -- \
/bin/sh -c 'while true; do wget -q -O- http://api >/dev/null; done'
# wait two and a half minutes, then take a look
sleep 150
k -n team-blue get hpa api
k -n team-blue get deploy api
k -n team-blue get pods -l app=api -o wideExpected (abridged):
horizontalpodautoscaler.autoscaling/api autoscaled
pod/last created
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
api Deployment/api cpu: 167%/50% 2 6 6 2m31s
NAME READY UP-TO-DATE AVAILABLE AGE
api 2/6 6 2 2m33s
api-589fc4fbcb-4x5qj 1/1 Running ... worker2
api-589fc4fbcb-722dd 0/1 Pending ... <none>
api-589fc4fbcb-97c7z 1/1 Running ... worker1
api-589fc4fbcb-cj42d 0/1 Pending ... <none>
api-589fc4fbcb-nsvbg 0/1 Pending ... <none>
api-589fc4fbcb-r9zkx 0/1 Pending ... <none>
The HPA has done its job – 6 replicas requested. But only 2 are running. Why?
# on cp1
# events of the first waiting pod
P=$(k -n team-blue get pods -l app=api --field-selector=status.phase=Pending -o name | head -1)
k -n team-blue describe $P | grep -A3 '^Events' | tail -1Expected:
Warning FailedScheduling 106s default-scheduler 0/3 nodes are available: 1 node(s) had untolerated taint(s), 2 node(s) didn't match pod topology spread constraints. preemption: 0/3 nodes are available: 1 Preemption is not helpful for scheduling
The spread rule counts all three nodes as domains –
including cp1, where an api pod can never land because of
its taint node-role.kubernetes.io/control-plane. So cp1
always has 0 pods. A third pod on a worker would mean 2 against 0, a
difference of 2 – forbidden. The default behind this is called
nodeTaintsPolicy: Ignore: taints are ignored when counting.
With Honor, only nodes whose taints the pod tolerates are
counted.
Save your progress? Sign up for free
Drill 3: Two corrections
You correct the spread rule – and at the same time a second error
that would have struck on the next apply:
replicas: 2 in the manifest. Every k apply
resets the replica count to 2 and overwrites what the HPA decided. A
Deployment under an HPA has no
replicas.
# on cp1
cat > api.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
name: api
namespace: team-blue
spec: # no replicas: the HPA decides that
selector:
matchLabels: {app: api}
template:
metadata:
labels: {app: api}
spec:
topologySpreadConstraints:
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: DoNotSchedule
nodeTaintsPolicy: Honor # only count nodes the pod tolerates
labelSelector:
matchLabels: {app: api}
containers:
- name: api
image: registry.k8s.io/hpa-example
ports: [{containerPort: 80}]
resources:
requests: {cpu: 100m, memory: 64Mi}
limits: {cpu: 300m, memory: 128Mi}
---
apiVersion: v1
kind: Service
metadata:
name: api
namespace: team-blue
spec:
selector: {app: api}
ports: [{port: 80}]
EOF
k apply -f api.yaml
sleep 60
k -n team-blue get hpa api
k -n team-blue get deploy api
# count pods per node
k -n team-blue get pods -l app=api -o wide --no-headers | awk '{print $7}' | sort | uniq -cExpected:
deployment.apps/api configured
service/api unchanged
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
api Deployment/api cpu: 84%/50% 2 6 6 4m34s
NAME READY UP-TO-DATE AVAILABLE AGE
api 6/6 6 6 4m36s
3 worker1
3 worker2
Six replicas, three per worker. Utilisation drops because the load is now spread out.
Save your progress? Sign up for free
Drill 4: Draining with a PodDisruptionBudget
Maintenance on worker1: kernel update, reboot.
kubectl drain cordons the node and evicts
the pods via the Eviction API. A PDB tells this API how many pods of
api may be missing at the same time.
# on cp1
# stop the load
k -n team-blue delete pod last --now
# PDB: at most 1 pod of api may be missing at the same time
# --selector which pods are protected
# --max-unavailable how many may be missing (alternative: --min-available)
k -n team-blue create poddisruptionbudget api --selector=app=api --max-unavailable=1
k -n team-blue get pdb api
# drain worker1
# --ignore-daemonsets DaemonSet pods (Cilium) stay, they belong to the node
# --delete-emptydir-data pods with emptyDir may go, their data is then gone
# --timeout=300s give up after 5 minutes instead of waiting forever
k drain worker1 --ignore-daemonsets --delete-emptydir-data --timeout=300s
k -n team-blue get pods -l app=api -o wide --no-headers | awk '{print $7}' | sort | uniq -c
k get node worker1Expected (abridged):
poddisruptionbudget.policy/api created
NAME MIN AVAILABLE MAX UNAVAILABLE ALLOWED DISRUPTIONS AGE
api N/A 1 1 1s
evicting pod team-blue/api-f74849d99-4jctv
evicting pod team-blue/api-f74849d99-kf52d
error when evicting pods/"api-f74849d99-kf52d" -n "team-blue" (will retry after 5s): Cannot evict pod as it would violate the pod's disruption budget.
error when evicting pods/"api-f74849d99-r6tf5" -n "team-blue" (will retry after 5s): Cannot evict pod as it would violate the pod's disruption budget.
pod/api-f74849d99-4jctv evicted
...
pod/api-f74849d99-kf52d evicted
...
pod/api-f74849d99-r6tf5 evicted
node/worker1 drained
6 worker2
NAME STATUS ROLES AGE VERSION
worker1 Ready,SchedulingDisabled <none> 24m v1.37.3
The error messages are the desired behaviour here: drain wanted to
evict three pods at once, the PDB only allowed one. Only when the
replacement on worker2 was ready could the next one go. Thanks to
nodeTaintsPolicy: Honor, the replacement pods land on
worker2 – the cordoned worker1 carries the taint
node.kubernetes.io/unschedulable and no longer counts as a
domain.
Maintenance done, node back:
# on cp1
k uncordon worker1Expected:
node/worker1 uncordoned
The pods do not move back by themselves – Kubernetes does not move running pods. Only new pods (next rollout, next scale-up) use worker1 again.
Save your progress? Sign up for free
Drill 5: Priority for the platform
When space gets scarce, priority decides who starts – and who gets evicted if necessary. Gitea is a platform service: if it fails, no team can deliver anymore from Day 3 on.
# on cp1
# existing classes: two for system components
k get priorityclass
# own class for platform services
# --value higher = more important; pods without a class have 0
# --description purpose, readable for others
k create priorityclass plattform-kritisch --value=100000 \
--description='Dienste der Plattform: Git, GitOps, Monitoring'
# switch Gitea via Helm, not via kubectl patch: otherwise the next helm upgrade resets it
cd ~/cnpe/tag00
helm upgrade gitea gitea-charts/gitea --version 12.7.0 -n gitea -f gitea-werte.yaml \
--set priorityClassName=plattform-kritisch
k -n gitea rollout status deploy/gitea --timeout=300s
k -n gitea get pod -l app.kubernetes.io/name=gitea \
-o custom-columns=NAME:.metadata.name,CLASS:.spec.priorityClassName,PRIO:.spec.priority,STATUS:.status.phaseExpected (abridged):
NAME VALUE GLOBAL-DEFAULT AGE PREEMPTIONPOLICY
system-cluster-critical 2000000000 false 26m PreemptLowerPriority
system-node-critical 2000001000 false 26m PreemptLowerPriority
priorityclass.scheduling.k8s.io/plattform-kritisch created
STATUS: deployed
REVISION: 2
deployment "gitea" successfully rolled out
NAME CLASS PRIO STATUS
gitea-5c88dbf968-2spzr plattform-kritisch 100000 Running
The number is written into the pod at creation time
(spec.priority). A later change to the class does not
change running pods.
Save your progress? Sign up for free
Exercise: Calm after the load
Time limit: 5 minutes. The load is gone. How many replicas will
api have in five minutes, and why does the HPA not shrink
immediately?
Solution
# on cp1
k -n team-blue get hpa api
# behaviour when scaling down: default waiting time 300 s
k explain hpa.spec.behavior.scaleDown.stabilizationWindowSeconds | head -14Expected (abridged, after a good five minutes without load):
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
api Deployment/api cpu: 1%/50% 2 6 2 12m
...
stabilizationWindowSeconds is the number of seconds for which past
recommendations should be considered while scaling up or scaling down.
... If not set, use the default values: - For
scale up: 0 (i.e. no stabilization is done). - For scale down: 300 (i.e. the
stabilization window is 300 seconds long).
The HPA only scales down once the recommendation has been below the
current number for five minutes (stabilisation window)
– so that short pauses in the load do not lead to constant ups and
downs. After that it goes back to --min=2. Scaling up, on
the other hand, happens immediately.
Save your progress? Sign up for free
Challenge
Time limit: 10 minutes. Team Blue sets the PDB of api to
--min-available=6. What happens on the next
drain, and how do you quickly find out in the exam which
PDB is blocking?
Solution
With minAvailable equal to the number of pods,
ALLOWED DISRUPTIONS is always 0. drain keeps trying
endlessly (until --timeout) and reports
would violate the pod's disruption budget on every
attempt.
# on cp1
# all PDBs that currently allow no disruption
k get pdb -A -o custom-columns=NS:.metadata.namespace,NAME:.metadata.name,ALLOWED:.status.disruptionsAllowed \
| awk 'NR==1 || $3==0'Remedy: adjust the PDB (k -n team-blue edit pdb api) or
scale up beforehand. Deleting a PDB to push maintenance through is the
emergency exit – and belongs in the log.
Save your progress? Sign up for free
Checkpoint
# on cp1
# HPA with limits 2 and 6
k -n team-blue get hpa api -o jsonpath='{.spec.minReplicas} {.spec.maxReplicas}{"\n"}'
# spread rule with Honor
k -n team-blue get deploy api -o jsonpath='{.spec.template.spec.topologySpreadConstraints[0].nodeTaintsPolicy}{"\n"}'
# PDB exists
k -n team-blue get pdb api -o jsonpath='{.spec.maxUnavailable}{"\n"}'
# all nodes schedulable again (no line with SchedulingDisabled: 0)
k get nodes --no-headers | grep -c SchedulingDisabled
# Gitea with priority
k -n gitea get pod -l app.kubernetes.io/name=gitea -o jsonpath='{.items[0].spec.priority}{"\n"}'Expected:
2 6
Honor
1
0
100000
Interview Note
- An HPA is at 6, but only 2 pods are running – what do you check? Events of the pending pods: quota, node resources, taints, affinities, topology spread. The HPA does not report an error.
- Why no
replicasin the manifest with an HPA? Every apply and every GitOps sync resets the number; Argo CD would fight with the HPA over the replica count. - PDB with
maxUnavailableorminAvailable?maxUnavailableadapts to the replica count;minAvailableas a fixed number blocks every maintenance when there are few replicas.
Enterprise Note
- Zones instead of nodes as the domain
(
topology.kubernetes.io/zone), plus a second rule per node withScheduleAnyway. - Enforce PDBs for every service running multiple replicas as a policy
(Day 13), but forbid
minAvailableequal to the replica count – otherwise teams block cluster upgrades. - Assign PriorityClasses centrally and protect them by policy; otherwise teams give themselves the highest class.
- HPA with custom metrics (requests per second, queue length) instead of CPU – via Prometheus Adapter or KEDA.