ByteGuideHub
Systems Performance / Storage • • 9 min read

Self-Hosted eBPF-Based Disk I/O Scheduler and Writeback Tuning for NVMe Latency

A practical guide to using eBPF to trace block-layer and writeback behavior, then dynamically tune cgroup v2 io.max, BFQ/mq-deadline selection, and dirty page ratios to cut tail latency on self-hosted NVMe arrays.

Sponsored / Ad Space

Self-Hosted eBPF-Based Disk I/O Scheduler and Writeback Tuning for NVMe Latency

Quick Summary (TL;DR)

  • NVMe drives have microsecond averages but can still spike at the 99.9th percentile due to queuing and writeback bursts.
  • Use eBPF (bpftrace, BCC) to observe block-layer latency and writeback events in production without kernel modules.
  • For most NVMe arrays, prefer the none or mq-deadline scheduler; reserve BFQ for mixed/fairness-sensitive workloads.
  • Lower dirty page ratios (vm.dirty_ratio=10, vm.dirty_background_ratio=5) to smooth writeback bursts.
  • Enforce cgroup v2 io.max limits to isolate noisy neighbors and dynamically adjust with eBPF observations.

Modern self-hosted infrastructure—databases, object stores, CI runners—lives or dies by storage tail latency. This guide walks through a production-ready workflow: observe the block layer and writeback path with eBPF, choose the right scheduler, tune dirty page ratios, and enforce per-cgroup I/O limits that keep your 99.9th percentile honest.

Introduction: Why Tail Latency Matters on NVMe

An NVMe drive can deliver sub-100µs average read latency, yet a single writeback storm or a noisy neighbor can push the 99.9th percentile into tens of milliseconds. For a database serving thousands of queries per second, that tail is what users feel—every hundredth request that stalls becomes a timeout, a retry, or a failed transaction. Averages lie; tails tell the truth.

The problem is not raw bandwidth. It’s queuing: scheduler overhead, deep queue depths, dirty page accumulation, and cgroup contention. eBPF gives you a surgical view into each of these layers without recompiling the kernel, and cgroup v2 gives you the levers to act on what you see.

Understanding the Block Layer and Writeback Path

Block Layer Overview

When an application issues a write, it passes through the VFS, the page cache, and—if not cached—the block layer, where an I/O scheduler may reorder or merge requests before dispatching to the NVMe driver’s multi-queue (blk-mq) submission path.

flowchart TD
    A[Application write] --> B[VFS / syscall]
    B --> C{Page cache hit?}
    C -->|Yes| D[Dirty page marked]
    C -->|No| E[Block layer submit_bio]
    E --> F[I/O Scheduler: none / mq-deadline / BFQ]
    F --> G[blk-mq queues]
    G --> H[NVMe driver]
    H --> I[NVMe device]
    D --> J[Writeback flusher]
    J --> E

Writeback and Dirty Pages

