Mental model
Legacy spinning hard disks (HDDs) serialized commands into one single mechanical arm-seek queue (CFQ scheduler). Modern NVMe (Non-Volatile Memory Express) SSDs connect straight over PCIe buses exposing thousands of parallel hardware submission and completion queues (up to 64K queues x 64K commands) cleanly mapped per CPU core through Linux's Multi-Queue block layer (blk-mq)—eliminating lock contention across software queues, kernel Page Cache (when using O_DIRECT), and high-IOPS io_uring engines cleanly.
Learning outcomes
- Trace I/O submission cleanly across user-space buffers, Linux Page Cache (
bufferedvsO_DIRECT),blk-mqper-CPU staging queues, and hardware NVMe PCIe queues cleanly. - Choose cleanly across
none,mq-deadline, andkyberblock schedulers on bare-metal NVMe vs cloud EBS virtual disks cleanly. - Avoid classic storage bugs:
EINVALunalignedO_DIRECTbuffer failures, double-caching RAM waste, andfsync()false-durability traps cleanly (missing parent directory fsync).
Theory
Every database WAL writer (PostgreSQL, RocksDB), vector store (DiskANN, Milvus), and AI checkpoint loader faces an explicit split cleanly inside Linux storage:
| Block Layer Choice | Kernel Behavior & Buffering | CPU / Latency Impact | Ideal Production Configuration |
|---|---|---|---|
Scheduler: none (noop) | Bypasses kernel queue reordering; submits straight to NVMe hardware queues | Lowest CPU latency cleanly (0 inter-core lock traffic) | Default cleanly for local physical PCIe Gen4/Gen5 NVMe drives |
Scheduler: mq-deadline / kyber | Bounds read-vs-write latency fairness & target I/O deadlines | Prevents giant sequential write flushes from starving tiny random reads | Preferred on SATA SSDs, mixed read/write heavy EBS virtual volumes |
Buffered I/O (standard read/write) | Flows transparently cleanly through Linux Page Cache; requires fsync() for durability | Fastest hot OS-cached reads; risks silent data loss before fsync() | File servers, mmap model loaders cleanly managed by OS memory |
Direct I/O (O_DIRECT) | Bypasses OS Page Cache completely; DMA directly cleanly between aligned app RAM & SSD | Zero double-caching (Postgres shared_buffers / RocksDB block_cache) | Transactional storage engines managing explicit user caches + aligned buffers |
Crucially, calling fsync(file_fd) alone still loses brand-new created files during sudden power loss cleanly unless the parent directory FD (fsync(dir_fd)) is also synced cleanly (ensuring directory inode entry points persist cleanly onto storage!). And on Linux kernels 5.1+, io_uring pushes multiple async aligned/buffered I/O submissions smoothly through lock-free shared user/kernel ring buffers—slashing syscall context-switch costs (especially alongside NVMe Polling!).
c#define _GNU_SOURCE#include <fcntl.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>int append_aligned_direct_wal(const char *path) {/* O_DIRECT skips kernel Page Cache cleanly; requires sector-aligned memory, offset & length! */int fd = open(path, O_WRONLY | O_CREAT | O_DIRECT, 0644);if (fd < 0) return -1;void *aligned_buf = NULL;if (posix_memalign(&aligned_buf, 4096, 4096) != 0) {close(fd);return -1;}memset(aligned_buf, 0, 4096);memcpy(aligned_buf, "WAL_COMMIT_EPOCH=1024", 21);ssize_t written = write(fd, aligned_buf, 4096);int sync_ok = (written == 4096) && (fsync(fd) == 0);free(aligned_buf);close(fd);return sync_ok ? 0 : -1;}
Trade-offs
Configuring none cleanly inside blk-mq alongside O_DIRECT + io_uring delivers peak million-IOPS NVMe throughput with deterministic sub-100-microsecond read tails cleanly for custom engines (RocksDB, ClickHouse, ScyllaDB) by erasing OS double-buffering cleanly and scaling linearly per CPU core. However, bypassing kernel Page Cache completely forfeits OS read-ahead heuristics unless the application implements explicit aligned async pre-fetching, and imposes strict 4 KiB / 512 B alignment discipline across every buffer address, file offset, and I/O byte count cleanly.
Failure modes and misconceptions
EINVALCrashes From UnalignedO_DIRECTPointers / Sizes: Passing plain unalignedmalloc()arrays or arbitrary 317-bytewrite()lengths ontoO_DIRECThandles fails instantaneously cleanly at syscall verification (always use posix_memalignaligned to filesystem logical/physical sector bounds!).- Write Flush Starvation Without
kyber/mq-deadlineon Heavy Virtual Disks: Massive checkpoint dumps flooding virtualized cloud EBS queues stall tiny SQL read queries for hundreds of milliseconds cleanly when queue depth limits aren't tuned (kyberbounds target latencies cleanly!). - Missing Parent Directory
fsync()on Atomic File Rename Writes: Writingtmp+fsync(tmp_fd)+rename()without callingfsync(parent_dir_fd)can vanish cleanly on power failure before metadata updates hit journal blocks cleanly. - Double Caching RAM Waste: Holding
32 GBinside an app cache (RocksDB block cache) while opening files withoutO_DIRECTduplicates identical blocks inside Linux Page Cache cleanly cleanly stealing RAM from neighbor containers!
Decision scenario
A custom vector/WAL storage daemon writes variable 500-byte append commits synchronously using O_DIRECT, immediately crashing with EINVAL, while heavy nightly dataset checkpoint flushes stall active small index reads cleanly across NVMe/EBS volumes (scheduler=none on EBS!). Align WAL buffers cleanly to 4096 bytes via posix_memalign, invoke explicit fsync(dir_fd) after atomic file creation cleanly, use none on local NVMe hardware vs kyber/mq-deadline on throttled virtual EBS disks cleanly, and prevent double-caching RAM waste cleanly!