Skip to content
System design on Kubernetes · Chapter 4 of 20 Day 2: Measuring in the cluster

Day 2: Measuring in the cluster

Goal: Put kurz under load in the cluster, find the bottleneck with Little’s Law, set requests and limits, make CPU throttling visible and compare the numbers with those from the VMs · Duration: approx. 90 min · Prerequisite: Day 1

Briefing

  • In the predecessor course, kurz ran as a process on a VM. It got as much CPU and memory as the machine had to give. In the cluster, it shares nodes with other pods, and two numbers per container decide what it gets:
Field Who reads it What it does
requests.cpu the scheduler reserves room on a node; weight under contention
requests.memory the scheduler reserves room on a node
limits.cpu the Linux kernel (CFS) at most this much CPU time per 100 ms, then throttling
limits.memory the Linux kernel (cgroup) whoever needs more is killed: OOMKilled
  • Requests are a promise for scheduling, limits a hard boundary at runtime. Today you see what each of them does to p95 and the error rate when set wrong.
  • Little’s Law from the predecessor course still applies: in progress at once = throughput × time in system. With it, you calculate what the cluster network costs.

Drill 1: The staircase in the cluster

The load script is the same as in the predecessor course: 90 % redirects, 10 % new links, a fixed rate per second. You fetch the codes for the redirects from the database:

# on s1
# Create today's working directory and change into it
mkdir -p ~/sdk/tag02 && cd ~/sdk/tag02
# Write 1000 random short codes from the links table into a file
kubectl -n kurz exec db-1 -c postgres -- psql -d kurz -Atc \
  "select code from links order by random() limit 1000" > codes.txt
# Count lines: there should be 1000
wc -l < codes.txt

Expected:

1000
# on s1
# Create the k6 script: fixed arrival rate, 90 % reads, 10 % writes
cat > mix.js <<'EOF'
import http from "k6/http";
import { check } from "k6";
import { SharedArray } from "k6/data";

const codes = new SharedArray("codes", () => open("./codes.txt").split("\n").filter(Boolean));
const ZIEL = __ENV.ZIEL || "http://localhost:8080";

export const options = {
  scenarios: {
    mix: {
      executor: "constant-arrival-rate",
      rate: Number(__ENV.RATE || 200), timeUnit: "1s",
      duration: __ENV.DAUER || "30s",
      preAllocatedVUs: 50, maxVUs: 500,
    },
  },
  thresholds: { http_req_failed: ["rate<0.01"], http_req_duration: ["p(95)<200"] },
};

export default function () {
  if (Math.random() < 0.9) {
    const code = codes[Math.floor(Math.random() * codes.length)];
    const r = http.get(`${ZIEL}/${code}`, { redirects: 0, tags: { name: "weiterleiten" } });
    check(r, { "302": (x) => x.status === 302 });
  } else {
    const r = http.post(`${ZIEL}/api/links`, JSON.stringify({ url: `https://example.org/neu/${__VU}-${__ITER}` }),
      { headers: { "Content-Type": "application/json" }, tags: { name: "anlegen" } });
    check(r, { "201": (x) => x.status === 201 });
  }
}
EOF

k6 runs on s1, not in the cluster. But s1 is a node, and every node reaches the ClusterIP of a Service, because kube-proxy creates the rules for it on every node. A gateway from outside comes on Day 3.

# on s1
# Remember the ClusterIP of the kurz Service as the target for k6
export ZIEL=http://$(kubectl -n kurz get svc kurz -o jsonpath='{.spec.clusterIP}')
# Print it so you see where the load goes
echo $ZIEL
# On which nodes do the two kurz pods run?
kubectl -n kurz get pods -l app=kurz -o wide --no-headers | awk '{print $1, $7}'
# Four steps of 20 seconds each; grep and sed keep only the important lines
for r in 500 1000 2000 4000; do
  echo "== $r/s"
  RATE=$r DAUER=20s k6 run --quiet mix.js 2>/dev/null \
    | grep -E 'http_req_duration\.|http_req_failed\.|http_reqs\.|dropped_iterations' \
    | sed 's/  */ /g'
done

Expected:

http://10.43.67.150
kurz-68d75bfb98-9qzcw s3
kurz-68d75bfb98-qzbv2 s1
== 500/s
 http_req_duration..............: avg=2.51ms min=754.31µs med=2.01ms max=143.19ms p(90)=3.46ms p(95)=4.34ms
 http_req_failed................: 0.00% 0 out of 10000
 http_reqs......................: 10000 499.951272/s
