{}DSA Atlas

File Systems, Storage & I/O

Disk and SSD characteristics, disk scheduling (FCFS, SSTF, SCAN, C-SCAN, LOOK) worked, file system internals (inodes, directories, links, journaling), RAID levels, the I/O stack, and I/O models — blocking, non-blocking, select/poll/epoll, io_uring, zero-copy.

Intermediate → Advanced8 interview questions

The storage hierarchy

LevelTypical latencyTypical size
CPU register~0.3 nsbytes
L1 cache~1 ns32–64 KB / core
L2 cache~4 ns1–2 MB / core
L3 cache~15–40 nstens of MB
DRAM~80–100 nsGBs–TBs
NVMe SSD (random read)~20–100 µsTBs
SATA SSD~100 µsTBs
HDD (random read)~5–10 msTBs
Network round trip (same DC)~0.5 ms—

Every factor of 1000 in that table explains a design decision: caches, page caches, buffer pools, batching, and sequential layouts.

Disks

HDD access time

Text
access time = seek time + rotational latency + transfer time
rotational latency (avg) = ½ × (60 / RPM) s     → 7200 RPM: ½ × 8.33 ms ≈ 4.17 ms

Random 4 KB reads on an HDD give ~100–200 IOPS; sequential reads stream at ~150–250 MB/s. Hence: sequential good, random bad.

SSD / NVMe

  • No seek; random reads are fast (tens of µs), hugely parallel (NVMe: up to 64K queues × 64K commands).
  • Writes go to erased pages; erasure happens per block (e.g. 256 pages). The flash translation layer remaps writes and runs garbage collection → write amplification and finite endurance (TBW / DWPD ratings).
  • TRIM/discard tells the SSD which blocks are free.

Disk scheduling (HDD)

Queue of cylinder requests: 98, 183, 37, 122, 14, 124, 65, 67; the head is at 53; cylinders 0–199.

AlgorithmOrder servedTotal head movement
FCFS53→98→183→37→122→14→124→65→67640
SSTF (shortest seek time first)53→65→67→37→14→98→122→124→183236
SCAN (elevator), moving toward 053→37→14→0→65→67→98→122→124→183236
C-SCAN, moving toward 19953→65→67→98→122→124→183→199→0→14→37382 (counting the return sweep)
LOOK, moving toward 19953→65→67→98→122→124→183→37→14299
C-LOOK, moving toward 19953→65→67→98→122→124→183→14→37322 (counting the jump 183→14)

Calculations:

  • FCFS: 45 + 85 + 146 + 85 + 108 + 110 + 59 + 2 = 640.
  • SSTF: 12 + 2 + 30 + 23 + 84 + 24 + 2 + 59 = 236.
  • SCAN (down): (53 − 0) + (183 − 0) = 236.
  • C-SCAN (up): (199 − 53) + 199 + 37 = 382.
  • LOOK (up): (183 − 53) + (183 − 14) = 299.
  • C-LOOK (up): (183 − 53) + (183 − 14) + (37 − 14) = 322.

Trade-offs: SSTF can starve far requests; SCAN/C-SCAN give bounded waits, C-SCAN more uniform wait times. Modern Linux uses mq-deadline, bfq, kyber, or none (best for NVMe, where the device schedules internally).

File systems

What a file system provides

Files (named byte sequences), directories (a hierarchy of names), metadata and permissions, space allocation, and crash consistency.

On-disk layout (Unix-style, e.g. ext4)

superblock block bitmap inode bitmap inode table data blocks inode #4711 mode, uid, size, links=2 direct[0..11] → data single indirect → double / triple indirect → data ptr block data data directory entry:"notes.txt" → 4711
Names live in directories; everything else about a file lives in its inode. Modern ext4 uses extents instead of block lists.

Maximum file size with 4 KB blocks and 4-byte pointers (classic ext2/3): 12 direct + 1024 + 1024² + 1024³ blocks ≈ 4 TB (ext4 extents go beyond).

Path lookup

open("/home/ana/notes.txt") → read the root inode → read its directory data to find home → its inode → … → notes.txt → inode 4711 → check permissions → create an open file description (offset, flags) → return the lowest free file descriptor in the process's fd table. The kernel caches lookups in the dentry cache.

Allocation methods

MethodIdeaProsCons
Contiguousfile = start + lengthfast sequential/randomexternal fragmentation, hard to grow
Linked (FAT)each block points to the next (table in FAT)no fragmentationslow random access
Indexed (inode)index block(s) list data blocksfast random accessindex overhead
Extents (ext4, XFS, NTFS)runs of contiguous blockscompact, fast—
  • Hard link — another name for the same inode (ln a b).
  • Symbolic link — a file containing a path (ln -s a b).

Crash consistency

