Self-Hosted eBPF I/O Latency Profiling for Your Storage Stack
Quick Summary (TL;DR)
- What: Use self-hosted eBPF (bpftrace/BCC) to measure I/O latency at the VFS, filesystem, block, and device layers — without recompiling kernels or loading out-of-tree modules.
- Why: Traditional tools (
iostat,sar) give you averages and queue depths, not per-request latency distributions or the ability to point at which layer is stalling.- How: Attach tracepoints (
block:block_rq_issue/complete,vfs_*), aggregate in-kernel with histograms, add off-CPU analysis, then join per-request data to application traces.- Watch out for: High-frequency kprobes, unbounded maps, and per-event
printf— all of which can turn a diagnostic into an outage.- Best payoff: Correlating kernel I/O stalls with application p99 latency, layer by layer (NVMe, ZFS, NFS/iSCSI).
Storage latency problems are notoriously slippery. An application reports p99 spikes, iostat shows healthy %util, and the disk vendor swears the device is fine. The truth is usually buried in a specific layer of the I/O path — and eBPF lets you look at every layer, in production, with low overhead.
This guide walks you through a production-ready workflow: from kernel prerequisites to block-layer histograms, filesystem tracing, off-CPU analysis, storage-specific nuances, and finally correlating kernel stalls with application tail latency.
Why eBPF for Storage Latency (and Where It Fits)
Classic storage observability has a blind spot: it measures aggregates. iostat gives you await and r_await — averages that hide bimodal distributions. blktrace gives you per-request detail but writes enormous trace files and is awkward in production.
eBPF changes the economics. You can attach to stable kernel tracepoints, aggregate latency histograms in-kernel (so you never flood user space), and correlate by thread ID, cgroup, device, or filesystem — all with low single-digit CPU overhead when done correctly.
Where eBPF fits best:
- Per-request latency distributions at the block layer, not just averages.
- Layer attribution: is the time in VFS, the filesystem, the block scheduler, or the device?
- Off-CPU analysis: which threads are blocked on I/O, and for how long.
- Correlation: joining kernel I/O stalls to application request IDs.
It is not a replacement for capacity planning tools or vendor telemetry — it’s a precision instrument for answering “where is the time going?”
Prerequisites and Environment Setup
Kernel, BTF, and Toolchain Requirements
You need a modern kernel with BPF and BTF support. Verify:
uname -r # 5.10+ recommended, 6.x ideal
ls /sys/kernel/btf/vmlinux # BTF present → CO-RE works
grep -E 'CONFIG_BPF=|CONFIG_BPF_SYSCALL=|CONFIG_BPF_JIT=|CONFIG_DEBUG_INFO_BTF=' /boot/config-$(uname -r)
BTF (BPF Type Format) enables CO-RE — “compile once, run everywhere” — so your compiled programs work across kernel versions. If /sys/kernel/btf/vmlinux is missing, you’ll need a BTF-enabled kernel or a BTFHub-provided BTF file.
Installing bpftrace and BCC
# Debian/Ubuntu
sudo apt install -y bpftrace bpfcc-tools linux-headers-$(uname -r)
# RHEL/Fedora
sudo dnf install -y bpftrace bcc-tools kernel-devel-$(uname -r)
# Smoke test
sudo bpftrace -l 'tracepoint:block:*' | head
If bpftrace -l lists block tracepoints, you’re ready.
Mapping the I/O Path: Where Latency Hides
Before writing probes, know the terrain. A write from an application traverses several distinct stages, each of which can add latency.
flowchart TD
A[Application write/read] --> B[VFS layer]
B --> C{Filesystem}
C -->|ext4/xfs| D[Page cache / writeback]
C -->|ZFS| E[ZIO pipeline + ARC]
D --> F[Block layer bio]
E --> F
F --> G[I/O scheduler / request queue]
G --> H{Device}
H -->|NVMe| I[Multi-queue blk-mq]
H -->|Network| J[NFS/iSCSI → RPC → remote]
I --> K[Media]
J --> K
VFS, Filesystem, Block Layer, and Device Queues
- VFS (
vfs_read,vfs_write): syscall entry; cheap unless locks contend. - Filesystem: ext4/xfs use the page cache; ZFS has its own ARC and ZIO pipeline.
- Block layer:
bio(block I/O) objects becomerequestobjects in the scheduler queue. - Device queue: with blk-mq (NVMe), requests fan out across hardware queues.
The key insight: block:block_rq_issue → block:block_rq_complete measures device + scheduler time, not the whole application-visible latency. If your block histograms are healthy but the app is slow, the stall is above or below this window.
NVMe vs. ZFS vs. Network Storage Paths
| Storage type | Latency window to probe | Gotcha |
|---|---|---|
| NVMe | block_rq_issue → complete | Deep queues hide per-request latency; watch queue depth |
| ZFS | ZIO pipeline (kprobes) + block layer below | Out-of-tree; internal symbols unstable across versions |
| NFS/iSCSI | RPC/SCSI layer + block layer | Network retransmits look like device latency |
Tracing Block-Layer Latency with bio and request Probes
A bpftrace Script for Per-Device Latency Histograms
This script measures request latency keyed by device, using in-kernel aggregation:
sudo bpftrace -e '
tracepoint:block:block_rq_issue
{
@start[args->dev, args->sector] = nsecs;
}
tracepoint:block:block_rq_complete
/ @start[args->dev, args->sector] /
{
$lat = nsecs - @start[args->dev, args->sector];
@us[args->dev] = hist($lat / 1000);
delete(@start[args->dev, args->sector]);
}
interval:s:10
{
print(@us);
clear(@us);
}
'
Key design choices:
- Keyed by
devandsectorto match issue→complete pairs (sector is a coarse but effective correlator; for stricter matching, includeargs->rwbs). hist()aggregates in-kernel — no per-event printing, so overhead stays flat regardless of IOPS.interval:s:10flushes and clears, giving you rolling 10-second windows.
Interpreting the Output
@us[259:0]:
[256, 512) 1024 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@|
[512, 1K) 2048 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@|
[1K, 2K) 12 | |
[8K, 16K) 3 | |
A healthy NVMe device shows a tight cluster at low microseconds. A bimodal histogram — a big low-latency cluster plus a thin tail at 8–16 ms — is the classic signature of queue saturation or a slow device behind a cache. That tail is what shows up as your application p99.
Filesystem-Level Tracing and Off-CPU Analysis
Capturing VFS and Filesystem Latency
Block-layer latency excludes time spent in the filesystem. To capture the full application-visible read/write latency, probe VFS entry/exit:
sudo bpftrace -e '
kprobe:vfs_read, kprobe:vfs_write
{
@vfs_start[tid] = nsecs;
}
kretprobe:vfs_read, kretprobe:vfs_write
/ @vfs_start[tid] /
{
@vfs_us = hist((nsecs - @vfs_start[tid]) / 1000);
delete(@vfs_start[tid]);
}
interval:s:10 { print(@vfs_us); clear(@vfs_us); }
'
Compare the vfs_us histogram to @us from the block script. If vfs_us has a fat tail but @us is tight, your latency is in the filesystem or page-cache path, not the device.
Off-CPU Time: When Threads Wait on I/O
Off-CPU analysis answers “which threads are blocked, and for how long?” This is where you catch lock contention and scheduler delays that on-CPU profiling misses.
sudo bpftrace -e '
tracepoint:sched:sched_switch / args->prev_state == 2 / // TASK_UNINTERRUPTIBLE
{
@offcpu[args->prev_comm] = hist(nsecs - @wake[args->prev_pid]);
}
tracepoint:sched:sched_switch { @wake[args->next_pid] = nsecs; }
'
Threads in TASK_UNINTERRUPTIBLE (state 2) are typically blocked on I/O or locks. A histogram of their blocked durations, keyed by process name, immediately shows whether your application threads are waiting on disk, on a filesystem lock, or on network.
Storage-Specific Considerations: NVMe, ZFS, and Network Storage
NVMe Multi-Queue and Queue Depth
NVMe uses blk-mq with many hardware queues. Aggregate latency can look fine while a single queue is saturated. Add queue depth to your probes:
# In-flight requests per device
tracepoint:block:block_rq_issue { @inflight[args->dev] = count(); }
If in-flight count climbs while latency tails grow, you’re queue-bound — increase concurrency or investigate the device’s internal GC.
ZFS: ZIO, ARC, and the Block Layer Below
ZFS is an out-of-tree module, so its internal functions (zio_*, arc_*) are not tracepoints. You must use kprobes on ZFS symbols — which are less stable across versions. Validate against /proc/kallsyms first:
grep -E ' (zio_execute|arc_read|zio_done)$' /proc/kallsyms
The block-layer tracepoints still work for ZFS I/O (ZFS issues bios to the underlying devices), so block-layer latency is always visible. ZFS-internal measurement is a bonus, not a requirement.
Network Storage: NFS and iSCSI
For remote storage, separate network latency from server latency. Probe the RPC layer for NFS:
sudo bpftrace -e '
kprobe:rpc_task_run_action { @rpc_start[tid] = nsecs; }
kretprobe:rpc_task_run_action { @rpc_us = hist((nsecs - @rpc_start[tid]) / 1000); }
'
For iSCSI, trace the SCSI mid-layer and the block layer beneath it. This lets you see whether a slow write is a slow network or a slow remote disk.
Correlating Kernel I/O Stalls with Application Tail Latency
Joining eBPF Data with Application Traces
Aggregate percentiles are a starting point, but the strongest signal comes from per-request joins. Capture a shared identifier at both layers:
- Application side: log the thread ID (TID) and a request/trace ID when issuing I/O.
- eBPF side: key latency maps by TID (or cgroup/container ID) and emit per-request latency.
Then join offline by TID and timestamp window.
A Practical Correlation Workflow
sequenceDiagram
participant App
participant eBPF
participant Store as Metrics/Trace Store
participant Analyst
App->>App: Issue I/O, log TID + trace ID
App->>eBPF: syscall enters kernel
eBPF->>eBPF: Record latency by TID
eBPF->>Store: Export per-TID histograms
App->>Store: Export trace spans
Analyst->>Store: Join by TID + time window
Analyst->>Analyst: Identify p99 requests with block stalls
Steps:
- Instrument the app to emit TID + trace ID per I/O operation.
- Run the block-layer script keyed by TID (replace
args->devkey withtid). - Export both datasets to your metrics/trace backend (Prometheus, Tempo, Jaeger).
- Join by TID and timestamp to find which p99 requests had high block latency.
- Compare p99 block latency vs p99 app latency over the same interval for a fast sanity check.
Comparison: eBPF vs. Traditional Storage Profiling Tools
| Tool | Granularity | Overhead | Layer coverage | Production-safe | Correlation |
|---|---|---|---|---|---|
| eBPF (bpftrace/BCC) | Per-request, per-thread | Low (in-kernel agg) | VFS → device | Yes, with care | Excellent (TID/cgroup) |
| iostat / sar | Aggregate averages | Negligible | Block/device | Yes | None |
| blktrace | Per-request | High (trace files) | Block only | Marginal | Manual |
| ftrace | Per-event | Medium | Kernel-wide | Marginal | Manual |
| Application APM | Per-request | Low | User space only | Yes | Excellent |
The verdict: eBPF is the only tool that gives per-request granularity across the full kernel I/O path with production-acceptable overhead. Use iostat for the 30,000-foot view; reach for eBPF when you need to point at a layer.
Production Hardening and Overhead Control
eBPF is safe if you respect its failure modes. The three biggest risks:
- High-frequency kprobes on hot paths — prefer tracepoints over kprobes; they’re stable and cheaper.
- Unbounded map growth — always key maps by a bounded set (device, TID within a window) and
clear()on interval. - Per-event
printf— never. Aggregate withhist()/lhist()and flush on a timer.
Practical hardening checklist:
# Only trace I/O above a latency threshold (sampling)
tracepoint:block:block_rq_complete
/ (nsecs - @start[args->dev, args->sector]) > 1000000 / // > 1ms
{ @slow[args->dev] = count(); }
# Cap map entries
sudo bpftrace --unsafe -e '...' # only if you understand the risk
Additional controls:
- Benchmark on a canary host first and compare CPU overhead before/after.
- Set
RLIMIT_MEMLOCKappropriately (or use--unsafein bpftrace for high-volume maps). - Scope by cgroup to profile one tenant or container: attach with a cgroup filter.
- Run in a sidecar rather than on the host where possible, to isolate blast radius.
A well-scoped tracepoint probe with in-kernel aggregation typically adds low single-digit CPU overhead — the kind you can run continuously on a canary.
Conclusion
Self-hosted eBPF turns storage latency from a black box into a per-request, layer-by-layer story. The workflow is deliberate:
- Map the I/O path — know where latency can hide.
- Trace block-layer latency with
block_rq_issue/completeand in-kernel histograms. - Add VFS and off-CPU analysis to catch stalls above the device.
- Account for storage specifics — NVMe queues, ZFS’s out-of-tree symbols, NFS/iSCSI network paths.
- Correlate by TID to link kernel stalls to application tail latency.
- Harden for production — tracepoints over kprobes, aggregate in-kernel, benchmark on a canary.
The payoff is precision: instead of “the disk is slow,” you’ll know which layer, which requests, and why.
FAQ
Does eBPF I/O tracing work on ZFS, given it is an out-of-tree module?
Yes, with caveats. eBPF can attach to stable tracepoints like block:block_rq_issue and block:block_rq_complete, which ZFS I/O passes through, so block-layer latency is visible. ZFS-internal functions (zio_*, arc_*) are not tracepoints — you must use kprobes on ZFS symbols, which are less stable across versions and may be inlined or renamed. Validate probe names against /proc/kallsyms for your exact module build before relying on them in production.
What is the overhead of running these eBPF probes in production?
Well-scoped tracepoint probes with in-kernel aggregation (histograms and maps) typically add low single-digit CPU overhead. The main risks are high-frequency kprobes on hot paths, unbounded map growth, and per-event user-space printing. Mitigate by aggregating in-kernel with hist()/lhist() instead of printf, setting map size limits, and sampling with filters (e.g. only I/O above a latency threshold). Always benchmark on a canary host first.
How do I correlate block-layer latency with application tail latency? Capture a shared identifier at both layers. On the application side, record the request/trace ID and thread ID (TID) when issuing I/O. In eBPF, key latency maps by TID (or cgroup/container ID) and emit per-request latency. Then join the two datasets offline by TID and timestamp window, or export eBPF histograms to your metrics backend and compare p99 block latency against p99 application latency over the same interval. Per-request joins give the strongest signal.
Why does my application see high latency when block-layer histograms look healthy? The stall is likely above the block layer: filesystem lock contention, page-cache misses and readahead behavior, ZFS ARC misses, NFS retransmits, or scheduler/cgroup throttling. Use off-CPU analysis and VFS-level probes to see where the thread actually waits. If block latency is low but application latency is high, the time is spent in the kernel above the device queue or in user space — not on the media.
Can I use eBPF to profile NFS and iSCSI latency?
Yes. For NFS, trace the NFS client RPC layer (sunrpc/nfs tracepoints or kprobes on rpc_* functions) to measure round-trip time, retransmits, and queueing separately from local block I/O. For iSCSI, trace the SCSI mid-layer and the block layer beneath it. This separates network and server-side latency from local device latency — essential when storage is remote.
Do I need a specific kernel version or BTF to run these tools?
You need a reasonably modern kernel (5.x+, ideally 5.10+ or 6.x) built with CONFIG_BPF, CONFIG_BPF_SYSCALL, CONFIG_BPF_JIT, and CONFIG_DEBUG_INFO_BTF. BTF enables CO-RE, letting compiled eBPF programs run across kernel versions without recompilation. Check for /sys/kernel/btf/vmlinux; if missing, use a BTF-enabled kernel or a BTFHub-provided BTF file.