Skip to content
System design on Kubernetes · Chapter 6 of 20 Day 4: Failures

Day 4: Failures

Goal: Under load, crash a Pod, roll out again and cut a whole node off the network, counting the errors each time, and use preStop, retries and passive health checks in the Gateway to make sure users (almost) notice nothing · Duration: approx. 90 min · Prerequisite: Day 3

Briefing

  • In the predecessor course, you taught HAProxy to deal with failures: health checks, redispatch, deregistering before a restart. In the cluster, the same failures are spread over more places:
Failure Who notices How fast
Process dies (kill -9) Envoy (connection refused), kubelet (restart), probe immediately / up to 10 s
Rollout, Pod is terminated API server, then endpoints, then every proxy fractions of a second, but not at the same time
Node gone, network dead nobody right away; the node simply stops reporting ~50 s until NotReady
  • Today k6 runs at 800 or 600 requests per second through the Gateway while you inject faults. The result of each drill is the number of failed requests.
  • kurz can already shut down gracefully: on SIGTERM it keeps answering running requests for up to ten seconds (predecessor course, Day 4). You measure whether that is enough in the cluster.

Drill 1: The normal case

A baseline without disruption, and a function that takes work off your hands in the next drills: start the load, trigger a fault after ten seconds, show the result.

# on s1
# Working directory, load script and codes from yesterday
mkdir -p ~/sdk/tag04 && cd ~/sdk/tag04 && cp ../tag03/mix.js ../tag03/codes.txt .
# From today on, the target is always the Gateway
export ZIEL=http://172.16.0.126
# lauf NAME COMMAND: 40 s load at 800/s, run the command after 10 s, then show errors
lauf() {
  (RATE=800 DAUER=40s k6 run --quiet mix.js > k6-$1.txt 2>&1 &)
  sleep 10
  eval "$2"
  sleep 34
  echo "== $1"
  grep -E 'http_req_failed\.|http_reqs\.' k6-$1.txt | sed 's/  */ /g'
}
# Baseline run without disruption
lauf ruhe "true"

Expected:

== ruhe
 http_req_failed................: 0.00% 0 out of 31998
 http_reqs......................: 31998 799.839152/s

Save your progress? Sign up for free

Drill 2: A crash

kubectl delete pod --force sounds like a crash, but it is not one: the Pod disappears from the API immediately, yet the process still gets SIGTERM and shuts down gracefully.

# on s1
# Delete a kurz Pod "by force"
lauf force "kubectl -n kurz delete pod \$(kubectl -n kurz get pods -l app=kurz -o name | head -1) --grace-period=0 --force >/dev/null 2>&1"
# Wait until two Pods are running again
kubectl -n kurz rollout status deploy/kurz

Expected:

== force
 http_req_failed................: 0.00% 0 out of 32001
 http_reqs......................: 32001 799.917303/s
deployment "kurz" successfully rolled out

A real crash is kill -9 on the node: no signal the process can catch. For that you need two terminals. First check which node a kurz Pod runs on:

# on s1
# Nodes of the kurz Pods
kubectl -n kurz get pods -l app=kurz -o wide --no-headers | awk '{print $1, $7}'
# Start the load, 40 s at 800/s
(RATE=800 DAUER=40s k6 run --quiet mix.js > k6-kill9.txt 2>&1 &)
# on s2 (or the node from the output above that is not s1), within 10 s
# Kill the kurz process without warning
sudo pkill -9 -x kurz
# on s1, after 40 s
# Result and restart counter
grep -E 'http_req_failed\.|http_reqs\.' k6-kill9.txt | sed 's/  */ /g'
kubectl -n kurz get pods -l app=kurz -o wide --no-headers | awk '{print $1, $2, $4, $7}'

Expected:

 http_req_failed................: 0.89% 287 out of 31992
 http_reqs......................: 31992 799.717966/s
kurz-6489c67588-mpm9t 1/1 1 s2
kurz-6489c67588-prx65 1/1 0 s1

287 errors. The kubelet restarts the container after one second (RESTARTS 1), but until then, and until the readiness probe is green again, Envoy keeps sending part of the requests to an address that refuses connections. On the VM, HAProxy helped with option redispatch: try the request elsewhere. Envoy Gateway can do that too, with a BackendTrafficPolicy:

