bpftrace

On this page 7

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 typeAttaches toStabilityExample use
tracepointStatic kernel instrumentation pointsStable across versionsSystem call entry and exit
kprobe / kretprobeEntry or return of any kernel functionUnstable, depends on internalsTiming a file system function
fentry / fexitKernel functions via BTF trampolinesUnstable, lower overheadReading typed function arguments
uprobe / uretprobeFunctions in user-space binariesDepends on the binaryLatency of a library call
USDTStatic markers in applicationsStable if maintained by the vendorDatabase query events
profile / intervalTimed sampling on CPUsStableCPU flame graph data
Main bpftrace probe types

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.

FunctionResultTypical question answered
count()Number of events per keyWhich process calls this most often
hist()Power-of-two histogramHow are latencies distributed
lhist()Linear histogram with set bucketsHow are request sizes distributed
sum(), avg()Totals and averagesHow many bytes were written per process
stats()Count, average and total togetherQuick summary of a metric
Common bpftrace aggregation functions

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.

ToolStrengthOverheadBest suited for
bpftraceOne-liners and short custom scriptsLow, in-kernel aggregationAd hoc questions in production
BCC toolsComplex tools in Python and CLowPackaged, reusable utilities
perfCPU profiling and hardware countersLow to moderatePerformance profiling and sampling
straceComplete system call trace of one processHigh, uses ptraceDebugging a single program
ltraceLibrary call tracingHighInvestigating library usage
bpftrace and related tools

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.bt and execsnoop.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.

SymptomLikely causeFix
Script fails to loadKernel too old or BTF missingUse a newer kernel or install headers
Lost events warningOutput buffer overflowingAggregate in maps instead of printing
Noticeable slowdownProbe on a very hot functionNarrow the probe or sample instead
Script breaks after upgradeKprobe target renamed or inlinedSwitch to a tracepoint if available
Truncated stringsDefault string length limitRaise the limit with a config setting
Typical bpftrace problems

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.