== 1000/s
 http_req_duration..............: avg=2.92ms min=734.7µs med=2.34ms max=41.84ms p(90)=4.83ms p(95)=6.38ms
 http_req_failed................: 0.00% 0 out of 20001
 http_reqs......................: 20001 999.893254/s
== 2000/s
 http_req_duration..............: avg=20.31ms min=655.57µs med=12.77ms max=385.14ms p(90)=48.08ms p(95)=63.16ms
 http_req_failed................: 0.00% 0 out of 38568
 http_reqs......................: 38568 1925.862523/s
 dropped_iterations.............: 1433 71.55572/s
== 4000/s
 http_req_duration..............: avg=141.61ms min=833.3µs med=121.98ms max=1.06s p(90)=284.09ms p(95)=321.39ms
 http_req_failed................: 5.44% 2783 out of 51157
 http_reqs......................: 51157 2540.867202/s
 dropped_iterations.............: 28606 1420.80355/s

2>/dev/null swallows k6’s warnings, for example that thresholds were crossed. Placed next to the staircase from Day 2 of the predecessor course:

Rate VMs: achieved, p95, errors Cluster: achieved, p95, errors
500/s 500/s, 4.8 ms, 0 500/s, 4.3 ms, 0
1000/s 996/s, 5.3 ms, 0 1000/s, 6.4 ms, 0
2000/s 1988/s, 22 ms, 0 1926/s, 63 ms, 0
4000/s 2635/s, 239 ms, 0 2541/s, 321 ms, 5.4 %

Up to 1000/s, you notice no difference. Above that, the cluster tips over earlier, and at 4000/s errors appear for the first time. On the VMs, the overloaded system was merely slow. Where do the errors come from, and why does the cluster saturate at almost the same number as the VMs, even though two instances are running now?

Caution: Your pods may be on other nodes than here. If one is on s1, it shares the four cores with k6 and the database. The numbers then fluctuate by a few percent. Day 13 shows how to spread pods deliberately.

Save your progress? Sign up for free

Drill 2: Where is the bottleneck?

4000/s once more, and check in the middle of the run who is working:

# on s1
# Start the run in the background, output into a file
(RATE=4000 DAUER=30s k6 run --quiet mix.js > k6-4000.txt 2>&1 &)
# Wait until the full load is applied
sleep 15
# Line 3 of top: how busy is s1 overall?
top -bn1 | sed -n 3p
# The three processes using the most CPU on s1
top -bn1 -o %CPU | sed -n 8,10p | cut -c1-80
# How many connections does each kurz pod hold to the database?
kubectl -n kurz exec db-1 -c postgres -- psql -d kurz -Atc \
  "select client_addr, count(*) from pg_stat_activity where usename = 'kurz' group by 1"
# Wait for the run to finish
sleep 20
# Throughput and error rate from the file
grep -E 'http_req_failed\.|http_reqs\.' k6-4000.txt | sed 's/  */ /g'
# All log lines of both pods from the last minute, counted by frequency
kubectl -n kurz logs -l app=kurz --since=1m --tail=-1 | cut -c21- | sort | uniq -c | sort -rn | head -2

Expected:

%Cpu(s): 56.2 us, 21.9 sy,  0.0 ni,  6.2 id,  0.0 wa,  0.0 hi, 15.6 si,  0.0 st
 155500 ubuntu    20   0 1442784 191452  32584 S 141.2   1.6   0:29.75 k6
 154488 65532     20   0 1272204  29680  10588 S 117.6   0.2   1:01.10 kurz
10.42.0.30|4
10.42.4.14|4
 http_req_failed................: 2.21% 1758 out of 79242
 http_reqs......................: 79242 2617.341071/s
   1701 weiterleiten: context deadline exceeded
     53 weiterleiten: timeout: context deadline exceeded

Three findings:

  1. Four connections per pod. Without a setting, the pgx pool opens at most as many connections as the machine has cores, but at least four. Two pods, so eight connections in total.
  2. The errors are timeouts. On Day 1, you set KURZ_TIMEOUT to 2s. If a request waits longer than two seconds for a free connection, kurz gives up and answers with an error. On the VMs, there was no such time limit, which is why things only got slow there.
  3. kurz with UID 65532 is the pod on s1. You see container processes in top like any other process, only under the UID from the securityContext.

Tip: Without --tail=-1, kubectl -n kurz logs -l app=kurz shows only the last ten lines per pod, even with --since. For counting, always set --tail=-1.

Save your progress? Sign up for free

Drill 3: Little’s Law does the math

