Measuring syscall latency with bpftrace without a profiling budget
You rarely need a full profiler to answer "why is this service slow". A histogram of a handful of syscalls, sampled for thirty seconds, usually identifies the layer before anyone opens a flame graph.
Prerequisites
bpftrace needs BTF for kernel type information and a kernel configured with CONFIG_BPF_KPROBE_OVERRIDE. On Debian and Ubuntu the tracefs mount is usually present; if /sys/kernel/tracing is empty, mount it.
apt-get install -y bpftrace linux-headers-$(uname -r)
ls /sys/kernel/btf/vmlinux || mount -t tracefs tracefs /sys/kernel/tracing
# quick sanity check
bpftrace -l 'tracepoint:syscalls:sys_enter_*' | wc -l
One-liner for read latency
Timing the entry and exit of read(2) per process, bucketed logarithmically, gives a shape rather than an average. The shape is what tells you whether you are looking at a fast path with a tail or a uniformly slow path.
bpftrace -e '
tracepoint:syscalls:sys_enter_read
{
@start[tid] = nsecs;
}
tracepoint:syscalls:sys_exit_read
/@start[tid]/
{
@us[comm] = hist((nsecs - @start[tid]) / 1000);
delete(@start[tid]);
}
interval:s:30 { exit(); }'
Three details make this usable on a live host. @start[tid] is keyed by thread id, so concurrent reads do not collide. delete() keeps the map from growing without bound. The interval probe guarantees the script exits instead of being killed at an arbitrary point.
Reading the histogram
A healthy page-cache read sits in the 1–4 µs buckets with a thin tail. A distribution that starts at 40 µs and has a second mode near 500 µs usually means the process is doing blocking I/O in a hot loop, and the second mode is device queueing rather than the filesystem.
| Shape | Likely cause | Next probe |
|---|---|---|
| Tight mode, no tail | Cache hits, healthy | Nothing |
| Bimodal | Cache miss path interleaved with hits | vfs_read entry vs return |
| Long flat tail | Device queue saturation | block:block_rq_complete |
| Everything > 1 ms | Contention on a lock or a shared fd | offcputime for the same comm |
When to stop
If two probes do not narrow the layer, the question is wrong. Latency work converges fastest when each probe eliminates a layer; a third script that measures everything tells you less than a second script that measures one thing precisely.