Day 8: File systems – cache, write-back, fsync and latency per operation
Goal: understand the layer between program and disk, measure the hit rate of the page cache, observe delayed write-back, see file system latency per operation and find an application that slows itself down with
fsync· Duration: about 3 hours · Prerequisite: Day 0–7
Where we start
perf1 is quiet, /daten is mounted, swap is active, and
no test service is running. You check this with three individual
commands.
/daten is mounted.
# on perf1
findmnt -no SOURCE,OPTIONS /datenfindmntshows mounted file systems.-nleaves out the header line,-o SOURCE,OPTIONSselects the columns device and mount options.
Expected:
/dev/sdb rw,noatime
Swap is active.
# on perf1
swapon --showExpected:
NAME TYPE SIZE USED PRIO
/swapfile file 4G 0B -2
One line for /swapfile (Day 7) below the header
line.
No service has failed.
# on perf1
systemctl list-units --failed --no-legendExpected: no output.
Introduction
When a program reads or writes a file, it does not talk to the disk but to the file system. In between there are layers that change almost everything: the page cache answers reads from memory, writes land only in memory at first, and the file system keeps a journal that has to be waited for in some operations.
That is why the question “How fast is my disk?” is often the wrong
one for applications. The right one is: How long does my
application wait for the file system? A read from the cache
takes microseconds, one from disk milliseconds. A normal write is fast,
an fsync – “write everything to disk now for real and let
me know” – can take a thousand times longer.
Today you measure this layer directly: the hit rate of the cache, the write-back of modified pages, the latency of each file system operation individually, and which files a program opens. Along the way you run into a problem that is common in real life: a measuring tool that silently delivers wrong numbers on a new kernel.
Today you learn:
- how VFS, page cache, file system and journal work together,
- to measure the hit rate of the page cache – and why
cachestatonly shows zeros on Ubuntu 24.04, - to understand delayed write-back and the limits
dirty_ratioanddirty_background_ratio, - what
fsynccosts, - to measure latency per file system operation with
ext4distandext4slower, - to see with
filetopandopensnoopwhich files a program reads, writes and opens, - to find and speed up an application that calls
fsyncafter every line.
Background
The picture for today: desk, out tray and archive
Picture an office. On your desk are the files you are working on right now – that is the page cache. In the archive in the basement everything is kept permanently – that is the disk.
- Reading: If the file is on the desk, you grab it immediately (hit). Otherwise you have to go to the basement (miss) – that takes a while.
- Writing: You put the changed sheet in the out tray “to the archive” and keep working. The sheets in the tray are the dirty pages.
- Write-back: A messenger empties
the tray regularly and takes the sheets to the basement. If the tray
gets too full, you have to go down yourself and wait
(
dirty_ratio). fsync: You go down to the basement with the messenger and wait until the archive signs for the delivery. Safe – but a trip to the basement every time.- Journal: The archive’s register. Before anything counts as delivered, it has to be entered there. There is only one register per archive – everyone queues in front of it.
The terms
| Term | Meaning | in the picture |
|---|---|---|
| VFS | common interface of all file systems in the kernel | the office door every job comes through |
| Page cache | file contents in main memory | desk |
| Hit / miss | page already in the cache / must be read | file is there / trip to the basement |
| Dirty page | changed, but not yet on disk | sheet in the out tray |
| Write-back | kernel threads write dirty pages later | the messenger |
fsync() |
waits until a file’s data is safely on disk | go down with it and have it signed for |
| Journal | ext4’s log of metadata changes (jbd2) |
register |
Remember: Reading from the cache and buffered writing cost microseconds. Every trip to the basement – a miss or an
fsync– costs milliseconds.
The layers
A program’s read() or write() passes
through several layers in the kernel:
- VFS (Virtual File System): the common interface of all file systems. It accepts the system call, checks permissions and passes it on to the right file system.
- Page cache: If the requested page is already in memory, the read ends here – a hit. Otherwise a miss, and the file system has to read.
- File system (here ext4): knows where a file’s data lies on disk and manages metadata such as directories, sizes and timestamps.
- Block layer and device: the actual disk – the topic of Day 9.
A tool that measures at layer 1 or 3 sees what the application
experiences. One at layer 4 (iostat) only sees what arrives
at the disk – and that is often much less and grouped differently.
Write-back
A write() only copies the data into the page cache,
marks the pages as dirty and returns immediately.
Kernel threads write them to disk later in batches. Four settings
control this:
| Setting | Default | Meaning |
|---|---|---|
vm.dirty_background_ratio |
10 | From this share of dirty pages (in % of available memory), write-back starts in the background. |
vm.dirty_ratio |
20 | From this share, a writing process has to wait itself until pages have been written back. |
vm.dirty_expire_centisecs |
3000 | Dirty pages older than 30 seconds are written in any case. |
vm.dirty_writeback_centisecs |
500 | Every 5 seconds the kernel threads check what needs to be done. |
That makes writing fast but has a price: if the machine goes down, the dirty pages are lost.
fsync and the journal
Programs that have to store data safely – databases,
mail servers, package managers – call
fsync(). The call only returns when all
dirty pages of the file and the necessary metadata are
on disk and the disk has confirmed that they are not just in its own
cache (flush). ext4 keeps its journal for
this: a log of metadata changes that has to be written first on
fsync. You know the kernel thread for it from Day 2:
jbd2.
An fsync therefore costs at least one complete write and
flush round trip to the disk – a few hundred microseconds on a good SSD,
rather milliseconds on a virtual disk, ten milliseconds on a hard disk.
Whoever calls fsync after every small write is limited to a
few hundred operations per second, no matter how fast the disk’s
throughput is.
Tools for this layer
The bcc tools have their own family for file systems. Today you use:
ext4dist– latency histograms for the ext4 operationsread,write,openandfsync.ext4slower– every single ext4 operation that takes longer than a threshold, with file.filetop– which files are read and written how much, liketop.opensnoop– everyopen()with file and result.cachestat– hit rate of the page cache. In theory.
For other file systems there are siblings (xfsdist,
btrfsslower, nfsdist …).
Drill 1: The hit rate of the page cache
Where you are: on perf1, two terminals.
What you have afterwards: seen that a standard tool fails on this kernel, and measured the hit rate with a bpftrace one-liner instead.
Step 1 – A test file. One gigabyte of random data so that you have something to read:
# on perf1, terminal 1
dd if=/dev/urandom of=/daten/daten.bin bs=1M count=1024 status=noneif=/dev/urandomreads random data,of=writes to the file,bs=1M count=1024= 1,024 times 1 MiB,status=nonesuppresses the status message.
Step 2 – start cachestat.
# on perf1, terminal 1
sudo cachestat-bpfcc 1 5cachestat-bpfcc 1 5prints five times at one-second intervals how many page accesses were hits and misses.
Step 3 – read while it measures. As soon as
cachestat shows its first line, read the file six times in
a row in the second terminal. cat accepts several files –
here the same one six times:
# on perf1, terminal 2
cat /daten/daten.bin /daten/daten.bin /daten/daten.bin /daten/daten.bin /daten/daten.bin /daten/daten.bin > /dev/null> /dev/nullthrows away what is read – it is only about reading.
Expected (terminal 1):
HITS MISSES DIRTIES HITRATIO BUFFERS_MB CACHED_MB
2 0 0 100.00% 14 1334
0 0 0 0.00% 14 1334
0 0 0 0.00% 14 1334
0 0 0 0.00% 14 1334
0 0 13 0.00% 14 1334
While one gigabyte after another is being read from the cache,
cachestat counts zero accesses. The tool
does not measure, it stays silent.
Step 4 – where does cachestat listen?
cachestat attaches to certain kernel functions. Which ones
is in its source code. grep -n searches for a word in a
file and gives the line number:
# on perf1
grep -n "attach_kprobe" /usr/sbin/cachestat-bpfccExpected:
121:b.attach_kprobe(event="add_to_page_cache_lru", fn_name="do_count_apcl")
122:b.attach_kprobe(event="mark_page_accessed", fn_name="do_count_mpa")
131: b.attach_kprobe(event="folio_account_dirtied", fn_name="do_count_apd")
133: b.attach_kprobe(event="account_page_dirtied", fn_name="do_count_apd")
141:b.attach_kprobe(event="mark_buffer_dirty", fn_name="do_count_mbd")
The first two matter: cachestat counts accesses at
mark_page_accessed and new pages in the cache at
add_to_page_cache_lru.
Step 5 – which functions exist in the running
kernel? /proc/kallsyms lists all kernel functions.
grep -E searches for four names at once (|
means “or”, $ “at the end of the line”):
# on perf1
sudo grep -E " (mark_page_accessed|folio_mark_accessed|add_to_page_cache_lru|filemap_add_folio)$" /proc/kallsymsExpected:
ffffffffb93ca970 T filemap_add_folio
ffffffffb93dc170 T mark_page_accessed
ffffffffb93dc480 T add_to_page_cache_lru
ffffffffb93e1360 T folio_mark_accessed
The old functions still exist – but the kernel hardly uses them
anymore. Since kernel 5.16, memory management works with
folios (groups of pages), and the actual work is done
by folio_mark_accessed and filemap_add_folio.
cachestat in the version shipped with Ubuntu 24.04 (bcc
0.29) listens in the wrong place.
This is an important lesson about eBPF tools: they attach to internal kernel functions, and those change. A tool that shows zero can be broken. Test new tools against a load you know – as here.
Step 6 – empty the cache. So that the first read really comes from disk. First write back everything dirty:
# on perf1
syncThen discard the page cache. tee writes into the kernel
file with root rights (a sudo echo 3 > … would not work
because the redirection > runs as a normal user);
> /dev/null swallows the echo of tee:
# on perf1
echo 3 | sudo tee /proc/sys/vm/drop_caches > /dev/nullStep 7 – measure it yourself. With bpftrace you count the right functions. The program is a single command over several lines:
# on perf1, terminal 1
sudo timeout 12 bpftrace -e '
kprobe:folio_mark_accessed { @zugriffe = count(); }
kprobe:filemap_add_folio { @neu_im_cache = count(); }
interval:s:2 { print(@zugriffe); print(@neu_im_cache); clear(@zugriffe); clear(@neu_im_cache); }'kprobe:FUNKTION { … }runs the block on every call of the kernel function (FUNKTION= function).@zugriffe = count()counts the calls in a map named@zugriffe(“accesses”).interval:s:2fires every two seconds: print the values, then reset them withclear.timeout 12ends bpftrace after twelve seconds. You learn the bpftrace language on Day 14.
As soon as Attaching 3 probes... appears, read the file
once in the second terminal (cold cache), wait a moment and read it a
second time (warm cache):
# on perf1, terminal 2
cat /daten/daten.bin > /dev/null# on perf1, terminal 2
cat /daten/daten.bin > /dev/nullExpected (terminal 1, excerpt – the first eight lines; how the numbers are distributed over the two-second sections depends on when you type):
Attaching 3 probes...
@zugriffe: 119931
@neu_im_cache: 118663
@zugriffe: 110059
@neu_im_cache: 107607
@zugriffe: 478
@neu_im_cache: 85
@zugriffe: 263673
@neu_im_cache: 0
- First read, cold cache: it took four seconds in the lab and is
therefore spread over two sections (the third is a small remainder).
Together 230,468 accesses, of which 226,355 came into the cache
new (
neu im Cache= “new in cache”) – almost every access was a miss. - Second read: 263,673 accesses, 0 new pages. Hit rate 100 %.
- What bpftrace still prints after
timeoutends (the empty maps) you can ignore.
That is exactly what cachestat should have shown.
Remember: A tool that shows zeros can be broken. Test it against a load whose result you know – before you trust it in an emergency.
Save your progress? Sign up for free
Drill 2: Watching write-back
Where you are: on perf1.
What you have afterwards: seen how fast buffered writing is, how many dirty pages it creates and what
syncstill has to do.
Step 1 – the thresholds. cat can print
several files one after the other:
# on perf1
cat /proc/sys/vm/dirty_ratio /proc/sys/vm/dirty_background_ratioExpected:
20
10
From 10 % dirty pages the messenger starts, from 20 % the writer has to go down to the basement themselves.
Step 2 – write two GiB.
# on perf1
dd if=/dev/zero of=/daten/schreib.bin bs=1M count=2048 status=progressstatus=progressmakesddprint the data rate during the run and at the end.
Expected (excerpt – the last line):
2147483648 bytes (2.1 GB, 2.0 GiB) copied, 6.72614 s, 319 MB/s
Step 3 – what is still in the out tray?
grep -E with ^ (beginning of the line) finds
the two lines in /proc/meminfo:
# on perf1
grep -E "^(Dirty|Writeback):" /proc/meminfoDirtyare dirty pages,Writebackpages that are on their way to the disk right now.
Expected:
Dirty: 258052 kB
Writeback: 0 kB
Step 4 – force the rest. sync writes
back everything dirty and waits for it; time measures how
long that takes:
# on perf1
time syncExpected:
real 0m0.306s
user 0m0.002s
sys 0m0.008s
Step 5 – and afterwards?
# on perf1
grep -E "^(Dirty|Writeback):" /proc/meminfoExpected:
Dirty: 4 kB
Writeback: 84 kB
With eleven GiB of available memory, the background threshold (10 %)
is a good one GiB. The kernel had already been writing back in the
background during the write; at the end 252 MiB were still dirty, and
sync needed a third of a second for the rest. With a slower
disk or larger amounts of data, sync – and every program
that hits dirty_ratio – can wait for seconds. That is a
common cause of “sudden hangs” during large copy operations.
Step 6 – clean up.
# on perf1
rm -f /daten/schreib.binRemember:
write()only puts things in the out tray. The waiting happens later – by the messenger in the background, by the writer itself fromdirty_ratio, or by anyone who callssync/fsync.
Save your progress? Sign up for free
Drill 3: Latency per operation
Where you are: on perf1, two terminals.
What you have afterwards: histograms of the ext4 latencies, a list of individual slow operations and a ranking of the files.
Step 1 – a mixed load. In the first terminal you
start a load of 70 % reading and 30 % writing, with an
fsync after every 32 writes. First change to the
directory:
# on perf1, terminal 1
cd /daten# on perf1, terminal 1
fio --name=misch --directory=/daten --size=256M --rw=randrw --rwmixread=70 --bs=8k \
--ioengine=psync --fsync=32 --numjobs=2 --runtime=60 --time_based| Option | Meaning |
|---|---|
--name=misch --directory=/daten --size=256M |
name of the run (misch = “mixed”); one 256 MiB file per
process in /daten |
--rw=randrw --rwmixread=70 |
random reading and writing, 70 % reading |
--bs=8k |
8 KiB per access, a typical database page size |
--ioengine=psync |
ordinary system calls pread/pwrite, like
most applications |
--fsync=32 |
fsync after every 32 writes |
--numjobs=2 |
two processes at the same time |
--runtime=60 --time_based |
exactly 60 seconds |
This time without --direct=1: the
accesses go through the page cache.
Step 2 – histograms. In the second terminal, while fio is running:
# on perf1, terminal 2
sudo ext4dist-bpfcc 10 110 1: measure for ten seconds, print once.
Expected (shortened by empty lines):
operation = write
usecs : count distribution
4 -> 7 : 23 | |
8 -> 15 : 418 |**** |
16 -> 31 : 1554 |**************** |
32 -> 63 : 3705 |****************************************|
64 -> 127 : 3469 |************************************* |
128 -> 255 : 677 |******* |
256 -> 511 : 111 |* |
512 -> 1023 : 27 | |
1024 -> 2047 : 2 | |
2048 -> 4095 : 1 | |
operation = read
usecs : count distribution
128 -> 255 : 1424 |*** |
256 -> 511 : 15888 |****************************************|
512 -> 1023 : 4946 |************ |
1024 -> 2047 : 740 |* |
2048 -> 4095 : 142 | |
4096 -> 8191 : 21 | |
operation = fsync
usecs : count distribution
64 -> 127 : 17 |** |
128 -> 255 : 336 |****************************************|
256 -> 511 : 314 |************************************* |
512 -> 1023 : 59 |******* |
1024 -> 2047 : 19 |** |
2048 -> 4095 : 224 |************************** |
4096 -> 8191 : 80 |********* |
8192 -> 16383 : 3 | |
How to read a histogram: on the left is a range in microseconds, on the right how many operations took that long; the asterisks show this as a bar.
| Operation | Main range | Interpretation |
|---|---|---|
write |
32–127 µs | writing only lands in the page cache – fast |
read |
256–511 µs | the files were not yet in the cache, ext4 had to read from disk; with a warm cache it would be a few µs |
fsync |
two peaks: around 200 µs and around 3 ms | little in the tray → fast; a lot accumulated → milliseconds. These are the outliers an application feels |
Step 3 – the slow ones individually.
# on perf1, terminal 2
sudo timeout -s INT 40 ext4slower-bpfcc 2ext4slower-bpfcc 2shows every operation that takes longer than 2 ms.timeout -s INT 40ends it after 40 seconds with the signalINT– like Ctrl+C, so that it cleans up properly. On perf1 the tool needs about 25 seconds before it even starts, because at startup it reads a long list of kernel functions. Be patient.
Expected (excerpt – the first lines):
Tracing ext4 operations slower than 2 ms
TIME COMM PID T BYTES OFF_KB LAT(ms) FILENAME
13:37:55 fio 3570 S 0 0 2.56 misch.0.0
13:37:55 fio 3571 S 0 0 2.79 misch.1.0
13:37:55 fio 3570 S 0 0 2.23 misch.0.0
13:37:55 fio 3571 S 0 0 2.33 misch.1.0
13:37:55 fio 3570 S 0 0 2.22 misch.0.0
13:37:55 fio 3571 S 0 0 2.67 misch.1.0
13:37:55 fio 3570 S 0 0 2.49 misch.0.0
13:37:55 fio 3571 S 0 0 2.13 misch.1.0
13:37:55 fio 3570 S 0 0 3.24 misch.0.0
13:37:55 fio 3571 S 0 0 3.47 misch.1.0
13:37:55 fio 3570 R 8192 4584 8.82 misch.0.0
13:37:55 fio 3570 R 8192 67912 2.48 misch.0.0
| Column | Meaning |
|---|---|
T |
type of operation: S = sync (fsync),
R = read, W = write, O =
open |
BYTES, OFF_KB |
size and position in the file |
LAT(ms) |
duration of the individual operation |
FILENAME |
the file |
Almost all slow operations are fsync; plus individual
reads of up to 8.8 ms with exact position. With process name, ID and
file you have everything to show an application which
of its operations are slow.
Step 4 – which files? Restart fio in terminal 1 if it has finished, then:
# on perf1, terminal 2
sudo filetop-bpfcc -C 5 1-Ckeeps the screen from being cleared (otherwise it behaves liketop),5 1means every five seconds, once.
Expected (excerpt – the first lines):
Tracing... Output every 5 secs. Hit Ctrl-C to end
13:37:15 loadavg: 1.64 0.74 0.63 3/159 3505
TID COMM READS WRITES R_Kb W_Kb T FILE
3501 filetop-bpfcc 1496 0 4461096 0 R vmlinux
3489 fio 2405 1047 19240 8376 R misch.1.0
3488 fio 2419 992 19352 7936 R misch.0.0
The two fio processes with about 2,400 reads and 1,000 writes each in
five seconds. And at the very top – the tool itself: at
startup filetop reads 4.4 GB from vmlinux (the
kernel’s type information under /sys/kernel/btf/, several
times). Measuring tools create load themselves. With eBPF tools it
occurs mainly at startup; that is why you do not measure in the first
moment and do not restart tools constantly.
Step 5 – clean up when fio has finished.
misch.* matches all files that start with
misch.:
# on perf1
rm -f /daten/misch.*Remember: Histograms show the shape of latency – often two peaks.
ext4slowershows the individual outliers with file. And every measuring tool costs something itself, above all at startup.
If it doesn’t work
ext4slowerstill shows nothing after 20 seconds, not even the header line: it is still starting. OnlyTracing ext4 operations slower than 2 msmeans that it is measuring.- An abort with
KeyboardInterruptand a Python traceback: you chosetimeouttoo short; the tool was interrupted while starting.
Save your progress? Sign up for free
Drill 4: Which files does a program open?
Where you are: on perf1, two terminals.
What you have afterwards: seen all files Python opens at startup – including the ones it does not find.
Step 1 – start opensnoop.
# on perf1, terminal 1
sudo opensnoop-bpfcc -n python3-n python3limits the output to processes with this name.
Wait until the header line appears (about 15 seconds).
Step 2 – start Python once.
# on perf1, terminal 2
python3 -c "import json"-cruns the text as a Python program: here only the modulejsonis loaded.
Stop opensnoop with Ctrl+C.
Expected (excerpt):
PID COMM FD ERR PATH
3654 python3 3 0 /etc/ld.so.cache
3654 python3 3 0 /lib/x86_64-linux-gnu/libm.so.6
...
3654 python3 -1 2 /usr/lib/locale/C.UTF-8/LC_CTYPE
3654 python3 -1 2 /usr/pyvenv.cfg
3654 python3 -1 2 /usr/bin/pyvenv.cfg
3654 python3 -1 2 /usr/bin/python3._pth
3654 python3 -1 2 /usr/bin/python3.12._pth
3654 python3 -1 2 /usr/bin/pybuilddir.txt
...
3654 python3 3 0 /usr/lib/python3.12/json/__pycache__/__init__.cpython-312.pyc
3654 python3 3 0 /usr/lib/python3.12/json/__pycache__/decoder.cpython-312.pyc
| Column | Meaning |
|---|---|
FD |
the file descriptor open returned; −1
means failed |
ERR |
the error number: 2 is ENOENT, “file
does not exist” |
PATH |
the file that was to be opened |
For a single import json, Python opens 59 files; 6 of
them do not exist – Python looks for configuration in several places.
With Python that is harmless. With programs that look for dozens of
non-existent files on every request (for example libraries on long
search paths or configuration on a network drive), it becomes a
performance problem – and opensnoop finds it in
seconds.
Remember:
ERR 2inopensnoopmeans: looked for and not found. Many of them per request are wasted trips – expensive ones on a network drive.
Save your progress? Sign up for free
Diagnosis task
A service writes events to a log file. It manages “only a few hundred events per second”, even though the CPU hardly does anything and the disk can do “hundreds of megabytes per second” according to the vendor. The team wants to order a faster disk.
Setup. A directory for today:
# on perf1
mkdir -p ~/tag08Then the program:
# on perf1
nano ~/tag08/protokoll.pyContent (nano as on Day 0: Ctrl+O and Enter saves, Ctrl+X exits):
import os, sys, time
ziel = sys.argv[1]
alle = int(sys.argv[2]) # nach wie vielen Zeilen fsync aufrufen
n = 0
t0 = time.time()
with open(ziel, "a") as f:
while True:
f.write(f"{time.time():.6f} Ereignis {n} verarbeitet\n")
n += 1
if n % alle == 0:
f.flush()
os.fsync(f.fileno())
if n % 20000 == 0:
jetzt = time.time()
print(f"{n} Zeilen, {20000 / (jetzt - t0):.0f} Zeilen/s", flush=True)
t0 = jetztThe while loop is in the program that runs as a service
– you do not type it into the shell.
Start it as a transient service (Day 15 explains
systemd-run in detail):
# on perf1
sudo systemd-run --unit=protokoll -p User=ubuntu python3 /home/ubuntu/tag08/protokoll.py /daten/ereignisse.log 1--unit=protokollname of the service (protokoll= “log”),-p User=ubunturuns as userubuntu.
Please do not read the second argument (1) yet – the
solution explains it. Wait 40 seconds.
Task (20 minutes): How many events does the service manage? What is the cause? Would a faster disk help?
Solution path
Step 1 – how fast? The program reports to the
journal every 20,000 lines. -n 1 shows only the last
message, -o cat only its text:
# on perf1
journalctl -u protokoll --no-pager -o cat -n 1Expected:
20000 Zeilen, 482 Zeilen/s
Step 2 – is it waiting?
# on perf1
vmstat 1 3Expected:
procs -----------memory---------- ---swap-- -----io---- -system-- -------cpu-------
r b swpd free buff cache si so bi bo in cs us sy id wa st gu
1 1 0 10555696 131320 1351600 111 111 2280 4860 978 1 2 1 94 2 0 0
0 1 0 10555696 133156 1351808 0 0 0 7760 4976 6311 1 6 76 16 2 0
0 1 0 10555696 134980 1351768 0 0 0 8072 5158 6564 1 6 76 16 1 0
The first line is the average since boot.
The service’s PID:
# on perf1
systemctl show -p MainPID --value protokollExpected:
77008
You will see a different number. Use yours in the following commands.
# on perf1
pidstat -p 77008 1 1Expected (excerpt – without the first line with kernel and date):
23:23:52 UID PID %usr %system %guest %wait %CPU CPU Command
23:23:53 1000 77008 5.00 8.00 0.00 0.00 13.00 0 python3
Average: 1000 77008 5.00 8.00 0.00 0.00 13.00 - python3
One process blocked (b = 1), 16 % wa, about
8 MB/s written – and the service itself needs only 13 % of a CPU. It is
waiting.
Step 3 – what does the disk see?
# on perf1
iostat -sxz 1 2-sshort columns,-xextended,-zonly devices with activity,1 2two reports at one-second intervals.
Expected (excerpt – the second report):
Device tps kB/s rqm/s await areq-sz aqu-sz %util
sdb 1555.00 8432.00 554.00 0.50 5.42 0.95 73.10
1,556 requests per second with only 5.4 KiB on average, each completed in 0.5 ms. The disk is busy 74 % of the time – with tiny jobs. Throughput: 8 MB/s. It is far from “hundreds of megabytes”, but not because it is slow.
Step 4 – which system calls? syscount
counts the system calls of a process:
# on perf1
sudo timeout -s INT 25 syscount-bpfcc -p 77008 -d 5-pthe process,-d 5measures for five seconds. This tool also needs a few seconds to start;timeoutgives it 25 in total.
Expected (the order of the two equally large lines can change):
Tracing syscalls, printing top 10... Ctrl+C to quit.
[23:24:08]
SYSCALL COUNT
write 2476
fsync 2476
As many fsync as write:
2,476 in five seconds, that is after every write.
Step 5 – what does that cost?
# on perf1
sudo timeout -s INT 25 ext4dist-bpfcc -p 77008 5 1-plimits the measurement to the process.
Expected (excerpt – the lines with hits):
operation = write
usecs : count distribution
8 -> 15 : 1 | |
16 -> 31 : 654 |****************** |
32 -> 63 : 1441 |****************************************|
64 -> 127 : 137 |*** |
128 -> 255 : 15 | |
256 -> 511 : 7 | |
512 -> 1023 : 1 | |
operation = fsync
usecs : count distribution
1024 -> 2047 : 1361 |****************************************|
2048 -> 4095 : 836 |************************ |
4096 -> 8191 : 55 |* |
8192 -> 16383 : 1 | |
Almost every write takes 16 to 63 µs, every
fsync 1 to 4 ms, mostly 1 to 2. So about 2
ms per line, more than 95 % of it in fsync. 1 ÷ 2 ms = 500
lines per second – matches the measured 482. A disk twice as fast might
turn 2 ms into 1 ms: 1,000 lines per second. The problem is not the disk
but how often data is secured – in the picture: how
often you go down to the basement with the messenger.
Now the second argument makes sense: alle = 1
(alle = “every”) – fsync after every line.
Step 6 – fix. Does every single line really have to
be safe immediately? Often it is enough to secure every few hundred
lines or once per second; in the worst case the last lines are lost in a
power failure. That is a business decision, not a technical one. Here:
fsync after every 1,000 lines. First stop the service:
# on perf1
sudo systemctl stop protokollIf a transient service has failed, systemd remembers that and refuses
the same name; reset-failed clears this state:
# on perf1
sudo systemctl reset-failed protokollIn the lab the result was
Failed to reset failed state of unit protokoll.service: Unit protokoll.service not loaded.
– the service had ended cleanly when stopped, there was nothing to
clear. That is not an error.
# on perf1
sudo systemd-run --unit=protokoll -p User=ubuntu python3 /home/ubuntu/tag08/protokoll.py /daten/ereignisse.log 1000Wait 15 seconds. Then the messages of the last twelve seconds:
# on perf1
journalctl -u protokoll --no-pager -o cat --since "-12s"Expected (excerpt – the last three lines):
1900000 Zeilen, 124236 Zeilen/s
1920000 Zeilen, 126401 Zeilen/s
1940000 Zeilen, 110992 Zeilen/s
# on perf1
iostat -sxz 1 2Expected (excerpt – the second report):
Device tps kB/s rqm/s await areq-sz aqu-sz %util
sdb 382.00 10400.00 888.00 0.73 27.23 0.33 25.60
About 120,000 lines per second instead of 482 – almost 250
times as many. And the disk has less to do:
382 instead of 1,555 requests per second, 27 instead of 5 KiB per
request, 26 % instead of 73 % utilization. syscount now
shows 656 fsync in five seconds – about 130 per second, one
per 1,000 lines. The faster disk can be cancelled.
Step 7 – clean up.
# on perf1
sudo systemctl stop protokoll# on perf1
sudo systemctl reset-failed protokollThe message not loaded again only means: nothing to
do.
# on perf1
rm -f /daten/ereignisse.log /daten/daten.binRemember: If an application calls
fsyncper operation, thefsynclatency determines the throughput – not the megabytes per second of the disk. Securing less often is a business decision.
If it doesn’t work
syscountshows nothing: it needs a few seconds to start;-d 5only measures five seconds after that. Givetimeoutenough time (25 seconds).- After the restart of the service no lines appear in the
journal:
--since "-12s"was too short, or the service has not reached 20,000 lines yet. Wait a few more seconds.
Challenge
Restart the log service with fsync after every line and
measure the latency of the fsync calls with
ext4dist -p. Then start the mixed fio load from Drill 3 in
the second terminal as well. What happens to the service’s
fsync times – and why?
Solution path: In the author’s lab the distribution
of fsync times (five seconds each, shortened) looked like
this:
### allein
512 -> 1023 : 9 | |
1024 -> 2047 : 1680 |****************************************|
2048 -> 4095 : 668 |*************** |
4096 -> 8191 : 38 | |
### mit fio
512 -> 1023 : 1 | |
1024 -> 2047 : 1211 |****************************************|
2048 -> 4095 : 835 |*************************** |
4096 -> 8191 : 72 |** |
8192 -> 16383 : 8 | |
16384 -> 32767 : 3 | |
The mass shifts to the right, outliers of more than 16 ms are added,
and in the same time the service manages 11 % fewer fsync –
even though it does nothing differently itself. ext4 has
one journal per file system – one register that
everyone queues in front of: an fsync has to wait until the
current journal transaction has been written, and that now also contains
fio’s metadata changes. Foreign load on the same file system therefore
slows down the securing of everyone else. In practice that is a reason
to put databases and their logs on file systems of their own. Clean up
afterwards as above.
Save your progress? Sign up for free
Checkpoint
# on perf1
systemctl is-active protokollExpected: inactive.
# on perf1
ls /datenExpected: only lost+found.
# on perf1
grep -E "^Dirty" /proc/meminfoExpected: a small value, a few hundred kB or less.
# on perf1
pgrep -fc "[b]pfcc"Expected: 0 – no measuring tool is running in the
background anymore. -f searches the whole command line,
-c only counts. The square brackets in the pattern prevent
pgrep from finding its own command line.
Test yourself
- A program writes 2 GiB and is done after seven seconds. Is the data on the disk now?
- How do you recognize that an eBPF tool measures wrongly on your kernel?
- Why does the
fsynchistogram in Drill 3 have two peaks? - A service manages 500 operations per second, the disk is only loaded
with 8 MB/s. Which two tools show you within five minutes whether
fsyncis the cause? - Why do a service’s
fsynccalls get slower when another process writes on the same file system?
Answers:
- No. Part of it is still in the cache as dirty pages
(
Dirtyin/proc/meminfo); only the messenger orsync/fsyncbrings it to disk. - Test it against a load whose result you know. If it then shows zeros or nonsense, it probably attaches to kernel functions that no longer exist (or work differently).
- If there was little to write back,
fsyncis done after a few hundred µs; if a lot had accumulated, it takes milliseconds. syscount -p(how manyfsyncperwrite) andext4dist -p(how long each one takes).- ext4 has one journal per file system; an
fsyncwaits for the current transaction, which also contains the changes of the others.
Interview Note
“Our database is slow under write load, but the disk is not
saturated.” – Whoever thinks of fsync here and can explain
that synchronous securing costs a fixed latency per operation that has
nothing to do with throughput is on the right track. Name the tools:
ext4dist/ext4slower for latency per operation,
syscount for frequency. Ideas for a solution: group
commits, securing per time period, faster flush latency (disks
with power-loss protection) – and the question of how much data loss is
acceptable from a business point of view.
Enterprise Note
Databases have settings for exactly this trade-off – for example how
often the transaction log is secured (in PostgreSQL
synchronous_commit, in MySQL
innodb_flush_log_at_trx_commit). They must not be changed
“for speed” without the approval of whoever is responsible for the data.
For application logs, buffered writing with regular securing is almost
always enough; journald, for example, only secures every few minutes or
on critical messages by default. And once more: test eBPF tools on the
kernel version in use before an emergency – a tool that shows zeros
during an incident does more damage than none at all.
Summary
- A file access passes through VFS → page cache → file system → block layer. What the application experiences is measured at the upper layers.
cachestat(bcc 0.29) only shows zeros on kernel 6.8 because it listens at old functions instead of the folio functions. Test tools against a known load. Replacement: bpftrace onfolio_mark_accessedandfilemap_add_folio.- Writes land in the cache as dirty pages;
dirty_background_ratio(10 %) starts write-back,dirty_ratio(20 %) throttles the writer. fsyncwaits for journal and flush – milliseconds instead of microseconds.ext4dist(histograms),ext4slower(individual slow operations),filetop(files),opensnoop(opened files, failed ones too). Some bcc tools take a long time to start and create load themselves while doing so.- Diagnosis today:
fsyncafter every line limited a service to 482 lines/s; with onefsyncper 1,000 lines 120,000 lines/s – with less load on the disk.
Commands at a glance
| Command | What it does | Parameters |
|---|---|---|
cachestat-bpfcc 1 5 |
hit rate of the page cache (broken on 6.8) | interval, count |
bpftrace -e 'kprobe:folio_mark_accessed {…}' |
count cache accesses yourself | see Drill 1 |
grep … /proc/kallsyms |
check whether a kernel function exists | – |
echo 3 \| sudo tee /proc/sys/vm/drop_caches |
discard the page cache (lab only) | – |
cat /proc/sys/vm/dirty_ratio,
dirty_background_ratio |
thresholds for dirty pages | – |
grep -E "^(Dirty\|Writeback):" /proc/meminfo |
dirty / write-back pages | – |
sync |
write back everything dirty | – |
ext4dist-bpfcc [-p PID] 10 1 |
latency histograms of the ext4 operations | -p process |
ext4slower-bpfcc 2 |
ext4 operations over 2 ms | threshold in ms |
filetop-bpfcc -C 5 1 |
files by read/write volume | -C do not clear |
opensnoop-bpfcc -n NAME |
every open of a program |
-n name, -x failures only |
syscount-bpfcc -p PID -d 5 |
count system calls | -p process, -d duration |
journalctl -u DIENST -o cat -n 1 |
last message of a service (DIENST = service) |
-n count, --since |
timeout -s INT 40 BEFEHL |
end a command after a time with the Ctrl+C signal
(BEFEHL = command) |
-s signal |
fio --rw=randrw --rwmixread=70 --fsync=32 … |
mixed load with fsync | see Drill 3 |