Eight connections, a good 2600 requests per second. How long does a request hold its connection?

  W  =  L / λ  =  8 connections / 2617 per s  ≈  3.1 ms

On the VMs, it was 4 connections at 2635/s, so 1.5 ms. In the cluster, a round trip to the database takes twice as long. The path is longer: pod → virtual network (flannel’s VXLAN) → other node → pod, and every connection to the Service db-rw passes through kube-proxy’s rules. Twice as many connections times twice the holding time gives the same throughput as on the VMs. That explains the almost identical saturation.

Proof by cross-check: more connections per pod. pgx reads the pool size from the connection URL. kubectl set env changes the variable in the Deployment and rolls out new pods:

# on s1
# Measure with 8 and 16 connections per pod
for n in 8 16; do
  # Append the pool size to the URL; \$(DB_PASSWORT) stays literal and is substituted in the pod
  kubectl -n kurz set env deploy/kurz \
    KURZ_DB="postgres://kurz:\$(DB_PASSWORT)@db-rw:5432/kurz?pool_max_conns=$n" >/dev/null
  # Wait until the new pods are ready
  kubectl -n kurz rollout status deploy/kurz >/dev/null
  echo "== pool $n je Pod"
  # Again 4000/s for 20 seconds
  RATE=4000 DAUER=20s k6 run --quiet mix.js 2>/dev/null \
    | grep -E 'http_req_duration\.|http_req_failed\.|http_reqs\.|dropped_iterations' | sed 's/  */ /g'
done

Expected:

== pool 8 je Pod
 http_req_duration..............: avg=90.47ms min=776.23µs med=80.51ms max=512.85ms p(90)=170.13ms p(95)=202.56ms
 http_req_failed................: 0.00% 0 out of 63243
 http_reqs......................: 63243 3145.338356/s
 dropped_iterations.............: 16765 833.793424/s
== pool 16 je Pod
 http_req_duration..............: avg=34.44ms min=1ms med=26.68ms max=322.7ms p(90)=70.84ms p(95)=91.12ms
 http_req_failed................: 0.01% 7 out of 69073
 http_reqs......................: 69073 3441.907488/s
 dropped_iterations.............: 10932 544.741544/s

With 8 connections per pod, throughput rises from 2617/s to 3145/s, a fifth more, and the errors disappear. With 16, only another 9 % is added, but p95 drops to 91 ms. The bottleneck has moved on. Where to is shown by top during a run with pool_max_conns=16:

# on s1
# Run in the background, look at the utilization of s1 after 12 seconds
(RATE=4000 DAUER=25s k6 run --quiet mix.js > k6-p16.txt 2>&1 &)
# Wait until the full load is applied
sleep 12
# Overall utilization and the biggest consumer
top -bn1 | sed -n 3p
top -bn1 -o %CPU | sed -n 8p | cut -c1-80

Expected:

%Cpu(s): 68.0 us, 19.6 sy,  0.0 ni,  1.0 id,  0.0 wa,  0.0 hi, 10.3 si,  1.0 st
 137656 ubuntu    20   0 1440808 117000  32848 S 223.1   1.6   0:28.76 k6

1 % idle. s1 carries k6, the database and the k3s server, and k6 alone eats more than two cores. As on the VMs: on s1, measurements up to about 3000/s are meaningful. Above that, you are measuring k6.

For the next days, the pool goes back to the default. The manifest from Day 1 contains the original URL; an apply resets it:

# on s1
# Bring the Deployment back to the state of the Day 1 manifest
kubectl apply -f ~/sdk/tag01/kurz.yaml
# Wait until the rollout is done
kubectl -n kurz rollout status deploy/kurz

Caution: kubectl top is not suitable for measurements during a short run. The metrics-server fetches values only every 15 seconds and averages over that window. In the tests for this chapter, kubectl top still showed 1m in the middle of a run for a pod that top already showed at 117 %. For exact numbers, you use the kubelet’s counters in Drill 8.

Save your progress? Sign up for free

Drill 4: Requests and QoS classes

So far, the pods have neither requests nor limits. What does Kubernetes make of that?

# on s1
# QoS class and node of every pod in the kurz namespace
kubectl -n kurz get pods -o custom-columns=NAME:.metadata.name,QOS:.status.qosClass,NODE:.spec.nodeName
# How much CPU is already committed on s2?
kubectl describe node s2 | grep -A4 'Allocated resources' | tail -1

Expected:

