FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

NVMe Storage & I/O Schedulers

Block I/O layer, storage schedulers (none, mq-deadline, kyber), direct I/O (O_DIRECT), and NVMe queues.

Freshness: current•15 min read•Computer Science and Programming

Key Learning Outcomes

  • ✓Select optimal I/O schedulers for NVMe SSD storage arrays
  • ✓Bypass OS page cache using O_DIRECT for database engines
Full Technical Reference Document

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.

App write() / O_DIRECT or io_uring
blk-mq per-CPU software staging queue
Scheduler (`none`, `mq-deadline`, `kyber`)
Hardware PCIe NVMe Submission Queue
SSD controller completion IRQ / poll
Conceptual teaching model synthesized from:Linux Kernel Kernel.org Official Architecture & Systems DocumentationNVM Express Base Architecture Specification

Learning outcomes

  • Trace I/O submission cleanly across user-space buffers, Linux Page Cache (buffered vs O_DIRECT), blk-mq per-CPU staging queues, and hardware NVMe PCIe queues cleanly.
  • Choose cleanly across none, mq-deadline, and kyber block schedulers on bare-metal NVMe vs cloud EBS virtual disks cleanly.
  • Avoid classic storage bugs: EINVAL unaligned O_DIRECT buffer failures, double-caching RAM waste, and fsync() 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 ChoiceKernel Behavior & BufferingCPU / Latency ImpactIdeal Production Configuration
Scheduler: none (noop)Bypasses kernel queue reordering; submits straight to NVMe hardware queuesLowest CPU latency cleanly (0 inter-core lock traffic)Default cleanly for local physical PCIe Gen4/Gen5 NVMe drives
Scheduler: mq-deadline / kyberBounds read-vs-write latency fairness & target I/O deadlinesPrevents giant sequential write flushes from starving tiny random readsPreferred 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 durabilityFastest 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 & SSDZero 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

  • EINVAL Crashes From Unaligned O_DIRECT Pointers / Sizes: Passing plain unaligned malloc() arrays or arbitrary 317-byte write() lengths onto O_DIRECT handles fails instantaneously cleanly at syscall verification (always use posix_memalign aligned to filesystem logical/physical sector bounds!).
  • Write Flush Starvation Without kyber / mq-deadline on 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 (kyber bounds target latencies cleanly!).
  • Missing Parent Directory fsync() on Atomic File Rename Writes: Writing tmp + fsync(tmp_fd) + rename() without calling fsync(parent_dir_fd) can vanish cleanly on power failure before metadata updates hit journal blocks cleanly.
  • Double Caching RAM Waste: Holding 32 GB inside an app cache (RocksDB block cache) while opening files without O_DIRECT duplicates 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!

Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next