Dirty pages accumulate in RAM until a threshold triggers the flusher threads (kworker/*). If the ratio is too high, writeback bursts arrive as a wall of I/O that saturates the device and inflates latency for foreground reads. Lower ratios mean more frequent, smaller writebacks—smoother latency curves.

eBPF Observability for Block I/O and Writeback

Key eBPF Tools and Their Use Cases

ToolPurposeTypical Use
biolatency (BCC)Block I/O latency histogramSpot tail spikes instantly
biosnoopPer-I/O trace with PID/diskAttribute latency to processes
bpftraceCustom kprobe/tracepoint scriptsMeasure writeback and queue depth
writeback (BCC)Dirty page → writeback latencyDiagnose flusher stalls
bitesizeI/O size distributionDetect pathological small I/O

Tracing Block I/O Latency with bpftrace

This script measures per-request latency from blk_account_io_start to completion, bucketed in microseconds:

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]) / 1000;
  @us = hist($lat);
  delete(@start[args->dev, args->sector]);
}
interval:s:10 { print(@us); clear(@us); }
'

Run this during a load test and watch the histogram’s right tail. A healthy NVMe array shows most I/O under 200µs; a long tail beyond 5ms signals queuing or writeback interference.

Tracing Writeback Events

sudo bpftrace -e '
tracepoint:writeback:writeback_start { @start[args->name] = nsecs; }
tracepoint:writeback:writeback_written /@start[args->name]/ {
  @wb_ms = hist((nsecs - @start[args->name]) / 1000000);
  delete(@start[args->name]);
}
'

If writeback durations cluster in the tens of milliseconds, your dirty ratios are too aggressive.

Choosing the Right I/O Scheduler for NVMe

Scheduler Comparison

SchedulerOverheadFairnessBest ForNotes
noneLowestNonePure NVMe, single workloadPass-through, max throughput
mq-deadlineLowWeakMixed read/write, latency SLOsDeadline expiry prevents starvation
bfqHigherStrongDesktop, multi-tenant fairnessAdds CPU cost, can hurt NVMe
kyberLowModerateFast devices, tuned domainsLess common, worth testing

For a self-hosted NVMe array running a database or object store, none or mq-deadline is the pragmatic default. BFQ shines when you need per-process fairness on a shared device but costs CPU per request.

How to Change the Scheduler

# Inspect current scheduler
cat /sys/block/nvme0n1/queue/scheduler

# Set mq-deadline persistently via udev
cat <<'EOF' | sudo tee /etc/udev/rules.d/60-iosched.rules
ACTION=="add|change", KERNEL=="nvme[0-9]*n[0-9]*", ATTR{queue/scheduler}="mq-deadline"
ACTION=="add|change", KERNEL=="nvme[0-9]*n[0-9]*", ATTR{queue/nr_requests}="1024"
EOF
sudo udevadm control --reload && sudo udevadm trigger

Raising nr_requests to 1024 lets the scheduler batch more deeply—useful for sequential workloads, risky for latency-sensitive ones. Validate with biolatency after each change.

Tuning Writeback and Dirty Page Ratios

Key Parameters

ParameterDefaultEffectNVMe Recommendation
vm.dirty_ratio20Max dirty % before blocking writes10
vm.dirty_background_ratio10% before background flusher starts5
vm.dirty_expire_centisecs3000Age before dirty page is written1500
vm.dirty_writeback_centisecs500Flusher wake interval100
cat <<'EOF' | sudo tee /etc/sysctl.d/90-nvme-writeback.conf
vm.dirty_ratio = 10
vm.dirty_background_ratio = 5
vm.dirty_expire_centisecs = 1500
vm.dirty_writeback_centisecs = 100
EOF
sudo sysctl --system

Lowering the background ratio to 5% means the flusher starts earlier and writes in smaller batches. On a 64GB host, that’s ~3.2GB of dirty pages before background writeback—smoother than the default 6.4GB burst.

Applying Settings

For servers with large RAM (256GB+), consider switching to absolute byte limits (vm.dirty_bytes, vm.dirty_background_bytes) so behavior doesn’t drift as memory scales.

Dynamic Tuning with cgroup v2 io.max

Setting Up cgroup v2

# Confirm unified hierarchy
mount | grep cgroup2
# Typical: cgroup2 on /sys/fs/cgroup type cgroup2 (rw,...)

# Create a slice for the noisy workload
sudo mkdir -p /sys/fs/cgroup/db.slice
echo "+io" | sudo tee /sys/fs/cgroup/cgroup.subtree_control

Configuring io.max

io.max accepts rbps, wbps, riops, wiops per device:

# Limit the noisy CI runner to 200k read IOPS and 500MB/s writes on nvme0n1
echo "259:0 rbps=524288000 wbps=524288000 riops=200000 wiops=200000" \
  | sudo tee /sys/fs/cgroup/ci.slice/io.max

The 259:0 is major:minor from lsblk -o NAME,MAJ:MIN. Assign processes to the cgroup with systemd’s Slice= directive or cgexec.

Dynamic Adjustment with eBPF

A lightweight feedback loop: an eBPF program tracks per-cgroup I/O latency, and a userspace daemon tightens or relaxes io.max when the 99th percentile drifts.

flowchart LR
    A[eBPF: track io latency per cgroup] --> B[Userspace daemon]
    B --> C{p99 > SLO?}
    C -->|Yes| D[Tighten io.max on noisy cgroup]
    C -->|No| E[Relax io.max gradually]
    D --> A
    E --> A

Keep the adjustment rate slow (e.g., once every 5 seconds) to avoid oscillation. Log every change for postmortems.

Putting It All Together: A Step-by-Step Tuning Workflow

Step 1: Baseline Measurement

Run fio with latency percentiles against your target device:

fio --name=baseline --rw=randrw --bs=4k --iodepth=64 \
    --runtime=120 --time_based --percentile_list=50:99:99.9 \
    --ioengine=io_uring --filename=/dev/nvme0n1 --direct=1

Record p50, p99, p99.9. This is your reference.

Step 2: Identify Bottlenecks with eBPF

Run biolatency and biosnoop concurrently. If latency correlates with specific PIDs, you’ve found a noisy neighbor. If it correlates with writeback, tune dirty ratios first.

Step 3: Apply Initial Tuning

Set mq-deadline, apply the sysctl file above, and re-run the baseline. Expect p99.9 to drop 20–50% on write-heavy workloads.

Step 4: Implement Dynamic Adjustments

Deploy the cgroup io.max feedback loop for multi-tenant hosts. Start with conservative limits and tighten based on observed p99.

Step 5: Validate and Iterate

Compare before/after with the same fio command. Monitor biolatency in production for a week. Only then consider further tuning.

Case Study: Reducing Tail Latency on a 4-Drive NVMe RAID

A self-hosted PostgreSQL host on 4× NVMe in RAID-10 showed p99.9 write latency of 42ms under mixed load. biolatency revealed that latency spikes coincided with kworker writeback bursts. Steps taken:

  1. Switched from bfq to mq-deadline → p99.9 dropped to 28ms.
  2. Set vm.dirty_background_ratio=5, vm.dirty_ratio=10 → p99.9 to 14ms.
  3. Added io.max on the backup job’s cgroup (wiops=50k) → p99.9 to 6ms.
  4. Set nr_requests=1024 on the NVMe devices → p99.9 to 4ms.

Final result: 90% reduction in tail latency with no change to average throughput, validated over a 7-day production window.

Conclusion

Tail latency on NVMe is a systems problem, not a hardware one. eBPF lets you see the truth; scheduler choice, dirty ratios, and cgroup v2 io.max let you act on it. Start with observation, apply conservative static tuning, then layer in dynamic feedback only where needed. Measure relentlessly—your p99.9 is the only metric your users will ever notice.

FAQ

What is tail latency and why is it important for NVMe? Tail latency refers to high-percentile response times (e.g., p99 or p99.9). NVMe drives have very low averages, but queuing, writeback stalls, or scheduler inefficiencies can still spike the tail—and those spikes are what latency-sensitive applications feel.

Can I use eBPF on any Linux distribution? eBPF is supported on most modern distributions with kernel 4.9+, but full block-layer tracing needs kernel 4.18+ and BTF. bpftrace and BCC are packaged for Debian, Ubuntu, Fedora, and RHEL-family distros.

Which I/O scheduler is best for NVMe drives? For most NVMe, none or mq-deadline are recommended due to deep queues and low latency. BFQ helps when fairness matters (desktop, multi-tenant) but adds CPU overhead. Always test against your actual workload.

How do dirty page ratios affect NVMe latency? They control how much data can be cached before writeback triggers. Higher ratios buffer more but cause larger writeback bursts that saturate the device. Lowering them (e.g., dirty_ratio=10, dirty_background_ratio=5) smooths writeback and cuts tail latency.

What is cgroup v2 io.max and how does it help? It sets per-device bandwidth and IOPS limits for a group of processes. Dynamically adjusting these limits based on eBPF observations prevents noisy neighbors from saturating the NVMe drive and causing latency spikes for critical workloads.

Sponsored / Ad Space