NAME                    QOS          NODE
db-1                    BestEffort   s1
kurz-8df6f8fb-2xvz9     BestEffort   s2
kurz-8df6f8fb-pqb7c     BestEffort   s1
  cpu                0 (0%)    0 (0%)

Every pod gets one of three QoS classes, derived from requests and limits:

Class Condition when the node runs out of memory
BestEffort neither requests nor limits evicted first
Burstable at least one request or limit, but not the same everywhere next
Guaranteed requests = limits for CPU and memory in every container last

BestEffort means: the scheduler places the pods as if they needed nothing. According to the bookkeeping, everything on s2 is still free, even though a kurz runs there that occupies a core under load. On Day 9 (HPA), this becomes a problem, because the HPA calculates in percent of the requests.

You create a copy of the manifest for today and add requests and limits. As a start, you take values often found in templates: a quarter core requested, half a core as the limit:

# on s1
# Copy the Day 1 manifest as a starting point
cd ~/sdk/tag02 && cp ~/sdk/tag01/kurz.yaml kurz.yaml
# Insert the resources block after the line with failureThreshold
sed -i '/failureThreshold: 2/a\        resources:\n          requests:\n            cpu: 250m\n            memory: 32Mi\n          limits:\n            cpu: 500m\n            memory: 64Mi' kurz.yaml
# Show the difference to the Day 1 manifest
diff ~/sdk/tag01/kurz.yaml kurz.yaml

Expected:

57a58,64
>         resources:
>           requests:
>             cpu: 250m
>             memory: 32Mi
>           limits:
>             cpu: 500m
>             memory: 64Mi
# on s1
# Apply the changed manifest
kubectl apply -f kurz.yaml
# Wait until both new pods are ready
kubectl -n kurz rollout status deploy/kurz >/dev/null
# QoS class of the new pods
kubectl -n kurz get pods -l app=kurz -o custom-columns=NAME:.metadata.name,QOS:.status.qosClass,NODE:.spec.nodeName

Expected:

configmap/kurz unchanged
deployment.apps/kurz configured
service/kurz unchanged
NAME                    QOS         NODE
kurz-5665c65b9b-cjtnv   Burstable   s1
kurz-5665c65b9b-kb9h8   Burstable   s2

Save your progress? Sign up for free

Drill 5: Making throttling visible

The kernel implements a CPU limit of 500m like this: in every 100 ms time window, the container may use 50 ms of CPU time, summed across any number of cores. Once the budget is used up, the container stands still until the next window. That is CFS throttling (Completely Fair Scheduler). The kubelet counts the periods and the throttled periods for every container. You read the counters via the API, without logging in to a node:

# on s1
# Function drossel: fetch the two CFS counters for every node with a kurz pod
drossel() {
  # Read the nodes of the kurz pods from the API
  for n in $(kubectl -n kurz get pods -l app=kurz -o jsonpath='{.items[*].spec.nodeName}'); do
    # Fetch the kubelet's metrics on this node via the API server
    kubectl get --raw /api/v1/nodes/$n/proxy/metrics/cadvisor \
      | grep -E '^container_cpu_cfs_(periods|throttled_periods)_total' | grep 'container="kurz"' \
      | sed -E "s/\{.*pod=\"([^\"]*)\".*\} ([0-9]+).*/ \1 \2/"
  done
}
# State before the load
drossel
# Two steps, reading the counters again after each
for r in 1000 2000; do
  echo "== $r/s"
  RATE=$r DAUER=20s k6 run --quiet mix.js 2>/dev/null \
    | grep -E 'http_req_duration\.|http_req_failed\.|http_reqs\.' | sed 's/  */ /g'
  drossel
done

Expected:

container_cpu_cfs_periods_total kurz-5665c65b9b-cjtnv 10
container_cpu_cfs_throttled_periods_total kurz-5665c65b9b-cjtnv 1
container_cpu_cfs_periods_total kurz-5665c65b9b-kb9h8 12
container_cpu_cfs_throttled_periods_total kurz-5665c65b9b-kb9h8 1
== 1000/s
 http_req_duration..............: avg=5.99ms min=760.38µs med=2.55ms max=274.37ms p(90)=12.93ms p(95)=22.72ms
 http_req_failed................: 0.00% 0 out of 19912
 http_reqs......................: 19912 995.41462/s
container_cpu_cfs_periods_total kurz-5665c65b9b-cjtnv 210
container_cpu_cfs_throttled_periods_total kurz-5665c65b9b-cjtnv 90
container_cpu_cfs_periods_total kurz-5665c65b9b-kb9h8 215
container_cpu_cfs_throttled_periods_total kurz-5665c65b9b-kb9h8 137
== 2000/s
 http_req_duration..............: avg=312.58ms min=1.57ms med=316.43ms max=1.57s p(90)=411.28ms p(95)=488.91ms
 http_req_failed................: 68.72% 19420 out of 28256
 http_reqs......................: 28256 1389.6306/s
