Self-Hosted eBPF Observability for io_uring: Tracing SQ/CQ Latency, SQPOLL Behavior, and Per-Opcode Async I/O Stalls
Quick Summary (TL;DR)
- io_uring’s shared-memory SQ/CQ rings and optional SQPOLL kernel thread make traditional syscall tracing blind spots.
- Attach eBPF kprobes to
io_uring_submit_sqe,io_uring_queue_async_work, andio_uring_completeto measure per-opcode latency from submission to completion.- Use
io_uring:io_uring_submit_sqetracepoints plussched_switchto catch SQPOLL thread starvation.- Correlate requests to application threads via
user_datain a BPF hash map, then export to Prometheus and alert on P99 CQ latency per opcode.- Target kernel ≥ 6.1 with BTF enabled for CO-RE portability and stable tracepoint signatures.
Introduction: Why io_uring Needs Dedicated eBPF Observability
io_uring replaces the syscall-per-I/O model with a pair of shared-memory ring buffers—the Submission Queue (SQ) and Completion Queue (CQ)—that userspace and kernel use to exchange I/O requests. The performance win is real: fewer syscalls, batched submissions, and optional kernel-side polling via SQPOLL. But that win comes at a cost to observability. Once you enable IORING_SETUP_SQPOLL, the application may never issue a syscall per request, so strace, perf trace, and classic sys_enter_* probes see almost nothing.
That blind spot is exactly where eBPF shines. By attaching kprobes and tracepoints to io_uring’s internal functions, you can reconstruct the full lifecycle of every request—when it entered the SQ, when the kernel picked it up, how long the operation ran, and when the CQE landed—without recompiling the kernel or restarting the application. This guide walks through a production-ready, self-hosted stack that answers three questions: How long does each request spend in the SQ? How long does the operation itself take, broken down by opcode? And is the SQPOLL kernel thread being starved?
Understanding io_uring Internals: SQ, CQ, and SQPOLL
Before writing probes, map the moving parts. Userspace writes a Submission Queue Entry (SQE) into the SQ ring, then either calls io_uring_enter() or, in SQPOLL mode, updates the tail pointer and lets the kernel thread notice it. The kernel dequeues the SQE, executes the operation (possibly asynchronously), and posts a Completion Queue Event (CQE) into the CQ ring. Applications read CQEs and, if IORING_SETUP_IOPOLL or IORING_SETUP_SQPOLL are used, may spin rather than block.
flowchart LR
A[App thread writes SQE] --> B{SQPOLL enabled?}
B -- No --> C[io_uring_enter syscall]
B -- Yes --> D[SQPOLL kernel thread polls SQ]
C --> E[Kernel dequeues SQE]
D --> E
E --> F[io_uring_queue_async_work / issue]
F --> G[Block layer / filesystem]
G --> H[io_uring_complete]
H --> I[CQE posted to CQ ring]
I --> J[App reads CQE]
style D fill:#f9e79f,stroke:#b7950b
style H fill:#abebc6,stroke:#1e8449
The three latency segments you care about are: SQ latency (SQE write → kernel dequeue), operation latency (dequeue → completion), and CQ latency (completion function → CQE visible to userspace). SQPOLL adds a fourth: thread wakeup latency (tail update → SQPOLL thread running).
Prerequisites and Environment Setup
You need a modern kernel and toolchain. The following baseline is what we recommend for a self-hosted deployment:
| Component | Minimum | Recommended | Reason |
|---|---|---|---|
| Linux kernel | 5.15 | 6.1+ | Stable io_uring tracepoints, BTF |
BTF (CONFIG_DEBUG_INFO_BTF) | required | required | CO-RE portability |
CONFIG_IO_URING | required | required | io_uring itself |
| libbpf | 1.0 | 1.4+ | CO-RE and ring buffer APIs |
| clang/LLVM | 12 | 17 | BPF target |
| Prometheus + Grafana | any | 2.45+ / 10+ | Dashboards and alerting |
Install the toolchain:
sudo apt install -y clang llvm libbpf-dev bpftool linux-tools-common \
linux-tools-$(uname -r) prometheus grafana
Verify BTF and tracepoints are available:
ls /sys/kernel/btf/vmlinux
sudo bpftool btf dump file /sys/kernel/btf/vmlinux | grep -i io_uring | head
sudo ls /sys/kernel/debug/tracing/events/io_uring/
If /sys/kernel/debug/tracing/events/io_uring/ is empty, you are on a kernel that predates the tracepoints; fall back to kprobes on io_uring_submit_sqe and io_uring_complete.
Step 1: Tracing Submission Queue (SQ) Latency with eBPF
SQ latency is measured from the moment userspace hands the SQE to the kernel. In non-SQPOLL mode, the natural anchor is the io_uring_enter syscall exit. In SQPOLL mode, use the io_uring:io_uring_submit_sqe tracepoint, which fires when the kernel consumes an SQE.
A minimal libbpf program that records the submission timestamp keyed by user_data:
struct submit_key {
__u64 user_data;
__u32 pid;
};
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, 65536);
__type(key, struct submit_key);
__type(value, __u64); // timestamp ns
} submit_ts SEC(".maps");
SEC("tp/io_uring/io_uring_submit_sqe")
int trace_submit(struct trace_event_raw_io_uring_submit_sqe *ctx)
{
struct submit_key k = {
.user_data = ctx->user_data,
.pid = bpf_get_current_pid_tgid() >> 32,
};
__u64 ts = bpf_ktime_get_ns();
bpf_map_update_elem(&submit_ts, &k, &ts, BPF_ANY);
return 0;
}
Compile with clang -O2 -g -target bpf -D__TARGET_ARCH_x86 -c sq_latency.bpf.c -o sq_latency.bpf.o, generate a skeleton with bpftool gen skeleton, and load it. Each entry in submit_ts marks the moment the kernel took ownership of the SQE—subtract this from the completion timestamp to get end-to-end latency, and from the dequeue timestamp (Step 2) to isolate SQ time.
Step 2: Tracing Completion Queue (CQ) Latency and Per-Opcode Stalls
The completion side is where per-opcode analysis lives. The io_uring_complete kprobe fires with the io_kiocb pointer, whose opcode field tells you whether the request was a READ, WRITE, FSYNC, SENDMSG, or something else. We pair it with a histogram map so the kernel does the aggregation and userspace only reads deltas.
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, 256);
__type(key, __u32); // opcode
__type(value, struct hist); // log2 buckets
} cq_latency SEC(".maps");
SEC("kprobe/io_uring_complete")
int BPF_KPROBE(trace_complete, void *req, long res)
{
__u32 opcode = BPF_CORE_READ((struct io_kiocb *)req, opcode);
struct submit_key k = { .user_data = BPF_CORE_READ((struct io_kiocb *)req, user_data),
.pid = bpf_get_current_pid_tgid() >> 32 };
__u64 *start = bpf_map_lookup_elem(&submit_ts, &k);
if (!start) return 0;
__u64 delta = bpf_ktime_get_ns() - *start;
__u32 slot = bpf_log2l(delta);
// bump hist[opcode].buckets[slot]
bpf_map_delete_elem(&submit_ts, &k);
return 0;
}
Reading opcode via BPF_CORE_READ requires BTF—which is why we insisted on it in the prerequisites. The resulting histogram, keyed by opcode, reveals stalls: a READ opcode whose P99 sits at 50 ms while WRITE sits at 200 µs tells you the read path (page cache miss, device queue depth, or filesystem contention) is the culprit.
Step 3: Monitoring SQPOLL Kernel-Thread Behavior
SQPOLL moves submission work to a per-ring kernel thread named io_uring-sq. If that thread is not scheduled—because the CPU is oversubscribed, or because IORING_SETUP_SQ_AFF pinned it to a busy core—submissions silently pile up in the SQ with no syscall to blame. Detect this by combining two probes:
tp/io_uring/io_uring_submit_sqefires when the SQPOLL thread consumes an SQE.sched/sched_switchtells you when the SQPOLL thread is preempted and how long it waits.
SEC("tp/sched/sched_switch")
int trace_switch(struct trace_event_raw_sched_switch *ctx)
{
char prev[TASK_COMM_LEN];
bpf_probe_read_kernel_str(prev, sizeof(prev), ctx->prev_comm);
if (bpf_strncmp(prev, 11, "io_uring-sq") == 0) {
// record preemption start for ctx->prev_pid
}
return 0;
}
Aggregate the time the SQPOLL thread spends off-CPU into a histogram and alert when P95 exceeds a threshold (e.g., 500 µs). The most common root causes are CPU affinity collisions with application threads and SCHED_OTHER starvation under load; setting IORING_SETUP_SQ_AFF to a dedicated core resolves the majority of cases.
Step 4: Correlating Async I/O Stalls with Application Threads
user_data is the natural correlation key—applications set it, and it survives from SQE to CQE. But it is opaque; to attribute latency to a thread, capture the TID at submit time. In non-SQPOLL mode, bpf_get_current_pid_tgid() inside the io_uring_enter syscall exit gives you the submitting thread. In SQPOLL mode, the submit path runs on io_uring-sq, so you must instead capture the TID at the moment userspace wrote the SQE—either via a uprobe on io_uring_get_sqe or by having the application embed its TID in user_data.
For most teams, the pragmatic approach is a hybrid: capture user_data in the SQE tracepoint, then on the CQ side look up which thread last touched that user_data using a small per-process map populated by a uprobe on io_uring_sqe_set_data. The result is a Prometheus series like io_uring_op_latency_seconds{opcode="READ",tid="12345"} that you can join with application-level tracing spans.
Step 5: Building a Self-Hosted Dashboard and Alerts
Export the BPF maps to Prometheus via a small Go or Rust daemon that reads the ring buffer and histogram maps every second. Grafana panels to build:
| Panel | Metric | Alert threshold |
|---|---|---|
| P99 end-to-end latency per opcode | io_uring_op_latency_seconds | > 10 ms for READ/WRITE |
| SQ wait time | io_uring_sq_wait_seconds | P95 > 200 µs |
| SQPOLL off-CPU time | io_uring_sqpoll_offcpu_seconds | P95 > 500 µs |
| CQ backlog | io_uring_cq_ring_used | > 80% of ring size |
| Opcode error rate | io_uring_completions_total{res<0} | > 0.1% |
Alert rules in Prometheus YAML:
- alert: IoUringSqPollStarvation
expr: histogram_quantile(0.95, rate(io_uring_sqpoll_offcpu_seconds_bucket[1m])) > 0.0005
for: 2m
annotations:
summary: "SQPOLL thread starved on {{ $labels.instance }}"
Comparison: eBPF vs. Traditional Tracing for io_uring
| Capability | strace / perf trace | ftrace | eBPF (this guide) |
|---|---|---|---|
| Sees SQPOLL submissions | ❌ (no syscall) | ⚠️ partial | ✅ |
| Per-opcode latency | ❌ | ⚠️ manual | ✅ native |
| Low overhead (production-safe) | ❌ | ⚠️ | ✅ |
| Correlate with app TID | ⚠️ | ⚠️ | ✅ via maps |
| Histograms in-kernel | ❌ | ❌ | ✅ |
| Requires kernel recompile | ❌ | ❌ | ❌ |
| Portability across kernels | ✅ | ✅ | ✅ with CO-RE |
The takeaway: traditional tools remain useful for one-off debugging, but for continuous production observability of io_uring, eBPF is the only approach that sees SQPOLL traffic, aggregates in-kernel, and stays safe at scale.
Best Practices and Pitfalls
- Always use CO-RE.
io_kiocblayout has shifted across kernel versions;BPF_CORE_READinsulates you from recompilation. - Cap map sizes. A 64K-entry
submit_tsmap is ~1 MB; grow it only if you observe drops (checkbpf_map_lookup_elemfailures). - Guard against missing
user_data. Not all applications set it; fall back toreqpointer hashing. - Beware
IORING_SETUP_IOPOLL. In IOPOLL mode,io_uring_completemay fire from a different context; verify your probe fires once per CQE. - Do not probe on the hot path with heavy work. Keep BPF programs under the 1M instruction limit and avoid string formatting in-kernel.
- Pin the SQPOLL thread.
IORING_SETUP_SQ_AFFpluscpu_set_tis the single highest-impact tuning knob for SQPOLL latency.
Conclusion and Next Steps
io_uring’s performance comes from moving work out of the syscall path—which is precisely where classic tracing tools stop looking. A self-hosted eBPF stack that traces SQ consumption, per-opcode completion latency, and SQPOLL thread scheduling closes that gap with production-safe overhead. Start by instrumenting a single service, validate the histograms against fio synthetic workloads, then roll out the Prometheus alerts. From there, natural next steps include adding IORING_OP_*-specific probes for multishot operations, correlating with OpenTelemetry spans via user_data, and extending the exporter to surface ring-pressure metrics for capacity planning.
FAQ
What is the difference between io_uring SQ and CQ latency? SQ latency measures the time from when an application submits a request to when the kernel begins processing it; CQ latency measures from kernel processing start to when the completion event is posted back to userspace. High SQ latency often indicates SQPOLL thread scheduling delays, while high CQ latency points to slow I/O operations or kernel-side stalls.
How does SQPOLL affect io_uring performance and observability? SQPOLL offloads submission queue polling to a dedicated kernel thread, reducing syscall overhead. However, if that thread is not scheduled promptly, submissions are delayed with no syscall to trace. eBPF can trace the SQPOLL thread’s wakeups, runtime, and context switches to diagnose such delays.
Can eBPF trace per-opcode io_uring stalls?
Yes. By attaching kprobes to io_uring_complete and reading the opcode field from the io_kiocb via BPF_CORE_READ, you can measure latency per opcode (e.g., IORING_OP_READ, IORING_OP_WRITE, IORING_OP_FSYNC) and identify which operation types are causing stalls.
What are the kernel requirements for tracing io_uring with eBPF?
You need a kernel that supports io_uring (5.1+) and eBPF (4.4+ for basic, 5.8+ recommended for BTF and CO-RE). For SQPOLL tracing, ensure CONFIG_IO_URING is enabled and the io_uring tracepoints are present. BTF support (CONFIG_DEBUG_INFO_BTF) is strongly recommended for portable BPF programs.
How do I correlate io_uring stalls with application threads?
Capture the userspace TID and PID at submission time and propagate this context to completion. Store the TID in a BPF map keyed by the request’s user_data, then look it up on the completion probe to attribute latency to specific application threads—even when the submission was executed by the SQPOLL kernel thread.