# on s1
# Retry requests whose connection was refused, up to twice
cat > retry.yaml <<EOF
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: BackendTrafficPolicy
metadata:
  name: kurz-retry
  namespace: kurz
spec:
  targetRefs:
  - group: gateway.networking.k8s.io
    kind: HTTPRoute
    name: kurz
  retry:
    numRetries: 2
    retryOn:
      triggers:
      - connect-failure
      - refused-stream
EOF
# Apply and check whether Envoy Gateway accepted the policy
kubectl apply -f retry.yaml && sleep 5
kubectl -n kurz get backendtrafficpolicy kurz-retry -o jsonpath='{.status.ancestors[0].conditions[0].type}={.status.ancestors[0].conditions[0].status}{"\n"}'

Expected:

backendtrafficpolicy.gateway.envoyproxy.io/kurz-retry created
Accepted=True

connect-failure and refused-stream mean: the request never reached the Pod. A new attempt is therefore safe even for POST /api/links; no duplicate link is created. Repeat the kill -9 twice under load:

Expected (two runs):

== kill9-retry-1
 http_req_failed................: 0.06% 22 out of 31958
== kill9-retry-2
 http_req_failed................: 0.05% 16 out of 31997

From 287 down to 16 to 22. What remains are requests that were already inside the Pod when it died. Envoy deliberately does not retry those with these triggers, because they might already have been executed.

Save your progress? Sign up for free

Drill 3: Rollout under load

A rollout restart replaces both Pods one after the other. Each old Pod gets SIGTERM and shuts down gracefully:

# on s1
# Rollout during the load, three times
for n in 1 2 3; do
  lauf rollout-$n "kubectl -n kurz rollout restart deploy/kurz >/dev/null"
  kubectl -n kurz rollout status deploy/kurz >/dev/null
done

Expected:

== rollout-1
 http_req_failed................: 0.04% 13 out of 31978
 http_reqs......................: 31978 799.334617/s
== rollout-2
 http_req_failed................: 0.14% 47 out of 31987
 http_reqs......................: 31987 799.534238/s
== rollout-3
 http_req_failed................: 0.13% 44 out of 31988
 http_reqs......................: 31988 799.57114/s

Few, but errors every time, even though kurz finishes answering running requests. The problem is the order. When a Pod is terminated, these happen at the same time:

  1. The kubelet sends SIGTERM. From now on, kurz accepts no new connections.
  2. The endpoint controller removes the Pod from the EndpointSlice. Envoy Gateway learns about it and sends Envoy a new configuration.

Step 2 takes a few hundred milliseconds. During that time, requests still arrive at the Pod, which is already closed. On the VM you solved that with “deregister from HAProxy first, then restart”. In the cluster you reverse the order with a pause before the SIGTERM: preStop. Since Kubernetes 1.30 there is a built-in sleep action for this that needs no shell in the image; the distroless image of kurz has none.

# on s1
# Copy yesterday's manifest and insert a 5 s preStop pause before "resources:"
cp ../tag02/kurz.yaml . && sed -i '/^        resources:/i\        lifecycle:\n          preStop:\n            sleep:\n              seconds: 5' kurz.yaml
# Show the difference
diff ../tag02/kurz.yaml kurz.yaml
# Apply and wait
kubectl apply -f kurz.yaml >/dev/null && kubectl -n kurz rollout status deploy/kurz | tail -1
# Three rollouts under load
for n in 1 2 3; do
  lauf rollout-prestop-$n "kubectl -n kurz rollout restart deploy/kurz >/dev/null"
  kubectl -n kurz rollout status deploy/kurz >/dev/null
done

Expected:

57a58,61
>         lifecycle:
>           preStop:
>             sleep:
>               seconds: 5
deployment "kurz" successfully rolled out
== rollout-prestop-1
 http_req_failed................: 0.00% 0 out of 31960
 http_reqs......................: 31960 798.886543/s
== rollout-prestop-2
 http_req_failed................: 0.00% 0 out of 31998
 http_reqs......................: 31998 799.742756/s