container_cpu_cfs_periods_total kurz-5665c65b9b-cjtnv 335
container_cpu_cfs_throttled_periods_total kurz-5665c65b9b-cjtnv 208
container_cpu_cfs_periods_total kurz-5665c65b9b-kb9h8 345
container_cpu_cfs_throttled_periods_total kurz-5665c65b9b-kb9h8 261

At 1000/s, one pod was throttled in 89 of 200 periods, the other in 136 of 203. No errors, the rate is held, but p95 rises from 6 to 23 ms. This is what throttling looks like day to day: nobody notices it, only the percentile gets worse. At 2000/s, half a core per pod is no longer enough. Requests pile up, run into the two seconds of KURZ_TIMEOUT, and two thirds of all requests fail. Without a limit, the same step ran without errors in Drill 1.

The counters exist only for containers with a CPU limit. Without a limit, there is nothing to throttle, and container_cpu_cfs_* is missing from the metrics entirely.

Save your progress? Sign up for free

Drill 6: Request yes, CPU limit no

Many teams today set a CPU request but no limit. The request secures the pod its share when the node is full (via the cgroup weight cpu.weight). When the node isn’t full, the pod may take more. For memory, the limit stays, because memory can’t be throttled, only taken away.

# on s1
# Delete the line with the CPU limit from the manifest
sed -i '/cpu: 500m/d' kurz.yaml
# Show the resources block as a check
grep -A6 'resources:' kurz.yaml
# Apply; apply removes fields it set itself that are now missing
kubectl apply -f kurz.yaml
# Wait until the new pods are ready
kubectl -n kurz rollout status deploy/kurz >/dev/null
# What is in the Deployment now?
kubectl -n kurz get deploy kurz -o jsonpath='{.spec.template.spec.containers[0].resources}{"\n"}'
# The same two steps as in Drill 5
for r in 1000 2000; do
  echo "== $r/s"
  RATE=$r DAUER=20s k6 run --quiet mix.js 2>/dev/null \
    | grep -E 'http_req_duration\.|http_req_failed\.|http_reqs\.' | sed 's/  */ /g'
done

Expected:

        resources:
          requests:
            cpu: 250m
            memory: 32Mi
          limits:
            memory: 64Mi
configmap/kurz unchanged
deployment.apps/kurz configured
service/kurz unchanged
{"limits":{"memory":"64Mi"},"requests":{"cpu":"250m","memory":"32Mi"}}
== 1000/s
 http_req_duration..............: avg=3.79ms min=756.21µs med=2.38ms max=167.59ms p(90)=6.22ms p(95)=9.54ms
 http_req_failed................: 0.00% 0 out of 19946
 http_reqs......................: 19946 997.181326/s
== 2000/s
 http_req_duration..............: avg=16.84ms min=620.39µs med=11.17ms max=216.32ms p(90)=39.69ms p(95)=50.07ms
 http_req_failed................: 0.00% 0 out of 39293
 http_reqs......................: 39293 1964.413257/s
CPU limit 500m request 250m only
1000/s p95 23 ms, 0 errors p95 10 ms, 0 errors
2000/s 1390/s, 69 % errors 1964/s, 0 errors, p95 50 ms

The pods stay Burstable. For Guaranteed, requests and limits would have to be equal, so a CPU limit would have to be set too. The Challenge shows when that fits anyway.

Save your progress? Sign up for free

Drill 7: Asking too much

Requests are a reservation. What happens when no node has enough free? You request two and a half cores per pod. s2 and s3 have only two:

# on s1
# Raise the CPU request directly in the Deployment (an experiment, so not in the manifest)
kubectl -n kurz set resources deploy/kurz --requests=cpu=2500m
# Give the scheduler time
sleep 20
# Status and node of all kurz pods
kubectl -n kurz get pods -l app=kurz -o wide | awk '{print $1, $2, $3, $7}'
# The scheduler's reasoning from the last event
kubectl -n kurz get events --field-selector reason=FailedScheduling -o jsonpath='{.items[-1:].message}{"\n"}'
# How much CPU is committed on s1 now?
kubectl describe node s1 | grep -A5 'Allocated resources' | grep cpu

Expected:

