bpftrace is a high-level tracing language and tool for Linux that compiles short scripts into eBPF programs, attaches them to kernel and user-space events, and aggregates the results inside the kernel. In Linux monitoring, bpftrace fills the gap between fixed-output tools such as top or iostat and full profilers such as perf: it lets an engineer ask ad hoc questions about a running production system with a one-line command and minimal overhead.
The language is inspired by awk and DTrace. A program consists of probes, optional filters and actions, for example bpftrace -e 'tracepoint:syscalls:sys_enter_openat { printf("%s %s\n", comm, str(args.filename)); }', which prints every file opened on the system together with the process name.
How bpftrace turns scripts into kernel programs
The bpftrace front end parses a script, performs semantic analysis and generates LLVM intermediate representation, which LLVM compiles into eBPF bytecode. The kernel verifier then checks the bytecode for safety: bounded loops, valid memory access and no crashes. Only verified programs are attached to probes.
When a probe fires, the eBPF program runs in kernel context, reads arguments or stack traces and updates BPF maps, which are kernel-side key-value stores. Aggregations such as counts and histograms are computed inside the kernel, so only summarized results cross into user space. This design keeps overhead low even for events that occur hundreds of thousands of times per second.
Type information comes from BTF (BPF Type Format) on modern kernels, which allows scripts to read kernel structure fields by name without kernel headers. Older systems without BTF require headers and are more fragile across kernel versions.
Probe types and language features
The probe type determines which events a script observes and how stable the script remains across kernel upgrades. Choosing a stable interface where one exists is a key practice.
| Probe type | Attaches to | Stability | Example use |
|---|---|---|---|
| tracepoint | Static kernel instrumentation points | Stable across versions | System call entry and exit |
| kprobe / kretprobe | Entry or return of any kernel function | Unstable, depends on internals | Timing a file system function |
| fentry / fexit | Kernel functions via BTF trampolines | Unstable, lower overhead | Reading typed function arguments |
| uprobe / uretprobe | Functions in user-space binaries | Depends on the binary | Latency of a library call |
| USDT | Static markers in applications | Stable if maintained by the vendor | Database query events |
| profile / interval | Timed sampling on CPUs | Stable | CPU flame graph data |
The language provides built-in variables such as pid, comm, nsecs, kstack and ustack, plus map functions that summarize data. The most frequently used functions are shown below.
| Function | Result | Typical question answered |
|---|---|---|
count() | Number of events per key | Which process calls this most often |
hist() | Power-of-two histogram | How are latencies distributed |
lhist() | Linear histogram with set buckets | How are request sizes distributed |
sum(), avg() | Totals and averages | How many bytes were written per process |
stats() | Count, average and total together | Quick summary of a metric |
bpftrace compared with other Linux tracing tools
bpftrace is best understood as an interactive analysis tool, not a replacement for every other utility in the monitoring toolbox. Its neighbors differ in overhead, flexibility and intended audience.
| Tool | Strength | Overhead | Best suited for |
|---|---|---|---|
| bpftrace | One-liners and short custom scripts | Low, in-kernel aggregation | Ad hoc questions in production |
| BCC tools | Complex tools in Python and C | Low | Packaged, reusable utilities |
| perf | CPU profiling and hardware counters | Low to moderate | Performance profiling and sampling |
| strace | Complete system call trace of one process | High, uses ptrace | Debugging a single program |
| ltrace | Library call tracing | High | Investigating library usage |
The difference from strace is especially important: strace stops the traced process at every system call and can slow it down many times, whereas bpftrace observes the same events across the whole system with a small fraction of that overhead.
Using bpftrace safely in production
Running bpftrace requires root or CAP_BPF with CAP_PERFMON on modern kernels, and it is usually started for minutes, not left running permanently. A disciplined workflow keeps it both useful and safe.
- Start with the bundled tools, such as
biolatency.bt,opensnoop.btandexecsnoop.bt, before writing new scripts. - Filter early with predicates like
/pid == 1234/so that actions run only for relevant events. - Prefer tracepoints over kprobes for scripts that must survive kernel upgrades.
- Aggregate instead of printing for high-frequency events, because per-event output is the main source of overhead.
- Use the `-l` option to list available probes before attaching to them.
For recurring needs, a script that proved useful during an investigation should be turned into a maintained tool or exported to a metrics pipeline. bpftrace excels at answering a new question quickly, whereas continuous dashboards are better served by exporters built on the same eBPF foundation.
Limitations and common mistakes
Most problems with bpftrace come from kernel requirements and from the cost of tracing very frequent events. The table below links typical symptoms to causes and fixes.
| Symptom | Likely cause | Fix |
|---|---|---|
| Script fails to load | Kernel too old or BTF missing | Use a newer kernel or install headers |
| Lost events warning | Output buffer overflowing | Aggregate in maps instead of printing |
| Noticeable slowdown | Probe on a very hot function | Narrow the probe or sample instead |
| Script breaks after upgrade | Kprobe target renamed or inlined | Switch to a tracepoint if available |
| Truncated strings | Default string length limit | Raise the limit with a config setting |
Another limitation is security policy: kernel lockdown in confidentiality mode and some container platforms restrict eBPF, so bpftrace may be unavailable exactly where an administrator expects it. Inlined functions also have no kprobe attach point, which can make a script silently miss events.
In plain words
bpftrace is like placing small, temporary sensors inside a running computer. An engineer writes a short instruction, for example “tell me every time a program opens a file”, and the system starts reporting it immediately without stopping or restarting anything.
Instead of sending every detail out, the sensors count and summarize on the spot, so the computer keeps working at nearly full speed. When the question is answered, the sensors are removed and the system returns to normal.
A real-world example
An online retailer notices that checkout requests occasionally take more than two seconds, although CPU and memory graphs look normal. A site reliability engineer runs the bundled biolatency.bt script on a database server and sees a second peak of disk I/O latency around 100 to 200 milliseconds.
A short custom script then counts block I/O requests by process name and shows that a nightly backup job, running at the wrong time because of a time zone error, saturates the storage. After the schedule is corrected, a repeated histogram shows the slow peak gone. The investigation takes about 30 minutes, requires no restart and adds no measurable load to the production database.