== rollout-prestop-3
 http_req_failed................: 0.00% 1 out of 32001
 http_reqs......................: 32001 799.930693/s
Rollout without preStop with preStop 5 s
Errors in three runs 13, 47, 44 0, 0, 1

For five seconds the Pod keeps accepting requests while it is removed everywhere. Only then does SIGTERM arrive. The pause counts toward terminationGracePeriodSeconds (default 30 s): pause plus shutdown must fit inside, otherwise SIGKILL comes.

Save your progress? Sign up for free

Drill 4: A node disappears

The hardest case: a node is still there but no longer reachable, as with a pulled network cable. You cut s2 off from s1 and s3 with a firewall. Your own SSH connection to s2 comes from your computer and stays up. As a safety measure, the command also schedules lifting the block on its own after 170 seconds.

Three steps in two terminals, in quick succession:

# on s1, terminal 1
# Where do kurz and the Envoys run?
kubectl -n kurz get pods -l app=kurz -o wide --no-headers | awk '{print $1, $7}'
kubectl -n envoy-gateway-system get pods -l app.kubernetes.io/component=proxy -o wide --no-headers | awk '{print $1, $7}'
# 150 s load at 600/s in the background
(RATE=600 DAUER=150s k6 run --quiet mix.js > k6-knoten.txt 2>&1 &)
# on s2, terminal 2, as soon as the load is running
# Drop all traffic from and to s1 and s3, tagged with the comment tag04
for ip in 172.16.0.126 172.16.0.83; do
  sudo iptables -I INPUT -s $ip -j DROP -m comment --comment tag04
  sudo iptables -I OUTPUT -d $ip -j DROP -m comment --comment tag04
done
# Safety net: delete all tag04 rules again after 170 s
sudo systemd-run --quiet --on-active=170 --unit=tag04-frei \
  sh -c 'iptables -S | grep tag04 | sed s/^-A/-D/ | while read r; do iptables $r; done'
# Time of the block
date +%T
# on s1, terminal 1
# Every 10 s: state of s2, ready kurz endpoints, ready Envoy endpoints
for i in $(seq 15); do
  printf "%s s2=%s kurz-bereit=%s envoy-bereit=%s\n" $(date +%T) \
    $(kubectl get node s2 -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}') \
    $(kubectl -n kurz get endpointslices -l kubernetes.io/service-name=kurz -o jsonpath='{range .items[*].endpoints[*]}{.conditions.ready}{","}{end}') \
    $(kubectl -n envoy-gateway-system get endpointslices -l gateway.envoyproxy.io/owning-gateway-name=web -o jsonpath='{range .items[*].endpoints[*]}{.conditions.ready}{","}{end}')
  sleep 9
done
# Result of the load
grep -E 'http_req_duration\.|http_req_failed\.|http_reqs\.|dropped' k6-knoten.txt | sed 's/  */ /g'

Expected (abridged):

kurz-b586bdcc8-29hmg s1
kurz-b586bdcc8-hskhx s2
envoy-kurz-web-01987d52-b867444d5-cmmmm s3
envoy-kurz-web-01987d52-b867444d5-p524f s2
08:10:58
08:10:58 s2=True kurz-bereit=true,true, envoy-bereit=true,true,
08:11:20 s2=True kurz-bereit=true,true, envoy-bereit=true,true,
08:11:42 s2=True kurz-bereit=true,true, envoy-bereit=true,true,
08:11:52 s2=Unknown kurz-bereit=true,false, envoy-bereit=true,false,
08:13:26 s2=Unknown kurz-bereit=true,false, envoy-bereit=true,false,
 http_req_duration..............: avg=1.05s min=0s med=30.79ms max=1m0s p(90)=3.36s p(95)=4.19s
 http_req_failed................: 2.42% 1047 out of 43239
 http_reqs......................: 43239 282.999685/s
 dropped_iterations.............: 46761 306.05121/s

For about 50 seconds, Kubernetes considers s2 healthy (bereit means ready). That is how long the kubelet stays silent before the node controller sets the node to Unknown and removes its Pods from all endpoints. During that time, connections to s2 hang until k6’s timeout (60 s). The error rate of 2.4 % is misleading: instead of 600, only 283 requests per second arrived, and k6 could not even send 46,761, because all 500 virtual users were waiting on hanging connections. For users that means: half of them see a page that does not load for a minute.