deployment.apps/kurz resource requirements updated
NAME READY STATUS NODE
kurz-68d75bfb98-vk7fq 1/1 Running s3
kurz-f95898db8-rnmkr 0/1 Pending <none>
kurz-f95898db8-z9589 1/1 Running s1
0/3 nodes are available: 3 Insufficient cpu. preemption: 0/3 nodes are available: 1 No preemption victims found for incoming pod, 2 Preemption is not helpful for scheduling.
  cpu                2700m (67%)  0 (0%)

A new pod fits only on s1 (four cores); the second finds no room and stays Pending. On s1, 2.7 of 4 cores are now committed, even though the pod is doing nothing at the moment. The rollout gets stuck, and as on Day 1, the old pod on s3 keeps serving. A request is not consumption but room that others lack.

# on s1
# Back to today's manifest
kubectl apply -f kurz.yaml
# Wait until everything is running again
kubectl -n kurz rollout status deploy/kurz

Save your progress? Sign up for free

Drill 8: Too little memory

At idle, kurz needs about 10 MiB. What happens with a limit of 8 MiB?

# on s1
# Set the memory request and limit to 8 MiB
kubectl -n kurz set resources deploy/kurz --requests=memory=8Mi --limits=memory=8Mi
# Wait until the new pods are running
kubectl -n kurz rollout status deploy/kurz >/dev/null
# 2000/s for 20 seconds
RATE=2000 DAUER=20s k6 run --quiet mix.js 2>/dev/null | grep -E 'http_req_failed\.|http_reqs\.' | sed 's/  */ /g'
# Status of the pods
kubectl -n kurz get pods -l app=kurz
# Why was each container last terminated, and with which exit code?
kubectl -n kurz get pods -l app=kurz -o jsonpath='{range .items[*]}{.metadata.name} {.status.containerStatuses[0].lastState.terminated.reason} {.status.containerStatuses[0].lastState.terminated.exitCode}{"\n"}{end}'

Expected:

deployment.apps/kurz resource requirements updated
 http_req_failed................: 89.03% 21827 out of 24514
 http_reqs......................: 24514 1116.410445/s
NAME                  READY   STATUS             RESTARTS     AGE
kurz-f8d6cf55-jwxbx   0/1     CrashLoopBackOff   2 (5s ago)   24s
kurz-f8d6cf55-mxzqx   0/1     CrashLoopBackOff   2 (6s ago)   27s
kurz-f8d6cf55-jwxbx OOMKilled 137
kurz-f8d6cf55-mxzqx OOMKilled 137

At idle, both pods start and become ready; the rollout completes. Only under load does kurz need more memory for connections and buffers, exceeds the 8 MiB, and the kernel kills the process (signal 9, exit code 128 + 9 = 137). Both pods at once, because both get the same load. Then CrashLoopBackOff, 89 % errors. Two replicas don’t protect against a fault that every replica has equally.

# on s1
# Back to today's manifest
kubectl apply -f kurz.yaml
# Wait until everything is running again
kubectl -n kurz rollout status deploy/kurz

Save your progress? Sign up for free

Drill 9: What does a request cost?

For capacity planning on Day 14, you need one number: how many requests can kurz handle with one core? The kubelet counts the CPU time consumed by each container in seconds. Difference before and after a run, divided by the number of requests:

# on s1
# Function cpu: add up the consumed CPU seconds of all kurz containers
cpu() {
  for n in $(kubectl -n kurz get pods -l app=kurz -o jsonpath='{.items[*].spec.nodeName}'); do
    kubectl get --raw /api/v1/nodes/$n/proxy/metrics/cadvisor \
      | grep '^container_cpu_usage_seconds_total' | grep 'container="kurz"' | awk '{print $2}'
  done | paste -sd+ | bc
}
# Two steps, 30 seconds each
for r in 1000 2000; do
  # Counter value before
  vorher=$(cpu)
  echo "== $r/s"
  RATE=$r DAUER=30s k6 run --quiet mix.js 2>/dev/null | grep -E 'http_reqs\.' | sed 's/  */ /g'
  # Counter value after, and the difference
  nachher=$(cpu)
  echo "CPU-Sekunden: $(echo "$nachher - $vorher" | bc)"
done

Expected:

== 1000/s
 http_reqs......................: 29960 998.577835/s
CPU-Sekunden: 25.601599
== 2000/s
 http_reqs......................: 59148 1967.402995/s
CPU-Sekunden: 45.200664
Step Requests CPU seconds Requests per CPU second
1000/s 29,960 25.6 ≈ 1170
2000/s 59,148 45.2 ≈ 1310

