Skip to content

bpftrace one-liners that answer production questions without a restart

Practical bpftrace one-liners for finding which files are opened, which syscalls are slow, which process issues the disk I/O, and how to read a bpftrace latency histogram — plus the kernel and BTF prerequisites that decide whether they run at all.

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 printf is worth the cost.
  • Save a working one-liner as a .bt script 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 without CONFIG_DEBUG_INFO_BTF and anything touching kernel structs will fail.
  • The package. apt install bpftrace on Debian and Ubuntu, dnf install bpftrace on 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 written args.filename or args->filename.
  • Root, or CAP_BPF plus CAP_PERFMON. On kernels 5.8 and later those two capabilities are enough; before that you need CAP_SYS_ADMIN, which in practice means root. sudo bpftrace is 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/debug mounted — a large ask on a shared platform. kernel.perf_event_paranoid and kernel.kptr_restrict can 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_openat and tracepoint:block:block_rq_issue are the workhorses.
  • kprobe: and kretprobe: — 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: and uretprobe: — 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.
  • BEGIN and END — run once at startup and once at teardown. END is 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.

Diagram of a bpftrace program compiled to BPF bytecode, verified by the kernel verifier, attached to a tracepoint, aggregating into a per-CPU BPF map that user space reads back periodically

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

  1. Confirm bpftrace runs and BTF is present. Two checks before anything else:

    bpftrace --version
    ls -l /sys/kernel/btf/vmlinux
    bpftrace v0.20.2
    -r--r--r-- 1 root root 5817397 Jul 30 08:12 /sys/kernel/btf/vmlinux

    A version and an existing vmlinux BTF 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.

  2. 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_openat2

    Add -v to 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_openat
    tracepoint:syscalls:sys_enter_openat
        int __syscall_nr
        int dfd
        const char * filename
        int flags
        umode_t mode
  3. 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]: 91755

    Output appears only after Ctrl-C, sorted ascending by value, so the answer is the last line. comm is the 16-character task name, not a full command line.

  4. 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.json

    str() is required — args.filename is a kernel pointer, not a string. On bpftrace older than 0.16 write args->filename instead; that single difference accounts for most copy-pasted one-liners failing.

  5. 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]: 6

    41,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.

  6. 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 on sys_exit_read matters — 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. Always delete() the per-thread key, or the map grows without bound.

  7. 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]: 41623552

    Be careful reading this one. Buffered writes are flushed later by a kernel worker, so a lot of I/O legitimately shows up under kworker or jbd2 rather than the process that wrote the data. Reads and O_DIRECT writes attribute correctly.

  8. 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
    ]: 87

    Swap kstack for ustack to 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.

  9. Save it as a script and redirect the output. Anything you might run twice belongs in a .bt file:

    #!/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.bt
    Attaching 3 probes...
    Counting openat by process. Ctrl-C to finish.
    ^C

    With -o, the map contents and printf output land in /tmp/opens.txt while 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/vmlinux exists, 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: run bpftrace -lv <probe> to see the real field names, and try args->field if args.field is 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 against bpftrace -l — open and openat and openat2 are different tracepoints, and a process using io_uring may never issue a read syscall at all. Check your filter, especially comm comparisons, since comm is truncated to 16 characters. And remember that maps print at END: press Ctrl-C, or add an interval probe with print().
  • 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. Your printf rate 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 the BPFTRACE_PERF_RB_PAGES environment variable. A related message about skipped keys means the map hit its key limit, tuned with BPFTRACE_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:99 sampling 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 to vfs_read on 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.