Wait until the block is lifted and s2 is Ready again:

# on s1
# Until s2 is ready again
until kubectl get node s2 -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}' | grep -q True; do sleep 2; done
kubectl get nodes --no-headers | awk '{print $1, $2}'

Expected:

s1 Ready
s2 Ready
s3 Ready

No Pod was moved: Pods on an unreachable node are only evicted after 300 seconds (toleration node.kubernetes.io/unreachable, default 300 s).

Save your progress? Sign up for free

Drill 5: Envoy notices first

Kubernetes needs 50 seconds. Envoy sees after only a few requests that a target does not answer. Two settings in the policy from Drill 2:

  • Connection setup at most 1 s (default 10 s). A connection to a dead Pod fails quickly, and the retry kicks in.
  • Passive health check (outlier detection): three connection failures in a row, and Envoy takes the target out of the rotation for 30 seconds, at most half of all targets.
# on s1
# Retry from Drill 2 plus connect timeout and passive health check
cat > retry.yaml <<EOF
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: BackendTrafficPolicy
metadata:
  name: kurz-retry
  namespace: kurz
spec:
  targetRefs:
  - group: gateway.networking.k8s.io
    kind: HTTPRoute
    name: kurz
  retry:
    numRetries: 2
    retryOn:
      triggers:
      - connect-failure
      - refused-stream
  timeout:
    tcp:
      connectTimeout: 1s
  healthCheck:
    passive:
      splitExternalLocalOriginErrors: true
      consecutiveLocalOriginFailures: 3
      interval: 2s
      baseEjectionTime: 30s
      maxEjectionPercent: 50
EOF
# Apply and check
kubectl apply -f retry.yaml && sleep 5
kubectl -n kurz get backendtrafficpolicy kurz-retry -o jsonpath='{range .status.ancestors[0].conditions[*]}{.type}={.status} {.message}{"\n"}{end}'

Expected:

backendtrafficpolicy.gateway.envoyproxy.io/kurz-retry configured
Accepted=True Policy has been accepted.

Happened during testing: The first attempt used consecutiveLocalOriginErrors and failed with strict decoding error: unknown field. The field is called consecutiveLocalOriginFailures. When a field name is wrong, kubectl explain backendtrafficpolicy.spec.healthCheck.passive shows the correct names.

splitExternalLocalOriginErrors separates errors that Envoy experiences itself (connection fails) from errors that the Pod reports (HTTP 5xx). Only the former are counted here: a 503 from kurz because the database is missing should not eject a healthy Pod.

Repeat Drill 4 with a new result file (k6-knoten-schutz.txt) and the unit name tag04-frei2 in systemd-run:

Expected:

 http_req_duration..............: avg=29.09ms min=0s med=4.59ms max=1m0s p(90)=9.59ms p(95)=12.94ms
 http_req_failed................: 0.25% 228 out of 89466
 http_reqs......................: 89466 596.413534/s
 dropped_iterations.............: 535 3.566508/s
Node failure without protection with timeout, retry, passive check
Requests/s arrived 283 of 600 596 of 600
not sent 46,761 535
failed 1,047 228
p95 4.2 s 13 ms

Most of the damage is gone, without Kubernetes having become any faster. The remaining 228 errors and the max=1m0s come from a place where Envoy can do nothing: the path to Envoy. ServiceLB on s1 also forwards connections via kube-proxy to the Envoy on s2, until its endpoint disappears after 50 seconds. That is what the Challenge is about.

Save your progress? Sign up for free

Exercise: Speed drills

  1. How long may a kurz Pod take at most after SIGTERM before the kubelet kills it hard? Read the value from the Deployment. Target time: 1 min
  2. How do you tell from kubectl get pods that a container crashed and restarted, and how do you see the reason? Target time: 2 min
  3. Why would retryOn: [5xx] be dangerous for POST /api/links? Target time: 2 min

Solution

# on s1
# 1: terminationGracePeriodSeconds from the Pod template
kubectl -n kurz get deploy kurz -o jsonpath='{.spec.template.spec.terminationGracePeriodSeconds}{"\n"}'