About 1200 requests per core, a bit more at higher load, because fixed costs (timers, garbage collector, probes) are spread over more requests. The predecessor course gives 1500 per core on Day 15, measured with a cache and without a network between pods. The two numbers are not a fair comparison; Day 14 makes up for that with Valkey. Remember for today: one core carries a good 1000 requests/s to kurz, and a request of 250m covers 250 to 300 of them.

Tip: Later, Prometheus collects the same counters. container_cpu_usage_seconds_total and container_cpu_cfs_throttled_periods_total are the two metrics by which you recognize throttling in production.

Save your progress? Sign up for free

Exercise: Speed drills

  1. Show the QoS class of both kurz pods. Target time: 1 min
  2. Use kubectl set resources to set a CPU limit of 1, then apply kurz.yaml with kubectl apply. Which CPU limit does the Deployment have now, and what does kubectl diff say? Target time: 3 min
  3. Reliably bring the Deployment to the state of kurz.yaml. Target time: 2 min

Solution

# on s1
# 1: QoS class from the status of each pod
kubectl -n kurz get pods -l app=kurz -o custom-columns=NAME:.metadata.name,QOS:.status.qosClass

Expected:

NAME                    QOS
kurz-68d75bfb98-d7f4w   Burstable
kurz-68d75bfb98-fk2tv   Burstable
# on s1
# 2: Set the CPU limit imperatively
kubectl -n kurz set resources deploy/kurz --limits=cpu=1
# Wait until the rollout is done
kubectl -n kurz rollout status deploy/kurz >/dev/null
# Apply the manifest on top
kubectl apply -f kurz.yaml
# Which limits are in the Deployment now?
kubectl -n kurz get deploy kurz -o jsonpath='{.spec.template.spec.containers[0].resources.limits}{"\n"}'
# Does kubectl see a difference to the manifest? Exit code 0 means: no
kubectl diff -f kurz.yaml; echo "diff: $?"

Expected:

deployment.apps/kurz resource requirements updated
configmap/kurz unchanged
deployment.apps/kurz unchanged
service/kurz unchanged
{"cpu":"1","memory":"64Mi"}
diff: 0

The limit stays, and kubectl diff reports no difference. kubectl apply compares three states: the manifest, the state from the last apply (in the annotation kubectl.kubernetes.io/last-applied-configuration) and the object in the cluster. It only removes fields that were in the manifest at the last apply and are missing now. limits.cpu came from kubectl set and was never in the manifest, so apply leaves it alone.

# on s1
# Who set limits.cpu? managedFields keeps track of every writer
kubectl -n kurz get deploy kurz --show-managed-fields -o yaml \
  | grep -B2 -A12 'manager: kubectl-set' | grep -E 'manager|f:cpu|operation'

Expected:

                    f:cpu: {}
    manager: kubectl-set
    operation: Update

On 3: kubectl replace replaces the whole object with the manifest. --save-config also writes the annotation for later apply calls; without it, the next apply warns:

# on s1
# Replace the objects completely with the manifest and rewrite the apply annotation
kubectl replace --save-config -f kurz.yaml
# Wait until the rollout is done
kubectl -n kurz rollout status deploy/kurz >/dev/null
# The CPU limit is gone
kubectl -n kurz get deploy kurz -o jsonpath='{.spec.template.spec.containers[0].resources}{"\n"}'

Expected:

configmap/kurz replaced
deployment.apps/kurz replaced
service/kurz replaced
{"limits":{"memory":"64Mi"},"requests":{"cpu":"250m","memory":"32Mi"}}

Happened during testing: While writing this chapter, a kubectl replace without --save-config ran in between. Afterwards the annotation was missing, and a following apply that was meant to remove the CPU limit left it in place and only warned: missing the kubectl.kubernetes.io/last-applied-configuration annotation. The measurement ran for two passes with a limit that, according to the manifest, no longer existed. Don’t mix imperative commands and apply, and if you do, first check with kubectl get -o jsonpath what is really in the object.

Save your progress? Sign up for free

Challenge

A platform team mandates: “Every pod in the kurz namespace must be Guaranteed so that it is evicted last when memory runs short.” Find a setting for kurz that fulfils this and does not measurably throttle at 1000/s. Justify the CPU value with a number from this day and prove that no period is throttled.

Hint: Guaranteed means requests = limits for CPU and memory. How much CPU does a pod need on average at 500/s (Drill 9), and how much headroom do spikes need within 100 ms?

Solution

