Day 15: Limiting and tuning resources
Goal: limit and weight services with cgroups v2, measure and recognize the effects of a limit, and change a kernel setting so that the effect is measured and the change is documented · Duration: about 2 hours · Prerequisite: Day 0–14
Where we start
stress-ng and fio are installed on perf1
(Day 0), the extra disk is mounted at /daten (Day 9), and
the kernel offers cgroups v2.
# on perf1
cat /sys/fs/cgroup/cgroup.controllers/sys/fs/cgroupis the root of the cgroup tree. The filecgroup.controllerslists the controllers, that is, the resources the kernel can limit here.
Expected:
cpuset cpu io memory hugetlb pids rdma misc
You need cpu, io and memory
today. If one is missing, the system still runs cgroups v1 – Ubuntu
24.04 uses v2 out of the box.
# on perf1
findmnt -n -o SOURCE,TARGET /datenExpected:
/dev/sdb /daten
Introduction
So far you have measured what a resource does: how busy is the CPU, how long does the disk wait, where is the network stuck. Today you turn things around: you give an application less than it wants – on purpose. systemd, Docker, Podman and Kubernetes do exactly that every day with cgroups. If you don’t know their limits, you can spend hours hunting a bottleneck that isn’t one: the CPU is 80 % idle, and the service is still slow because it is only allowed to use 30 %.
In the second part you change kernel settings. There you learn the most important rule of tuning: measure first, then change, then measure again – and often find that the change did nothing.
Today you learn:
- what the cgroup tree looks like and where systemd puts each service,
- to throttle a service with
CPUQuotaand see the throttling incpu.stat, - to decide with
CPUWeightwho gets how much CPU when it is scarce, - to throttle disk access with
IOWriteBandwidthMaxand recognize whyiostatshows nothing while it happens, - to measure a tuning change properly – even when the result is “no effect”,
- to set
sysctlvalues for the moment and permanently.
Background
The picture for today: an apartment building
Think of perf1 as an apartment building. Each apartment is a cgroup, the tenants are processes. Water, electricity and heating are CPU, memory and disk.
cpu.maxis a flow limiter on the tap. In each billing period of 100 ms the apartment may draw at most a fixed amount of water, for example 50 ms. Once that amount is used up, the tap stays closed until the next period starts – even if nobody else in the building needs water right now.cpu.weightis the allocation key. It only applies when water is scarce. Then an apartment with weight 400 gets four times as much as one with weight 100. If there is enough, each gets what it wants.io.maxis a throttle in the pipe to the basement. The basement (the disk) is free, but only a certain amount per second fits through the throttle.sysctlis the house rules. They apply to all apartments, and the caretaker (the kernel) follows them. What is only pinned to the notice board (sysctl -w) is gone after the next reboot; what is in the lease (/etc/sysctl.d/) applies permanently.
The terms
| Term | Meaning | in the picture |
|---|---|---|
| cgroup | group of processes with shared limits and counters | apartment |
| Controller | part of the kernel that distributes a resource (cpu,
io, memory …) |
water, electricity, heating meter |
| Slice, Service, Scope | how systemd names cgroups: slice = group, service = service, scope = a session | floor, apartment, guest room |
cpu.max |
quota: at most Q µs of CPU time per period P µs | flow limiter |
| Throttling | the cgroup has used up its quota and has to wait | tap closed until the next period |
cpu.weight |
share when CPU is scarce, 1 to 10000, default 100 | allocation key |
io.max |
maximum bytes or operations per second per device | throttle to the basement |
sysctl |
kernel settings under /proc/sys |
house rules |
Remember: A quota always throttles, even when the machine is idle. A weight only throttles when things get tight.
How systemd translates the values
You rarely write directly into /sys/fs/cgroup. systemd
translates its settings into cgroup files:
| systemd setting | cgroup file | Example |
|---|---|---|
CPUQuota=50% |
cpu.max |
50000 100000 |
CPUWeight=400 |
cpu.weight |
400 |
IOWriteBandwidthMax=/dev/sdb 20M |
io.max |
8:16 … wbps=20000000 … |
MemoryMax=1G |
memory.max |
1073741824 (Day 7) |
CPUQuota=50% means half a CPU. 200% would
be two whole CPUs.
Drill 1: Reading the cgroup tree
Where you are: on perf1.
What you have afterwards: seen which cgroup your shell and a service are in, and which files a cgroup has.
Step 1 – Where does your shell live? Every process
is in exactly one cgroup. /proc/self is always the process
that is reading it – here cat itself, which runs in the
same cgroup as your shell.
# on perf1
cat /proc/self/cgroupExpected (your session number is different):
0::/user.slice/user-1000.slice/session-303.scope
| Part | Meaning |
|---|---|
0:: |
cgroups v2 – there is only one tree, so always 0 |
user.slice |
everything users start |
user-1000.slice |
the user with UID 1000 (ubuntu) |
session-303.scope |
your SSH session |
Step 2 – The whole tree.
# on perf1
systemd-cgls --no-pagersystemd-cglsshows the cgroup tree with the processes in it.--no-pagerprints everything directly instead of opening it inless.
Expected (excerpt – the beginning at the top, below it the part with nginx):
CGroup /:
-.slice
├─user.slice
│ └─user-1000.slice
│ ├─[email protected] …
│ │ └─init.scope
│ │ ├─17101 /usr/lib/systemd/systemd --user
│ │ └─17103 (sd-pam)
│ └─session-303.scope
│ ├─17190 sshd: ubuntu [priv]
│ ├─17238 sshd: ubuntu@notty
├─init.scope
│ └─1 /sbin/init
└─system.slice
├─systemd-networkd.service
│ └─714 /usr/lib/systemd/systemd-networkd
Three branches: user.slice (sessions),
init.scope (systemd itself) and system.slice
(all services).
Step 3 – An apartment from the inside. nginx has been running as a service since Day 12. Its cgroup is a directory:
# on perf1
ls /sys/fs/cgroup/system.slice/nginx.service/Expected (excerpt – the files you need today):
cgroup.procs
cpu.max
cpu.pressure
cpu.stat
cpu.weight
io.max
io.pressure
io.stat
memory.current
memory.max
memory.pressure
cgroup.procs– the process IDs in this cgroup.cpu.*,io.*,memory.*– limits (max,weight), counters (stat,current) and PSI (pressure, Day 3) for this cgroup only.
Step 4 – What limits does nginx have?
# on perf1
cat /sys/fs/cgroup/system.slice/nginx.service/cpu.maxExpected:
max 100000
max means no quota. 100000 is the period in
microseconds, that is, 100 ms.
# on perf1
cat /sys/fs/cgroup/system.slice/nginx.service/cpu.weightExpected:
100
The default weight. systemd gives the same information in its own words:
# on perf1
systemctl show -p CPUWeight -p CPUQuotaPerSecUSec nginxsystemctl show -p PROPERTYprints individual properties of a service.
Expected:
CPUWeight=[not set]
CPUQuotaPerSecUSec=infinity
[not set] means the default (100) applies.
infinity: no quota.
Remember: Every service is a directory under
/sys/fs/cgroup/system.slice/. There you find its limits, its counters and its own pressure.
Save your progress? Sign up for free
Drill 2: A service with a quota
Where you are: in two terminals on perf1.
What you have afterwards: limited a service to half a CPU and seen the throttling in three places:
cpu.stat,pidstatandcpu.pressure.
Step 1 – Start a limited service.
systemd-run starts a command as a transient
service (transient unit). It gets its own cgroup without you
having to write a unit file.
# on perf1, terminal 1
sudo systemd-run --unit=bremse -p CPUQuota=50% stress-ng --cpu 2 --timeout 60s| Option | Value | Meaning |
|---|---|---|
--unit= |
bremse |
name of the service, so bremse.service (“brake”) |
-p |
CPUQuota=50% |
set a property: at most half a CPU |
| Command | stress-ng --cpu 2 |
two workers that each want to keep one CPU fully busy |
--timeout 60s |
stop by themselves after 60 seconds |
Expected:
Running as unit: bremse.service; invocation ID: b2621e577862463fb0dffde327dfa676
Two workers want 200 % together – 50 % is allowed.
Step 2 – The quota in the cgroup.
# on perf1, terminal 2
cat /sys/fs/cgroup/system.slice/bremse.service/cpu.maxExpected:
50000 100000
50,000 µs of compute time per 100,000 µs period – the flow limiter from the picture.
Step 3 – How often was it throttled? Wait about ten seconds.
# on perf1, terminal 2
cat /sys/fs/cgroup/system.slice/bremse.service/cpu.statExpected:
usage_usec 5598936
user_usec 5496509
system_usec 102427
core_sched.force_idle_usec 0
nr_periods 112
nr_throttled 111
throttled_usec 16409452
nr_bursts 0
burst_usec 0
| Line | Value | Meaning |
|---|---|---|
usage_usec |
5.6 s | CPU time used – exactly half after just over 11 s of runtime |
nr_periods |
112 | the service has had this many 100 ms periods so far |
nr_throttled |
111 | in this many of them the quota was used up early |
throttled_usec |
16.4 s | how long the processes stood still in total (two workers, about 8 s each) |
nr_throttled divided by nr_periods is the
most important number: here 99 % of the periods were
throttled. For a healthy service this share is close to zero.
Step 4 – What pidstat makes of it.
# on perf1, terminal 2
pidstat -u -C stress-ng 5 1-uCPU values,-C stress-ngonly processes whose name containsstress-ng,5 1once over five seconds.
Expected (excerpt – the lines of the two workers):
Average: UID PID %usr %system %guest %wait %CPU CPU Command
Average: 0 17299 24.85 0.00 0.00 75.94 24.85 - stress-ng-cpu
Average: 0 17300 24.85 0.00 0.00 75.94 24.85 - stress-ng-cpu
Each worker gets 25 % – together the allowed 50 %. The interesting
part is %wait: 76 %. You know this column
from Day 4 as the time spent waiting in the run queue. A throttled
process is runnable but not allowed to run – it counts as waiting even
though three CPUs are free.
Step 5 – The pressure in the cgroup.
# on perf1, terminal 2
cat /sys/fs/cgroup/system.slice/bremse.service/cpu.pressureExpected:
some avg10=58.76 avg60=17.06 avg300=3.89 total=11925976
full avg10=58.76 avg60=17.06 avg300=3.89 total=11925976
In the last ten seconds the processes of this cgroup spent 59 % of the time waiting for CPU.
For comparison, the pressure of the whole machine:
# on perf1, terminal 2
cat /proc/pressure/cpuExpected (measured in a second, identical run):
some avg10=47.22 avg60=11.72 avg300=4.80 total=217935250
full avg10=0.00 avg60=0.00 avg300=0.00 total=0
The machine also reports high some pressure, because PSI
counts throttled processes as waiting – even though three CPUs are free.
Who is affected only shows in the pressure of the
service’s cgroup.
After 60 seconds stress-ng ends by itself, and systemd
cleans up the transient service.
Remember: Throttling happens per 100 ms period. You see it in
nr_throttledincpu.stat, in a high%waitinpidstatand in the pressure in the cgroup’scpu.pressure– not in the utilization of the machine.
If it doesn’t work
Failed to start transient service unit: Unit bremse.service was already loaded or has a fragment file.– The service from the last attempt is still running. Wait until it is done, or stop it withsudo systemctl stop bremse.
Save your progress? Sign up for free
Drill 3: Weights – the noisy neighbor
Where you are: in two terminals on perf1.
What you have afterwards: two services fighting over all CPUs, and seen how the weight divides the CPU.
Step 1 – The neighbor. Four workers that want all four CPUs, with the default weight:
# on perf1, terminal 1
sudo systemd-run --unit=nachbar -p CPUWeight=100 stress-ng --cpu 4 --timeout 60sStep 2 – The important service. The same load, but four times as heavy:
# on perf1, terminal 1
sudo systemd-run --unit=wichtig -p CPUWeight=400 stress-ng --cpu 4 --timeout 60sTogether they want 800 %, the machine has 400 %.
(nachbar means “neighbor”, wichtig
“important”.)
Step 3 – Who gets what?
# on perf1, terminal 2
systemd-cgtop -b -n 3 -d 4 --depth=2 -c system.slice| Option | Meaning |
|---|---|
-b |
batch: plain output instead of redrawing the screen |
-n 3 |
three measuring rounds |
-d 4 |
every four seconds |
--depth=2 |
two levels deep into the tree |
-c |
sort by CPU |
system.slice |
only this part of the tree |
Expected (excerpt – the last round; the first round has no CPU values yet):
system.slice 59 399.5 363.0M 0B 92.6K
system.slice/wichtig.service 5 319.9 25.6M - -
system.slice/nachbar.service 5 79.6 25.6M - -
The columns: path, number of tasks, CPU in %, memory, read and write rate.
wichtig gets 320 %, nachbar 80 % – exactly
4 : 1, like the weights 400 : 100. Together that is the 400 % of the
machine.
Step 4 – Alone, everyone is king. Wait until both are done after 60 seconds. Then start only one neighbor with weight 100 (new name so it doesn’t collide with the old one):
# on perf1, terminal 1
sudo systemd-run --unit=nachbar2 -p CPUWeight=100 stress-ng --cpu 4 --timeout 20s# on perf1, terminal 2
systemd-cgtop -b -n 3 -d 4 --depth=2 -c system.sliceExpected (excerpt – the last round):
system.slice 58 399.5 687.0M 0B 1019B
system.slice/nachbar2.service 5 399.4 25.6M - -
Almost 400 % – despite weight 100. The weight only distributes what is scarce.
Remember:
CPUWeightprotects important services from noisy neighbors without wasting CPU.CPUQuotawastes CPU on purpose.
Save your progress? Sign up for free
Drill 4: Throttling the disk
Where you are: in two terminals on perf1.
What you have afterwards: throttled a writer to 20 MB/s and seen that the disk has almost nothing to do meanwhile.
Step 1 – Without a throttle. For comparison, write 500 MiB directly to the disk:
# on perf1, terminal 1
dd if=/dev/zero of=/daten/ohne.bin bs=1M count=500 oflag=directoflag=directbypasses the page cache (Day 8) so that the disk really writes.
Expected (last line):
524288000 bytes (524 MB, 500 MiB) copied, 0.93231 s, 562 MB/s
Step 2 – With a throttle.
IOWriteBandwidthMax needs the device and the rate.
--wait makes systemd-run wait until the
command is done and then show a summary.
# on perf1, terminal 1
sudo systemd-run --unit=schreiber -p "IOWriteBandwidthMax=/dev/sdb 20M" --wait dd if=/dev/zero of=/daten/mit.bin bs=1M count=200 oflag=direct- The quotes keep
/dev/sdb 20Mtogether as one value. 20Mis 20,000,000 bytes per second.
Expected:
Running as unit: schreiber.service; invocation ID: 4579e198571b4718853129462a260e54
Finished with result: success
Main processes terminated with: code=exited/status=0
Service runtime: 10.426s
CPU time consumed: 155ms
Memory peak: 576.0K
Memory swap peak: 0B
200 MiB in 10.4 seconds – 20 MB/s instead of 562 MB/s. The message
from dd itself is in the service’s journal:
# on perf1, terminal 1
sudo journalctl -u schreiber -o cat --no-pagerExpected (excerpt – the last lines):
200+0 records in
200+0 records out
209715200 bytes (210 MB, 200 MiB) copied, 10.396 s, 20.2 MB/s
schreiber.service: Deactivated successfully.
Step 3 – What the disk says about it. Start the
throttled load once more, this time 400 MiB and without
--wait, so you can measure on the side:
# on perf1, terminal 1
sudo systemd-run --unit=schreiber2 -p "IOWriteBandwidthMax=/dev/sdb 20M" dd if=/dev/zero of=/daten/mit.bin bs=1M count=400 oflag=directThat takes just over 20 seconds. In the second terminal:
# on perf1, terminal 2
iostat -x sdb 2 2Expected: two reports. In the second one,
sdb shows among others these values:
| Column | Value | Meaning |
|---|---|---|
w/s |
19.00 | 19 write requests per second |
wkB/s |
19456.00 | 19 MiB/s – the throttle |
w_await |
1.53 | each request takes 1.5 ms – fast |
wareq-sz |
1024.00 | 1 MiB each, as ordered with bs=1M |
%util |
2.30 | the disk is busy 2 % of the time |
By the USE method from Day 1 the disk looks healthy: hardly any
utilization, no waiting, no errors. And yet dd makes no
progress. The waiting happens before the disk, in the
cgroup.
Step 4 – The state of the process.
# on perf1, terminal 2
ps -o pid,stat,cmd -C ddExpected:
PID STAT CMD
17625 Ds /usr/bin/dd if=/dev/zero of=/daten/mit.bin bs=1M count=400 oflag=direct
D means waiting uninterruptibly for I/O (Day 2 and 3).
The process is waiting – just not for the disk.
Step 5 – Where the waiting becomes visible.
# on perf1, terminal 2
cat /sys/fs/cgroup/system.slice/schreiber2.service/io.pressureExpected:
some avg10=43.95 avg60=9.24 avg300=1.98 total=5921120
full avg10=43.95 avg60=9.24 avg300=1.98 total=5921120
The cgroup waits for I/O 44 % of the time. The limit itself is in
io.max:
# on perf1, terminal 2
cat /sys/fs/cgroup/system.slice/schreiber2.service/io.maxExpected:
8:16 rbps=max wbps=20000000 riops=max wiops=max
| Field | Meaning |
|---|---|
8:16 |
device number of sdb (major 8, minor 16), as
lsblk -o NAME,MAJ:MIN shows it |
rbps / wbps |
read / write bytes per second |
riops / wiops |
read / write operations per second |
Step 6 – Clean up.
# on perf1
sudo systemctl stop schreiber2# on perf1
rm /daten/ohne.bin /daten/mit.binRemember: You do not see an I/O throttle at the disk. You see it in the cgroup’s
io.pressureandio.max– and in processes in stateDnext to an idle disk.
Save your progress? Sign up for free
Drill 5: Measuring a tuning change
Where you are: on perf1.
What you have afterwards: measured two I/O schedulers against each other and learned when a difference is a difference.
Linux orders disk requests with an I/O scheduler.
mq-deadline sorts requests and limits waiting times,
none passes them on unchanged. You often read online: “For
SSDs and virtual disks always use none.” Is that true on
perf1?
Step 1 – What is set?
# on perf1
cat /sys/block/sdb/queue/schedulerExpected:
[none] mq-deadline
The active scheduler is in square brackets.
Step 2 – A test file. fio (Day 10) will
read randomly later. That needs a file with real data:
# on perf1
fio --name=vorb --filename=/daten/fio.bin --size=2G --rw=write --bs=1M --direct=1Step 3 – Measurement with none.
# on perf1
fio --name=zufall --filename=/daten/fio.bin --size=2G --rw=randread --bs=4k --iodepth=32 --ioengine=libaio --direct=1 --runtime=20 --time_based --group_reporting| Option | Meaning |
|---|---|
--rw=randread --bs=4k |
read randomly, 4 KiB each |
--iodepth=32 --ioengine=libaio |
up to 32 requests in flight at once – only then does a scheduler have something to order |
--direct=1 |
bypass the page cache |
--runtime=20 --time_based |
exactly 20 seconds |
--group_reporting |
one summary |
Expected (excerpt – the line with
IOPS=):
read: IOPS=3117, BW=12.2MiB/s (12.8MB/s)(248MiB/20341msec)
Step 4 – Switch over. The scheduler is a file in
/sys. tee writes into it with root privileges
(a sudo echo … > would not work, because the redirection
> still runs as a normal user):
# on perf1
echo mq-deadline | sudo tee /sys/block/sdb/queue/schedulerStep 5 – Measurement with mq-deadline.
The same fio command as in step 3.
Expected (excerpt):
read: IOPS=2363, BW=9453KiB/s (9680kB/s)(186MiB/20170msec)
3117 versus 2363 – none is 30 % faster. Done? Not
yet.
Step 6 – Repeat. Switch back and forth twice more and measure each time. In the lab the result was:
| Run | Scheduler | IOPS |
|---|---|---|
| 1 | none | 3117 |
| 2 | mq-deadline | 2363 |
| 3 | none | 2061 |
| 4 | mq-deadline | 1920 |
| 5 | none | 1740 |
| 6 | mq-deadline | 1609 |
Between two runs with the same scheduler (3117 → 2061 → 1740) there is more difference than between the two schedulers within a pair (about 5–10 %). perf1’s virtual disk sits on shared storage of the hypervisor whose state changes during the measurement. The truth is: on this system the scheduler makes no reliable difference – the noise is larger than the effect.
Step 7 – Back to the starting state.
# on perf1
echo none | sudo tee /sys/block/sdb/queue/scheduler# on perf1
rm /daten/fio.binRemember: A tuning change is only a gain if the difference is larger than the spread between repetitions. Always measure at least three times, alternating, and write down every value.
Save your progress? Sign up for free
Drill 6: sysctl for now and for good
Where you are: on perf1.
What you have afterwards: changed a kernel value at runtime, recorded it permanently in a file and seen in which order Linux reads such files.
The example is vm.swappiness from Day 7: how willingly
the kernel swaps out anonymous memory instead of freeing page cache (0
to 200, default 60).
Step 1 – Read the value.
# on perf1
sysctl vm.swappinessExpected:
vm.swappiness = 60
sysctl reads the file
/proc/sys/vm/swappiness; the dot in the name stands for the
slash.
Step 2 – Change it for the moment (the “notice board” from the picture):
# on perf1
sudo sysctl -w vm.swappiness=10-wwrites the value.
Expected:
vm.swappiness = 10
This applies immediately – and only until the next reboot.
Step 3 – Record it permanently (the “lease”). Create your own file. The number at the front of the name determines the order, the comment tells the next admin why:
# on perf1
sudo nano /etc/sysctl.d/90-tag15.conf# Tag 15: weniger früh auslagern (Messung siehe Kapitel)
vm.swappiness = 30The comment in the file says, in German, “swap out less early (measurement see chapter)”.
Step 4 – Reread all files.
# on perf1
sudo sysctl --system--systemreads all configuration files in their fixed order and reports each one.
Expected (excerpt – the lines in the middle; which files come before and after depends on the system):
* Applying /usr/lib/sysctl.d/50-pid-max.conf ...
* Applying /etc/sysctl.d/90-tag15.conf ...
* Applying /etc/sysctl.d/99-cloudimg-ipv6.conf ...
* Applying /usr/lib/sysctl.d/99-protect-links.conf ...
* Applying /etc/sysctl.d/99-sysctl.conf ...
The files from /usr/lib/sysctl.d/ (from packages) and
/etc/sysctl.d/ (from the admin) are sorted together by
name. If a value is in several files, the last one
wins. 90- comes before the 99- files
– if one of them also sets vm.swappiness, its value
applies.
# on perf1
sysctl vm.swappinessExpected:
vm.swappiness = 30
Step 5 – Proof without a reboot. At boot, the
service systemd-sysctl reads the files. Change the value on
purpose and let the service run again:
# on perf1
sudo sysctl -w vm.swappiness=99# on perf1
sudo systemctl restart systemd-sysctl# on perf1
sysctl vm.swappinessExpected:
vm.swappiness = 30
The value from the file is back – just like after a reboot.
Step 6 – Clean up. The setting was only an exercise:
# on perf1
sudo rm /etc/sysctl.d/90-tag15.conf# on perf1
sudo sysctl -w vm.swappiness=60Remember:
sysctl -wis the notice board,/etc/sysctl.d/NN-name.confthe lease. Every file gets a comment with the reason, and for the same key the file read last wins.
Save your progress? Sign up for free
Diagnosis task
Time limit: 20 minutes.
A computing service on perf1 answers only about 19 requests per
second, and each takes almost 400 ms. The team says: “That’s as fast as
it gets – top shows the machine has almost nothing to do.
The Python code is just slow.”
Setup. Create the service:
# on perf1
mkdir -p ~/tag15# on perf1
nano ~/tag15/rechner.py# rechner.py – kleiner HTTP-Dienst für Tag 15: jede Anfrage rechnet etwa 5 ms
import hashlib
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
wert = b"tag15"
for _ in range(4000):
wert = hashlib.sha256(wert).digest()
antwort = wert.hex().encode() + b"\n"
self.send_response(200)
self.send_header("Content-Length", str(len(antwort)))
self.end_headers()
self.wfile.write(antwort)
def log_message(self, *args):
pass
ThreadingHTTPServer(("", 8082), Handler).serve_forever()And the unit file for systemd:
# on perf1
sudo nano /etc/systemd/system/rechner.service[Unit]
Description=Rechner (Tag 15)
[Service]
ExecStart=/usr/bin/python3 /home/ubuntu/tag15/rechner.py
User=ubuntu
CPUQuota=30%
[Install]
WantedBy=multi-user.target# on perf1
sudo systemctl daemon-reload# on perf1
sudo systemctl start rechnerThe load comes from last1, with wrk
from Day 12: two threads, eight connections, 20 seconds.
# on last1
wrk -t2 -c8 -d20s --latency http://perf1:8082/Expected (excerpt):
Latency 366.43ms 93.11ms 788.93ms 74.28%
50% 384.70ms
99% 685.52ms
Requests/sec: 19.00
Your task: Find out whether the team is right. Restart the load for each measurement.
Solution path
1. The machine – USE for the CPU. While the load is running:
# on perf1
mpstat 5 1Expected (excerpt – the Average
line):
Average: all 6.21 0.00 0.65 0.00 0.00 0.99 1.09 0.00 0.00 91.05
91 % %idle. The team is right: the machine is bored.
2. The process.
systemctl show -p MainPID --value prints only the
number:
# on perf1
systemctl show -p MainPID --value rechnerExpected: the PID, 18259 in the lab.
Use yours below.
# on perf1
pidstat -u -p 18259 5 1Expected (excerpt):
Average: 1000 18259 27.00 3.00 0.00 24.20 30.00 - python3
%CPU 30.00 – suspiciously round. And %wait
24 % on a machine that is 91 % idle. You know this from Drill 2.
3. The cgroup.
# on perf1
cat /sys/fs/cgroup/system.slice/rechner.service/cpu.statExpected (excerpt):
nr_periods 90
nr_throttled 81
throttled_usec 8866129
Throttled in 81 of 90 periods. The cause is in the unit:
# on perf1
systemctl show -p CPUQuotaPerSecUSec rechnerExpected:
CPUQuotaPerSecUSec=300ms
300 ms of CPU per second – CPUQuota=30%. Someone limited
the service “to be safe”.
4. Put it to the test – without a restart.
systemctl set-property --runtime changes a limit on the
running service, only until the next restart. An empty value removes the
quota:
# on perf1
sudo systemctl set-property --runtime rechner CPUQuota=# on perf1
cat /sys/fs/cgroup/system.slice/rechner.service/cpu.maxExpected:
max 100000
Load once more:
# on last1
wrk -t2 -c8 -d20s --latency http://perf1:8082/Expected (excerpt):
Latency 88.18ms 23.13ms 320.47ms 75.59%
50% 86.24ms
99% 156.35ms
Requests/sec: 73.57
Almost four times as many requests, median 86 instead of 385 ms. And
pidstat now shows:
Average: 1000 18259 96.20 9.80 0.00 0.20 106.00 - python3
%wait has dropped to 0.2 %. At about 100 % CPU, Python
really is the limit now: because of the Global Interpreter
Lock, only one thread computes at a time. That would be the next
lever – but only now.
5. Fix it properly. Undo the runtime change and edit the unit file:
# on perf1
sudo systemctl revert rechnerExpected:
Removed "/run/systemd/system.control/rechner.service.d/50-CPUQuota.conf".
Removed "/run/systemd/system.control/rechner.service.d".
So set-property had created a small extra file (drop-in)
under /run. revert deletes it.
# on perf1
sudo nano /etc/systemd/system/rechner.service[Unit]
Description=Rechner (Tag 15)
[Service]
ExecStart=/usr/bin/python3 /home/ubuntu/tag15/rechner.py
User=ubuntu
[Install]
WantedBy=multi-user.targetThe line CPUQuota=30% is removed.
# on perf1
sudo systemctl daemon-reload# on perf1
sudo systemctl restart rechner# on perf1
systemctl show -p CPUQuotaPerSecUSec rechnerExpected:
CPUQuotaPerSecUSec=infinity
The lesson: An idle machine and a slow service are
not mutually exclusive. Before you suspect the code, look into the
service’s cgroup: nr_throttled in
cpu.stat.
Challenge
Limit the running service rechner to half a CPU
without a restart. Show that the limit takes effect and
which file systemd uses to record it. Then remove the limit again.
Solution path:
# on perf1
sudo systemctl set-property --runtime rechner CPUQuota=50%# on perf1
cat /sys/fs/cgroup/system.slice/rechner.service/cpu.maxExpected:
50000 100000
# on perf1
systemctl status rechner --no-pagerExpected (excerpt – the first lines):
● rechner.service - Rechner (Tag 15)
Loaded: loaded (/etc/systemd/system/rechner.service; disabled; preset: enabled)
Drop-In: /run/systemd/system.control/rechner.service.d
└─50-CPUQuota.conf
Active: active (running) since Mon 2026-11-30 22:02:26 UTC; 6s ago
The Drop-In line reveals every runtime change. Without
--runtime the file ends up under
/etc/systemd/system.control/ and survives a reboot – a
popular reason for “we never set that”.
# on perf1
sudo systemctl revert rechner# on perf1
cat /sys/fs/cgroup/system.slice/rechner.service/cpu.maxExpected:
max 100000
Save your progress? Sign up for free
Checkpoint
Stop the service:
# on perf1
sudo systemctl stop rechner# on perf1
systemctl is-active rechnerExpected: inactive.
# on perf1
cat /sys/block/sdb/queue/schedulerExpected: [none] mq-deadline – as before the
chapter.
# on perf1
sysctl vm.swappinessExpected: vm.swappiness = 60.
# on perf1
ls /datenExpected: no test files from today (ohne.bin,
mit.bin, fio.bin).
Test yourself
- A service has
CPUQuota=50%, the machine is otherwise idle. How much CPU does it get? - Two services have
CPUWeight=100andCPUWeight=300and both want all CPUs. How do they share four CPUs? And how much does the first get when the second is idle? - In which three places do you recognize that a service is being throttled by its CPU quota?
iostatshows%util2 %, and yet a process hangs in stateD. What do you think of?- A tuning change gives 30 % in the first attempt. What do you do before you roll it out?
- Where do you store a sysctl setting permanently, and which file wins if two set the same key?
Answers:
- Half a CPU – never more, not even on an idle machine.
- 100 % and 300 %. If the second is idle, the first gets all 400 %.
nr_throttledrises incpu.stat,pidstatshows a high%wait, the cgroup’scpu.pressureis high – while the machine is largely idle.- A throttle in the cgroup (
io.max); check with the service’sio.pressureandio.max. - Measure several times, alternating, and check whether the difference is larger than the spread.
- In
/etc/sysctl.d/NN-name.confwith a comment. The file read last wins – sorted by name.
Interview Note
“A container is slow, but the host has CPU to spare. What do you
check?” – The container’s CPU limit: in Kubernetes,
limits.cpu becomes cpu.max. I look at
nr_throttled relative to nr_periods in
cpu.stat and at the cgroup’s cpu.pressure. If
you can explain that the quota applies per 100 ms period and that
therefore several threads in particular use up a quota
in a few milliseconds and then stand still for the rest of the period,
you have understood the topic.
Enterprise Note
- Kubernetes:
requests.cpubecomescpu.weight,limits.cpubecomescpu.max. Many teams deliberately leave out CPU limits for latency-critical services and rely on requests (weights), because throttling ruins response times. Memory limits, on the other hand, remain mandatory. - Monitoring: cAdvisor and the kubelet provide
container_cpu_cfs_throttled_periods_total; an alert on the share of throttled periods finds wrong limits before users feel them. - Tuning: Every change to
sysctl, schedulers or limits belongs in configuration management (Ansible, Puppet) with a measurement, date and reason. Tools liketunedcome with ready-made profiles – those, too, must be measured on your own system.
Summary
- cgroups v2: one tree under
/sys/fs/cgroup; systemd puts services insystem.sliceand sessions inuser.slice. Every cgroup has its own limits, counters and PSI. CPUQuota→cpu.max: always throttles. Recognizable bynr_throttledincpu.stat,%waitinpidstatand the cgroup’scpu.pressure. In the lab: 99 % throttled periods at 50 %.CPUWeight→cpu.weight: only distributes when CPU is scarce. 400 : 100 gave 320 % : 80 %.IOWriteBandwidthMax→io.max: 20 MB/s instead of 562 MB/s, disk 2 % utilized, process in stateD, visible inio.pressure.- Measuring tuning: The scheduler comparison drowned in noise – measure several times, alternating.
- sysctl:
-wfor now,/etc/sysctl.d/for good; the file read last wins. - Diagnosis:
CPUQuota=30%turned 74 requests per second into 19, at 91 % idle.
Commands at a glance
| Command | What it does | Parameters |
|---|---|---|
cat /proc/self/cgroup |
cgroup of the current process | – |
systemd-cgls --no-pager |
cgroup tree with processes | – |
systemd-cgtop -b -n N -d S -c |
CPU, memory, I/O per cgroup | -c sort by CPU |
systemd-run --unit=NAME -p EIG=WERT BEFEHL |
start a command as a transient service with limits | --wait wait and show a summary |
systemctl show -p EIG DIENST |
property of a service | --value only the value |
systemctl set-property --runtime DIENST EIG=WERT |
change a limit on the running service | without --runtime permanent |
systemctl revert DIENST |
remove runtime and drop-in changes | – |
cat …/cpu.stat, cpu.max,
cpu.pressure |
throttling, quota, pressure of a cgroup | – |
cat …/io.max, io.pressure |
I/O throttle and pressure of a cgroup | – |
echo SCHED \| sudo tee /sys/block/DEV/queue/scheduler |
switch the I/O scheduler | none, mq-deadline |
sysctl NAME /
sudo sysctl -w NAME=WERT |
read / set a kernel value | – |
sudo sysctl --system |
reread all sysctl files | – |
(In the placeholders, EIG=WERT is PROPERTY=VALUE,
DIENST is SERVICE and BEFEHL is COMMAND.)