Expected:

30

30 seconds, the default. Of that, 5 go to the preStop pause, up to 10 to the shutdown of kurz. There is room to spare.

For 2: the RESTARTS column goes up. The reason is shown by the container’s last state: kubectl -n kurz get pod <name> -o jsonpath='{.status.containerStatuses[0].lastState.terminated.reason} {.status.containerStatuses[0].lastState.terminated.exitCode}'. After kill -9 it says Error 137 (128 + 9), after running out of memory OOMKilled 137 (Day 2).

For 3: a 5xx can occur after kurz has already stored the link, for example when the response fails because of a timeout. A new attempt then creates a second link. Retries on responses are only safe for idempotent requests; POST needs an idempotency key (predecessor course, Day 11).

Save your progress? Sign up for free

Challenge

The last 228 errors from Drill 5 come from connections that ServiceLB forwards to the Envoy on the dead node. Name two ways to avoid them, and the price of each.

Solution

  • Make Kubernetes doubt sooner: lower the controller manager’s node-monitor-grace-period (in k3s as --kube-controller-manager-arg on the server), say to 20 s. Price: during a short network glitch or with an overloaded kubelet, a healthy node is wrongly considered dead, and its Pods disappear from all endpoints.
  • A load balancer with its own health check in front (MetalLB with BGP, a hardware or cloud load balancer, HAProxy outside the cluster) that checks the nodes itself every few seconds and leaves out dead ones immediately. Price: one more component that someone has to run.
  • In addition: externalTrafficPolicy: Local on the Envoy Service. Each node then forwards only to the Envoy on itself, and only nodes with an Envoy accept traffic. That alone does not fix the error, but it makes the health check of the upstream load balancer meaningful. Envoy Gateway sets the value via the EnvoyProxy resource from Day 3.

Save your progress? Sign up for free

Checkpoint

# on s1
# preStop pause in the Deployment
kubectl -n kurz get deploy kurz -o jsonpath='{.spec.template.spec.containers[0].lifecycle.preStop.sleep.seconds}{"\n"}'
# Policy with retry, connect timeout and passive check accepted
kubectl -n kurz get backendtrafficpolicy kurz-retry -o jsonpath='{.spec.retry.numRetries} {.spec.timeout.tcp.connectTimeout} {.spec.healthCheck.passive.consecutiveLocalOriginFailures} {.status.ancestors[0].conditions[0].status}{"\n"}'
# All nodes ready again
kubectl get nodes --no-headers | awk '{print $1, $2}'
# Redirect through the Gateway
curl -s -o /dev/null -w "%{http_code}\n" http://172.16.0.126/$(head -1 ~/sdk/tag04/codes.txt)

Expected:

5
2 1s 3 True
s1 Ready
s2 Ready
s3 Ready
302
# on s2
# No tag04 rules left
sudo iptables -S | grep -c tag04

Expected:

0

Interview note

  • Graceful shutdown in Kubernetes: catching SIGTERM is not enough, because removal from the endpoints happens at the same time, not before. A short preStop pause reverses the order. Pause plus shutdown must fit into terminationGracePeriodSeconds.
  • Why is a dead node worse than a dead Pod? A dead process refuses connections immediately, a dead node does not answer at all; everyone waits until their timeout. Kubernetes only detects it after ~40–50 s. Short connect timeouts and passive health checks in the proxy bridge that time.
  • Retries: only for errors that certainly happened before processing (connection refused), or for idempotent requests. Otherwise duplicates appear, and under load retries multiply the load (retry storm, Day 12).

Enterprise note

  • preStop with sleep belongs in every template for HTTP services (Helm chart, Kustomize base). Many platforms enforce it by policy (Kyverno, Day 13).
  • You do not practice node failures for the first time in an emergency. Chaos tools such as Chaos Mesh or Litmus cut off nodes or Pods regularly, and SLO alerts show whether users would have noticed.
  • Anyone running Envoy Gateways in several zones puts a load balancer with its own health check in front and lets only nodes with a Gateway Pod accept traffic (externalTrafficPolicy: Local).

Contents

More