Drill 9: 1000/s on two pods costs a good 0.85 cores, so a good 0.4 per pod on average. But throttling happens in 100 ms windows, and Go spreads work across several threads: within a single window, a pod can briefly occupy two cores. With a limit of 1 (twice the average plus a reserve), there is enough headroom:

# on s1
# Set requests and limits equal: CPU 1, memory 64 MiB
kubectl -n kurz set resources deploy/kurz --requests=cpu=1,memory=64Mi --limits=cpu=1,memory=64Mi
# Wait until the new pods are running
kubectl -n kurz rollout status deploy/kurz >/dev/null
# Check the QoS class
kubectl -n kurz get pods -l app=kurz -o custom-columns=NAME:.metadata.name,QOS:.status.qosClass
# Apply load
RATE=1000 DAUER=20s k6 run --quiet mix.js 2>/dev/null | grep -E 'http_req_duration\.|http_req_failed\.' | sed 's/  */ /g'
# Read the counters from Drill 5 (the function drossel must still be defined in this shell)
drossel

Expected:

deployment.apps/kurz resource requirements updated
NAME                    QOS
kurz-74d4d8b75f-b8mwf   Guaranteed
kurz-74d4d8b75f-qshzv   Guaranteed
 http_req_duration..............: avg=3.16ms min=684.43µs med=2.31ms max=200.68ms p(90)=4.57ms p(95)=6.29ms
 http_req_failed................: 0.00% 0 out of 19953
container_cpu_cfs_periods_total kurz-74d4d8b75f-b8mwf 55
container_cpu_cfs_throttled_periods_total kurz-74d4d8b75f-b8mwf 0
container_cpu_cfs_periods_total kurz-74d4d8b75f-qshzv 89
container_cpu_cfs_throttled_periods_total kurz-74d4d8b75f-qshzv 0

p95 6 ms as without a limit, zero throttled periods. The kubelet updates the counters only every few seconds, which is why fewer than 200 periods appear here; what matters is the zero. The price: every pod reserves a whole core, on s2 and s3 half the node, even at night without load. Guaranteed buys predictability with capacity. Afterwards, back to the manifest: kubectl replace --save-config -f kurz.yaml.

Save your progress? Sign up for free

Checkpoint

# on s1
# Resources in the Deployment: request for CPU and memory, limit only for memory
kubectl -n kurz get deploy kurz -o jsonpath='{.spec.template.spec.containers[0].resources}{"\n"}'
# Both pods ready
kubectl -n kurz get deploy kurz --no-headers | awk '{print $1, $2}'
# Pool back to default: no pool_max_conns in the URL
kubectl -n kurz get deploy kurz -o jsonpath='{.spec.template.spec.containers[0].env[2].value}{"\n"}'
# Script and codes for the next days are present
ls ~/sdk/tag02/mix.js ~/sdk/tag02/codes.txt

Expected:

{"limits":{"memory":"64Mi"},"requests":{"cpu":"250m","memory":"32Mi"}}
kurz 2/2
postgres://kurz:$(DB_PASSWORT)@db-rw:5432/kurz
/home/ubuntu/sdk/tag02/codes.txt
/home/ubuntu/sdk/tag02/mix.js

Interview note

  • CPU limits or not? CPU is compressible: too little CPU makes things slow, not broken. A limit throttles in 100 ms windows, even when the node is empty, and worsens p95 without any average showing it. That’s why many teams set only requests for CPU and both request and limit for memory. Whoever needs limits (tenant isolation, billing, Guaranteed) measures throttling with container_cpu_cfs_throttled_periods_total.
  • Why was my pod killed? OOMKilled with exit code 137 means: memory limit exceeded. Pending with Insufficient cpu means: the requests fit on no node; actual consumption plays no role.
  • Little’s Law in the cluster: connections ÷ throughput = holding time per request. If the holding time rises after the move, the network is what costs, not the application.

Enterprise note

  • A LimitRange in the namespace sets defaults for containers without requests; a ResourceQuota caps the total. With these, a platform team prevents BestEffort pods without checking every manifest. Policy tools such as Kyverno can additionally forbid or mandate CPU limits.
  • You don’t find the right request by guessing, but from measured consumption: the Vertical Pod Autoscaler in recommendation mode, or a p95 of container_cpu_usage_seconds_total over a week.
  • Since Go 1.25, the runtime sets GOMAXPROCS from the cgroup’s CPU limit. Without a limit, it takes all cores of the node. Something similar applies to Java with -XX:+UseContainerSupport. Whoever changes limits thus also changes the behavior of the runtime.

Contents

More