bpftrace lets you ask a running Linux host a specific question — which files is this process opening, which syscall is slow, who is issuing the disk writes — and get an answer in seconds without restarting a service, attaching a debugger, or adding a line of instrumentation to any application. You write a few lines in its own small language, bpftrace compiles them to BPF bytecode, the kernel verifier checks the program, and it runs attached to a probe point until you press Ctrl-C. The trap is portability, not safety: tracepoints are a reasonably stable interface, but kprobe symbol names and tracepoint argument fields shift between kernel versions, so a one-liner copied from a blog post can refuse to compile on the box in front of you while being perfectly correct somewhere else.
What you’ll accomplish
- Confirm bpftrace can actually attach on this kernel, and list the probes that exist here rather than the ones a tutorial assumed.
- Answer four concrete production questions: which files are being opened, which process is burning syscalls, where a syscall’s latency actually sits, and which process issued the disk I/O.
- Read
hist()output correctly — including why the interesting information is almost always in the tail, not the mode. - Know when to aggregate in the kernel and when a per-event
printfis worth the cost. - Save a working one-liner as a
.btscript with its output redirected, so the next person can run it the same way.
Prerequisites
- A kernel with BPF tracing support. Anything from 5.4 onward will run most of what follows; 5.15 and newer is where things get pleasant. Check for BTF, which is what lets bpftrace resolve kernel types without matching kernel headers:
ls -l /sys/kernel/btf/vmlinux. If that file is missing, the kernel was built withoutCONFIG_DEBUG_INFO_BTFand anything touching kernel structs will fail. - The package.
apt install bpftraceon Debian and Ubuntu,dnf install bpftraceon the RHEL family. Distro packages lag upstream badly: 0.14 on an older LTS differs from 0.20+, most visibly in whether tracepoint arguments are writtenargs.filenameorargs->filename. - Root, or
CAP_BPFplusCAP_PERFMON. On kernels 5.8 and later those two capabilities are enough; before that you needCAP_SYS_ADMIN, which in practice means root.sudo bpftraceis the normal way to run it. - An honest caveat about where this will not work. Minimal cloud images, many container-optimized distributions and some vendor kernels ship without BTF or with kprobes disabled. Inside a container you generally need elevated capabilities, the host PID namespace, and
/sys/kernel/debugmounted — a large ask on a shared platform.kernel.perf_event_paranoidandkernel.kptr_restrictcan independently block stack collection and symbol resolution. Verify all of this before planning an incident response around it. - Somewhere to compare notes. If the question is “what is this process blocked on”, strace is usually the faster instrument.
How it works
A bpftrace program is a list of probe specifications, each with an optional filter and an action block. The probe type decides what you can see and how stable it is:
tracepoint:— static instrumentation points the kernel developers placed and named deliberately, with declared arguments. These are the closest thing to a stable interface.tracepoint:syscalls:sys_enter_openatandtracepoint:block:block_rq_issueare the workhorses.kprobe:andkretprobe:— dynamic attachment to the entry or return of almost any kernel function. Enormous reach, zero stability guarantee: functions get renamed, get inlined, or disappear across a minor kernel bump, and your probe silently stops matching.uprobe:anduretprobe:— the same idea for user-space functions in a binary or shared library, which needs symbols present in the target.profile:hz:99— fires on every CPU 99 times a second, regardless of what the kernel is doing. This is sampling, not tracing, and the odd number avoids locking in step with timers that run at 100 Hz.interval:s:10— fires on one CPU every 10 seconds. Use it to print and clear a map so a long-running script produces output while it runs.BEGINandEND— run once at startup and once at teardown.ENDis where bpftrace prints every map you did not print yourself, which is why a one-liner produces nothing at all until you interrupt it.
When you run it, bpftrace parses the program, compiles each action block into BPF bytecode, and loads it with the bpf() syscall. The kernel verifier then rejects anything it cannot prove safe: unbounded loops, out-of-range memory access, missing null checks. That verification pass is the reason this is safe to run on a production host — a program that could crash the kernel does not load in the first place. Once verified, the program is attached to the probe point and runs on every hit, in kernel context.
The part that makes this viable under load is where the data lives. Every @ variable is a BPF map held in the kernel, and count(), sum(), hist() and lhist() are per-CPU aggregations updated in place. A million openat calls become a million cheap counter increments on the CPU that handled them; user space reads the reduced map once, on an interval or at END. Nothing per-event crosses the boundary.
printf() is the exception, and worth internalizing: every printf pushes a record through a perf ring buffer to user space. Fine for a low-rate event; on a hot one it is how you get Lost N events. Print to explore, aggregate to measure.
Step-by-step
-
Confirm bpftrace runs and BTF is present. Two checks before anything else:
bpftrace --version ls -l /sys/kernel/btf/vmlinuxbpftrace v0.20.2 -r--r--r-- 1 root root 5817397 Jul 30 08:12 /sys/kernel/btf/vmlinuxA version and an existing
vmlinuxBTF file means the rest of this guide will work. A missing BTF file means kprobes on kernel structs are off the table and you should stay on tracepoints. -
List the probes that exist on this kernel. Never assume a probe name; ask.
sudo bpftrace -l 'tracepoint:syscalls:sys_*_openat*'tracepoint:syscalls:sys_enter_openat tracepoint:syscalls:sys_enter_openat2 tracepoint:syscalls:sys_exit_openat tracepoint:syscalls:sys_exit_openat2Add
-vto see the arguments a tracepoint exposes, which is the only reliable way to know what to write inside the action block:sudo bpftrace -lv tracepoint:syscalls:sys_enter_openattracepoint:syscalls:sys_enter_openat int __syscall_nr int dfd const char * filename int flags umode_t mode -
Count syscalls per process. The cheapest useful question on a busy box: who is doing the calling?
sudo bpftrace -e 'tracepoint:raw_syscalls:sys_enter { @[comm] = count(); }'Attaching 1 probe... ^C @[systemd-journal]: 1204 @[sshd]: 3391 @[postgres]: 48122 @[node]: 91755Output appears only after Ctrl-C, sorted ascending by value, so the answer is the last line.
commis the 16-character task name, not a full command line. -
Trace which files are being opened. Per-event printing, for a short look:
sudo bpftrace -e 'tracepoint:syscalls:sys_enter_openat { printf("%-6d %-16s %s\n", pid, comm, str(args.filename)); }'Attaching 1 probe... 1188 node /app/config/feature-flags.json 1188 node /app/config/feature-flags.json 842 postgres /var/lib/postgresql/16/main/base/16384/2673 1188 node /app/config/feature-flags.jsonstr()is required —args.filenameis a kernel pointer, not a string. On bpftrace older than 0.16 writeargs->filenameinstead; that single difference accounts for most copy-pasted one-liners failing. -
Aggregate the opens instead of streaming them. The same question, answered without a per-event cost, printing every 10 seconds and then stopping:
sudo bpftrace -e ' tracepoint:syscalls:sys_enter_openat { @[comm, str(args.filename)] = count(); } interval:s:10 { print(@); clear(@); exit(); }'Attaching 2 probes... @[node, /app/config/feature-flags.json]: 41230 @[postgres, /var/lib/postgresql/16/main/base/16384/2673]: 12 @[cron, /etc/localtime]: 641,230 opens of one config file in ten seconds is the kind of finding this tool exists for, and it never shows up in a metrics dashboard.
-
Build a latency histogram for a syscall. Stash a timestamp on entry keyed by thread ID, subtract on exit:
sudo bpftrace -e ' tracepoint:syscalls:sys_enter_read /comm == "postgres"/ { @start[tid] = nsecs; } tracepoint:syscalls:sys_exit_read /@start[tid]/ { @us = hist((nsecs - @start[tid]) / 1000); delete(@start[tid]); }'Attaching 2 probes... ^C @us: [0] 18442 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@| [1] 6210 |@@@@@@@@@@@@@@@@@ | [2, 4) 941 |@@ | [4, 8) 202 | | [8, 16) 61 | | [16, 32) 14 | | [1K, 2K) 7 | | [2K, 4K) 3 | |Read it as: power-of-two buckets in microseconds, then the count, then a bar scaled to the largest bucket.
[2, 4)means two to just under four microseconds. The filter onsys_exit_readmatters — without it, reads that started before you attached produce a garbage duration from an unset@start[tid]. And note where the story is: almost every read is instant, but ten of them took over a millisecond, and those are the ones a user noticed. Alwaysdelete()the per-thread key, or the map grows without bound. -
Get block I/O latency and per-process bytes. Time the device, not the syscall:
sudo bpftrace -e ' tracepoint:block:block_rq_issue { @start[args.sector] = nsecs; } tracepoint:block:block_rq_complete /@start[args.sector]/ { @ms = hist((nsecs - @start[args.sector]) / 1000000); delete(@start[args.sector]); }'Attaching 2 probes... ^C @ms: [0] 9812 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@| [1] 1104 |@@@@@ | [2, 4) 318 |@ | [4, 8) 77 | | [64, 128) 19 | |Then the companion question — who asked for it:
sudo bpftrace -e 'tracepoint:block:block_rq_issue { @bytes[comm] = sum(args.bytes); }'Attaching 1 probe... ^C @bytes[jbd2/nvme0n1p2-]: 1257472 @bytes[kworker/u65:3]: 8433664 @bytes[postgres]: 41623552Be careful reading this one. Buffered writes are flushed later by a kernel worker, so a lot of I/O legitimately shows up under
kworkerorjbd2rather than the process that wrote the data. Reads andO_DIRECTwrites attribute correctly. -
Sample on-CPU stacks with
profile:hz:99. When the question is “what is this process actually doing”, sampling costs almost nothing:sudo bpftrace -e 'profile:hz:99 /pid == 842/ { @[kstack] = count(); }'Attaching 1 probe... ^C @[ copy_page_range+1284 dup_mm+693 copy_process+5729 ]: 4 @[ ext4_file_read_iter+72 vfs_read+201 ksys_read+107 do_syscall_64+89 ]: 87Swap
kstackforustackto sample user-space stacks, which needs symbols and frame pointers in the target binary — many distro builds omit them and you get bare addresses instead. Sampling gives proportions, not exact counts, which is usually what you want. -
Save it as a script and redirect the output. Anything you might run twice belongs in a
.btfile:#!/usr/bin/env bpftrace BEGIN { printf("Counting openat by process. Ctrl-C to finish.\n"); } tracepoint:syscalls:sys_enter_openat { @opens[comm] = count(); } END { printf("Done.\n"); }chmod +x ./opens-by-comm.bt sudo bpftrace -o /tmp/opens.txt ./opens-by-comm.btAttaching 3 probes... Counting openat by process. Ctrl-C to finish. ^CWith
-o, the map contents andprintfoutput land in/tmp/opens.txtwhile attach messages stay on the terminal — which is what you want when you are collecting for later rather than watching.
Validate it works
Never trust a number you have not cross-checked against a workload you created yourself. Use -c so bpftrace traces exactly one command’s lifetime and exits.
Check a count against a known number of operations. Five hundred opens should read as five hundred:
sudo bpftrace -c 'sh -c "i=0; while [ $i -lt 500 ]; do head -c1 /etc/hostname >/dev/null; i=$((i+1)); done"' \
-e 'tracepoint:syscalls:sys_enter_openat /str(args.filename) == "/etc/hostname"/ { @opens = count(); }'
Attaching 1 probe...
@opens: 500
Check bytes against a known transfer size. 256 MiB written with oflag=direct bypasses the page cache, so the block layer sees exactly that much, attributed to dd:
sudo bpftrace -c 'dd if=/dev/zero of=/var/tmp/bpf-test.bin bs=1M count=256 oflag=direct' \
-e 'tracepoint:block:block_rq_issue /comm == "dd"/ { @bytes = sum(args.bytes); }'
256+0 records in
256+0 records out
268435456 bytes (268 MB, 256 MiB) copied, 1.91 s, 141 MB/s
Attaching 1 probe...
@bytes: 268435456
268435456 is 256 MiB to the byte. If your number is far off, the probe is not seeing what you think it is — most often because the write went to the page cache instead of the device. Remove the test file afterwards.
Cross-check against the conventional view. Run the per-process bytes one-liner alongside iostat -x 1 and confirm the totals move together; if bpftrace shows heavy I/O and the device shows none, you are looking at cached operations. The iostat columns worth trusting tell you whether the device is the constraint.
Troubleshooting
- The program will not compile, or complains it cannot resolve a type or field. Two usual causes. Missing BTF: check
/sys/kernel/btf/vmlinuxexists, and if it does not, install the matching kernel debug info package or rewrite the probe against a tracepoint. Wrong argument syntax for your version: runbpftrace -lv <probe>to see the real field names, and tryargs->fieldifargs.fieldis rejected on an older build. - It prints
Attaching N probes...and then nothing forever. Either the probe never fires or you never asked for output. Check the probe name againstbpftrace -l—openandopenatandopenat2are different tracepoints, and a process usingio_uringmay never issue areadsyscall at all. Check your filter, especiallycommcomparisons, sincecommis truncated to 16 characters. And remember that maps print atEND: press Ctrl-C, or add anintervalprobe withprint(). No probes to attach. The probe specification matched nothing on this kernel. A wildcard with no matches produces this too, which is the fast way to tell a typo from a genuinely absent probe.Lost N events. Yourprintfrate exceeded what the perf ring buffer could drain. Replace the print with an aggregation, tighten the filter so fewer events qualify, or raise the buffer with theBPFTRACE_PERF_RB_PAGESenvironment variable. A related message about skipped keys means the map hit its key limit, tuned withBPFTRACE_MAP_KEYS_MAX.- The box slows down while you are tracing. Real, and your fault. A kprobe on a function called millions of times per second adds that cost to every call. Prefer tracepoints, filter as early as possible in the action block, prefer
profile:hz:99sampling when you only need proportions, and keep production runs to tens of seconds rather than minutes. Test on a staging host of the same kernel version first, and never attach tovfs_readon a busy file server just to see what happens.
When this is the wrong approach
- The answer is already in your metrics. If a dashboard can tell you the disk is saturated or a service’s error rate tripled, start there. bpftrace is for the question metrics did not anticipate.
- You want continuous profiling. bpftrace is an interactive instrument, not a collector. A sampling profiler with a storage backend is the right shape for “show me last Tuesday’s CPU profile”.
- The question is about application logic. Which SQL query is slow, which HTTP route regressed, which customer is affected: bpftrace sees syscalls and kernel functions, not business logic. Application tracing answers those faster.
- You need it to keep working across kernel upgrades. Ad-hoc one-liners are fine to throw away. Anything you intend to depend on for months should be a BPF program built against libbpf with CO-RE, or one of the maintained bcc tools — both handle kernel drift deliberately rather than by accident.
- On a host you do not own, or during an incident you have not scoped. Attaching probes to hot paths on a system already in trouble can make the trouble worse. If the problem is one stuck process, exhaust the cheaper instruments first.
The reference guide at bpftrace.org documents every probe type, builtin and function, and the bpftrace repository carries the tools directory worth reading before writing your own.
If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.