ApproachHowExamples
fsckscan and repair after a crashext2
Journaling (WAL)log changes, then apply; replay on recoveryext4, XFS, NTFS
Copy-on-writenever overwrite; atomically switch a root pointerZFS, Btrfs, APFS
Log-structuredthe whole FS is an append-only logF2FS (flash), LFS

RAID

LevelLayoutUsable capacity (N disks)Fault toleranceNotes
0stripingNnonespeed only
1mirroring1 diskN − 1fast reads
5striping + 1 distributed parityN − 11 diskwrite penalty; risky rebuilds
6striping + 2 paritiesN − 22 disksbigger write penalty
10stripe of mirrorsN / 21 per mirror pairdatabases' favourite

Parity in RAID 5 is XOR: P = D1 ⊕ D2 ⊕ D3; a lost block is the XOR of the survivors. RAID ≠ backup.

The I/O stack

Text
application → libc buffering → syscall (read/write) → VFS → page cache
→ file system (ext4/XFS) → block layer + I/O scheduler → device driver
→ (DMA) device; completion interrupt
  • Programmed I/O vs interrupts vs DMA: DMA lets the device copy data to/from RAM without the CPU, interrupting only on completion.
  • Buffering smooths speed mismatches; caching keeps hot data in RAM; spooling queues output (printers).

I/O models (how servers wait)

Blocking thread sleeps inside read() until data arrives and is copied Non-blocking EAGAIN… EAGAIN… (polling burns CPU) Multiplexing epoll_wait() on thousands of fds read() ready fds Async completion submit thread does other work; kernel fills the buffer done readiness (reactor: epoll, kqueue) vs completion (proactor: io_uring, IOCP)
Four ways a thread can wait for I/O.

select, poll, epoll

selectpollepoll (Linux) / kqueue (BSD)
fd limitFD_SETSIZE (1024)nonenone
Per-call costO(all fds) copy + scanO(all fds)O(ready fds)
Interest setpassed every callpassed every callregistered once in the kernel
Triggeringlevellevellevel or edge
int ep = epoll_create1(0);
struct epoll_event ev = { .events = EPOLLIN, .data.fd = listen_fd };
epoll_ctl(ep, EPOLL_CTL_ADD, listen_fd, &ev);

struct epoll_event events[1024];
for (;;) {
    int n = epoll_wait(ep, events, 1024, -1);       // block until something is ready
    for (int i = 0; i < n; i++) {
        int fd = events[i].data.fd;
        if (fd == listen_fd) {
            int c = accept4(listen_fd, NULL, NULL, SOCK_NONBLOCK);
            struct epoll_event cev = { .events = EPOLLIN | EPOLLET, .data.fd = c };
            epoll_ctl(ep, EPOLL_CTL_ADD, c, &cev);
        } else {
            handle_readable(fd);    // edge-triggered: read until EAGAIN
        }
    }
}
import selectors, socket

sel = selectors.DefaultSelector()          # epoll on Linux, kqueue on macOS
srv = socket.socket(); srv.bind(("0.0.0.0", 8080)); srv.listen(); srv.setblocking(False)
sel.register(srv, selectors.EVENT_READ)

while True:
    for key, _ in sel.select():
        if key.fileobj is srv:
            conn, _ = srv.accept(); conn.setblocking(False)
            sel.register(conn, selectors.EVENT_READ)
        else:
            data = key.fileobj.recv(4096)
            if data:
                key.fileobj.send(data)       # echo
            else:
                sel.unregister(key.fileobj); key.fileobj.close()

io_uring

Linux's modern async interface: two ring buffers shared with the kernel — a submission queue and a completion queue. Applications batch many operations (reads, writes, accepts, sends, even fsync) with few or zero syscalls (with SQ polling). It supports files and sockets, unlike older Linux AIO. Used by high-performance databases and runtimes (TigerBeetle, ScyllaDB/Seastar, Tokio's tokio-uring). Because of a history of security bugs, some environments (Android, ChromeOS, some container runtimes) restrict it.

Zero-copy

TechniqueAvoids
sendfile, splicecopying file data through user space when sending to a socket
mmapthe copy from page cache to a user buffer
MSG_ZEROCOPYcopying send buffers into kernel memory
DMA + scatter-gatherCPU copies to the NIC
Kernel bypass (DPDK, RDMA)the kernel network stack entirely

Kafka's throughput comes largely from append-only sequential writes + page cache + sendfile to consumers.

Useful tools

iostat -x (device utilisation, await), vmstat (paging, run queue), iotop, lsof (open files, deleted-but-open), strace -e trace=file, df -i (inode exhaustion!), blktrace, perf, and BPF tools (biolatency, ext4slower).

Interview questions

0 / 8 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.