Filesystems and storage: inodes, mounts, durability, the I/O path, and flash wear

Disk full has two flavours — bytes and inodes — and deleting a file an open process still holds frees nothing. Check df, df -i, then lsof +L1 before you start deleting things.

Read the briefing
About 9 min to read 10 drills

What to remember

  1. Check inodes as well as bytes. df says 60% and writes still fail? df -i. Millions of tiny files exhaust inodes long before space.
  2. Deleting an open file frees nothing. The space returns when the holder closes it. lsof +L1 finds them; truncating a live log is the safe move.
  3. fsync is what makes a write durable. A returning write() only reached the page cache. Databases fsync; so must anything claiming durability.
  4. Mount noatime on anything write-heavy. Otherwise every read causes a write. Free performance on log and database volumes.
  5. Watch NVMe wear like a consumable. nvme smart-log percentage-used and media errors predict the failure you would otherwise meet by surprise.

The big picture

Storage questions in Linux rounds are about the layers between a write() call and a durable block on a device: names versus inodes, the page cache and the journal, the block layer and its queues, and the physical medium wearing out underneath. Interviewers use "disk full with space free", "the deleted log still eats space", "is my database durable", and "read this iostat output" because each one exposes whether you know which layer holds the answer.

The mental model

A write travels down a stack: directory entry → inode → page cache (dirty pages) → writeback and journal → block layer queue and scheduler → device cache → flash or platters. Every classic incident is one layer lying to the layer above it: df counts blocks that du cannot name, write() succeeds before anything is on disk, %util says busy while an NVMe has headroom, and a drive reports healthy while its endurance is nearly spent. Ask "which layer am I looking at?" before reading any number.

Diagrams

What write() promises, and what fsync() adds
write()  ---- returns HERE. Nothing is durable yet.
   |
   v
page cache (dirty)
   |                        fsync() waits for
   v                        everything below
filesystem journal
   |
   v
block layer / queue
   |
   v
device write cache ------> platter / NAND

Durable rename: write tmp -> fsync tmp -> rename
                -> fsync the DIRECTORY  (everyone forgets this)
Disk full: three causes, two commands
"No space left on device"
        |
        +-- df -h full? ---- yes --> real data
        |                            du -xh / --max-depth=2
        |
        +-- df -i full? ---- yes --> inodes exhausted
        |                            millions of tiny files
        |
        +-- both look fine? ------> deleted-but-open file
                                     lsof +L1, then
                                     : > /proc/<pid>/fd/N

In depth

Inodes, names, and the two ways a disk is full

A file is an inode: ownership, mode, timestamps, size and the map of blocks. Its name is a directory entry pointing at the inode number, which is why a hard link is just a second name (link count 2 in ls -l / stat) and why renaming is a metadata operation that never touches the data. ext4 allocates its inode table at mkfs time, by default one inode per 16 KiB of space, so a 1 TB volume gets about 61 million inodes and a workload of tiny files (mail queues, session files, Docker layer directories, npm trees) can consume them all while blocks remain free. The failure is ENOSPC: No space left on device with df -h at 40%; df -i shows IUse% 100. You cannot add inodes to ext4 in place: delete files, move the workload, or recreate the filesystem with -i or -N. xfs allocates inodes dynamically (bounded by imaxpct) and is the usual reason a team "never saw this on RHEL".

The second way to be full with space free is reserved blocks: ext4 keeps 5% for root by default (tune2fs -l | grep Reserved), so unprivileged writers hit ENOSPC at 95%. On a data volume that is wasted capacity (tune2fs -m 1), on the root filesystem it is what lets you log in and fix things. Quotas (repquota) are the third cause, and every one of them produces the same error string, which is why the first move is df -h, df -i, and lsof +L1 rather than deleting anything.

Deleted but open: where the space went

rm calls unlink, which removes a name and decrements the inode's link count. The blocks are freed only when the link count is zero and no process holds the file open. A log file that a daemon is still writing therefore keeps growing after rm: df (which asks the filesystem for allocated blocks) shows the space used, du (which walks names) cannot see it, and the gap between them is the size of the phantom.

$ lsof +L1
COMMAND   PID USER  FD   TYPE DEVICE   SIZE/OFF NLINK NODE NAME
java    41822  app   7w   REG  259,1 41823018496     0  393 /var/log/app/app.log (deleted)
$ ls -l /proc/41822/fd | grep deleted
l-wx------ 1 app app 64 ... 7 -> /var/log/app/app.log (deleted)

+L1 lists open files with a link count below one. The fix that needs no restart is to truncate through the descriptor: : > /proc/41822/fd/7 (or truncate -s 0). The writer keeps its offset, so the file becomes sparse from the app's point of view, but the blocks are returned immediately. The durable fix is to stop deleting files that are open: logrotate with copytruncate, or a postrotate hook that sends the daemon its reopen signal (SIGHUP or SIGUSR1) so it closes the old inode and opens the new name. The same mechanism explains why a running binary keeps working after apt upgrade replaces it (/proc/<pid>/exe shows (deleted)), and why a package upgrade needs a service restart to take effect.

Mounts, fstab, and not bricking the boot

A mount attaches a filesystem to a directory; anything previously under that directory is hidden, not deleted, which is a classic "where did my files go" after a mount succeeds late. /etc/fstab lines are device mountpoint type options dump pass; systemd generates a .mount unit for each at boot. Identify devices by UUID= or LABEL= (from blkid), never /dev/sdX, because enumeration order changes when a controller, cable or disk changes.

The options that matter operationally: noatime avoids a write on every read; nodev,nosuid,noexec neutralize device nodes, setuid bits and execution on filesystems users can write to (/tmp, /home, removable and network mounts); ro for immutable content; errors=remount-ro (ext4) turns corruption into a read-only filesystem instead of continuing to write garbage; discard issues TRIM inline while the periodic fstrim.timer does it in batches, which is usually the better choice; _netdev delays a mount until networking is up.

The boot-safety options are the ones interviewers care about. A non-root mount without nofail whose device is missing makes local-fs.target fail, and systemd drops into emergency mode with Dependency failed for Local File Systems. For anything that is not needed to boot, nofail lets the boot continue and x-systemd.device-timeout=10 shortens the 90-second wait. For a data volume a service depends on, pair nofail with RequiresMountsFor=/data in the service so it fails cleanly instead of starting on an empty directory. findmnt shows the live mount table with options; mount -o remount,ro /data changes options without unmounting; fuser -vm /data names what blocks an unmount.

From write() to durable: the page cache, fsync, and the journal

write() copies bytes into the page cache and returns; the page is now dirty and nothing is on disk. The flusher threads write it back when it is older than vm.dirty_expire_centisecs (30 s), when dirty memory exceeds vm.dirty_background_ratio, or when a process forces it. Above vm.dirty_ratio the writing process itself is stalled to write back, which is the "the box froze when the backup ran" symptom. Power loss before writeback loses everything dirty, silently; the application was told the write succeeded.

Durability is requested explicitly. fsync(fd) writes the file's dirty data and metadata, commits the journal transaction, and sends a cache-flush command so the device's volatile write cache is emptied; only when it returns is the data on stable media. fdatasync skips metadata that is not needed to read the data back (timestamps) and is cheaper. Creating or renaming a file is durable only after fsync of the directory, which is why databases and package managers write to a temp name, fsync the file, rename, then fsync the directory. O_DIRECT bypasses the page cache but says nothing about the device cache, so it still needs fsync or O_SYNC for durability; O_DSYNC makes every write behave like write + fdatasync.

Journaling is what keeps the filesystem consistent, not your data: ext4's default data=ordered journals metadata and guarantees that data blocks are written before the metadata that points at them, so you never see another file's old content in yours after a crash, but unsynced data is still gone. xfs journals metadata only with the same effect. The staff-level detail is error handling: if writeback fails, the kernel reports EIO from fsync once and marks the pages clean, so a retried fsync returns success with the data lost; PostgreSQL treats fsync failure as a panic for exactly this reason.

The block layer: schedulers and how to read iostat

Below the filesystem, block requests enter per-device queues and an I/O scheduler decides ordering and merging. /sys/block/<dev>/queue/scheduler shows the choice in brackets: [none] mq-deadline kyber bfq. none is right for NVMe, whose hardware queues do their own ordering; mq-deadline bounds latency on SATA SSDs and spinning disks; bfq gives proportional fairness (and makes io.weight work) at a CPU cost. Deep queues (nr_requests) raise throughput and latency together.

iostat -xz 1 prints one line per active device; skip the first sample, which averages since boot. Read the columns as four questions: how many operations (r/s, w/s), how many bytes (rkB/s, wkB/s), how long each waits in total (r_await, w_await, in ms, including queue time), how deep the queue is (aqu-sz), and how busy the device is (%util). f/s and f_await count cache flushes, i.e. fsyncs reaching the device. A spinning disk saturates around a few hundred random IOPS and shows it as await in the tens or hundreds of milliseconds with %util at 100. An NVMe device can run at %util 100 while serving far more, because %util only measures time with at least one request outstanding and the device handles dozens in parallel; on parallel devices trust await and aqu-sz, not %util. The USE reading: utilization is %util (with that caveat), saturation is aqu-sz and await, errors are in dmesg and SMART.

Attribute I/O to a process with pidstat -d 1 or iotop, and to a cgroup with io.stat. Per-file, /proc/<pid>/io distinguishes bytes the process read through the cache (rchar) from bytes that hit the device (read_bytes). biolatency from BCC shows the latency histogram, which catches the bimodal pattern (fast cache hits, slow device reads) that averages hide.

LVM, RAID, and flash wear

LVM inserts a mapping layer: physical volumes (pvs) pool into a volume group (vgs) that is carved into logical volumes (lvs). Its operational value is growing a volume online: lvextend -r -L +200G /dev/vg0/data extends the LV and runs resize2fs or xfs_growfs in one step, no unmount. xfs cannot shrink; ext4 can shrink offline. Snapshots are copy-on-write and become invalid when their allocated space fills, so size them or use thin pools.

RAID trades capacity for redundancy. RAID 1 mirrors; RAID 10 stripes mirrors and is the choice for databases (random write cost of two writes, fast rebuild of one disk); RAID 5 and 6 store one or two parity blocks, cost a read-modify-write per small write, and rebuild by reading every remaining disk, which on large drives takes days during which a second failure (or an unrecoverable read error) loses the array. cat /proc/mdstat and mdadm --detail /dev/md0 show state; [U_] means degraded. RAID is availability, not backup: a deletion or corruption is mirrored instantly.

Flash wears by writes. A drive is rated in terabytes written (TBW) or drive writes per day (DWPD), and reports its state through nvme smart-log /dev/nvme0 or smartctl -a: percentage_used is the vendor's estimate of endurance consumed (it can exceed 100), data_units_written counts 512,000-byte units, available_spare is the reserve of replacement blocks, media_errors and critical_warning are the alarms. Write amplification multiplies host writes: small random writes, a nearly full drive with little room for garbage collection, and LSM-tree compaction (RocksDB-style state databases rewrite data many times) can turn 1 TB of application writes into 10 TB on the flash. Hosts with that profile need percentage_used trended, a replacement threshold, over-provisioning (leave 10–20% unpartitioned), periodic fstrim, and enterprise drives rated for the write volume.

Myths and facts

Myth: If df says there is free space, writes cannot fail with 'No space left on device'.

Fact: ENOSPC also comes from inode exhaustion (df -i), the root-reserved blocks, and quotas. df -h is one of three numbers to check.

Myth: Deleting a file frees its space.

Fact: Deleting a name frees space only when the last link and the last open descriptor are gone. An open, deleted file keeps its blocks; lsof +L1 finds it and truncating through /proc//fd frees it.

Myth: Once write() returns the data is on disk.

Fact: It is in the page cache. Only fsync/fdatasync (or O_SYNC) forces it to stable storage, and a new name is durable only after fsync of the directory.

Myth: %util at 100% means the disk is saturated.

Fact: It means at least one request was outstanding all the time. For parallel devices like NVMe that says nothing about headroom; await and aqu-sz show saturation.

Myth: The journal protects my data from a crash.

Fact: It protects filesystem metadata consistency. Unsynced data in the page cache is lost regardless of journaling mode.

Myth: RAID means I do not need backups, and an SSD with no errors is healthy.

Fact: RAID mirrors mistakes instantly and rebuilds are the riskiest window. Flash wears by write volume; percentage_used and available_spare predict failure long before media_errors do.

How pros do it

  • On ENOSPC run df -h, df -i and lsof +L1 before deleting anything; each names a different cause with a different fix.
  • Rotate logs with copytruncate or a reopen signal; never let a rotation scheme delete files that a process holds open.
  • Mount by UUID or LABEL, add nofail and x-systemd.device-timeout to every non-boot-critical mount, and use RequiresMountsFor in services that need a data volume.
  • Mount user-writable and untrusted filesystems with nodev,nosuid (and noexec where the workload allows); keep errors=remount-ro on ext4 roots.
  • Treat fsync as the durability boundary: write temp, fsync, rename, fsync directory; treat an fsync error as data loss, not a retry.
  • Read iostat -x as await and aqu-sz for saturation and %util only for single-queue devices; attribute I/O with pidstat -d and cgroup io.stat.
  • Trend percentage_used and available_spare on every flash device, alert at a replacement threshold, and enable fstrim.timer.

Questions people ask

du says 30 GB but df says 80 GB used on the same filesystem. Where is the rest?

In files that were deleted while a process still had them open, almost always a log removed by a rotation script. du walks names and cannot see an unlinked inode; df asks the filesystem for allocated blocks, which stay allocated until the last descriptor closes. lsof +L1 or a grep for '(deleted)' in /proc/*/fd names the holder, and truncating through /proc//fd/N frees the space without a restart. The caveat: a directory that had files written into it before something was mounted over it produces the same gap; findmnt rules it out.

Why does my host say the disk is full when df shows 60% used?

Most often inodes: df -i shows IUse% at 100 because millions of small files consumed ext4's fixed inode table. Otherwise the 5% root reserve (non-root writers fail at 95%) or a quota. The error string is the same for all three, which is why the first move is df -h, df -i and lsof +L1 rather than deleting anything. The caveat: ext4 cannot grow its inode table in place, so the fix is moving or deleting the small files, or recreating the filesystem with -i or -N; xfs allocates inodes dynamically and rarely hits this.

How do I tell whether a database's latency is the disk?

iostat -xz 1 for the device: await in the tens of milliseconds on flash, or aqu-sz climbing, is saturation whatever %util says. Confirm with /proc/pressure/io (or the cgroup's io.pressure) and biolatency for the distribution, then attribute the load with pidstat -d. The caveat: %util saturates at 100 on a single-queue disk but says nothing about headroom on NVMe, so quote await and queue depth, not %util.

Is fsync really necessary if the machine has a battery-backed RAID cache or an enterprise SSD?

Yes. fsync is what moves dirty pages from RAM to the device at all; the battery only protects data that has already reached the device cache. Power-loss protection makes the flush cheap, not unnecessary. The caveat: a rename is durable only after fsync of the directory, and an fsync error must be treated as data lost rather than retried, because the kernel marks the pages clean after reporting it once.

Can I grow a filesystem without downtime?

With LVM, yes: lvextend -r grows the LV and the filesystem online for ext4 and xfs. Without LVM you can grow a partition with growpart and resize2fs or xfs_growfs online, but only into free space directly after the partition. The caveat: shrinking xfs is impossible and shrinking ext4 needs an unmount, so size volumes to grow, never to shrink.

Which I/O scheduler should I pick?

none for NVMe, mq-deadline for SATA SSDs and most spinning disks, bfq when you need proportional fairness between cgroups or interactive latency on a slow disk. Set it with a udev rule so it survives reboot, not by hand in /sys. The caveat: with none on NVMe, cgroup io.weight does nothing unless io.cost is configured, so 'we set IOWeight' may be a no-op.

How fast will a busy NVMe drive wear out?

Take data_units_written times 512,000 bytes, divide by the drive's TBW rating, and compare with percentage_used; divide the remaining endurance by the write rate per day from two readings. Compaction-heavy databases can burn a consumer drive in months. The caveat: write amplification means the flash sees far more than the application writes, so trend the drive's own counters rather than the application's.

Further reading

Drills · 10

Answer in your head, or out loud, before you reveal. Mark each one: "Again" brings it back, "Got it" counts on your desk.

1 Pick the strongest answer

A write fails with No space left on device, but df -h shows the filesystem is only 40% full. What do you check next?

  1. The file exceeds the filesystem's maximum file size. That returns EFBIG, and modern filesystem limits are in terabytes.
  2. df is caching a stale value; remount to refresh it. df reads live values from statfs.
  3. df -i — the filesystem may have exhausted its inodes. Every file consumes one regardless of size, so millions of tiny files fill the inode table long before they fill the blocks. ENOSPC covers both out-of-blocks and out-of-inodes; df -h only shows the first.
  4. The disk is failing; check SMART data. A failing disk gives I/O errors, not ENOSPC.
In short

A filesystem can run out of inodes as well as space, and both give the same error, so run df -i too.

Why

This is a favourite because the error message points one way and the truth is elsewhere. The habit worth having: when ENOSPC and df -h disagree, run df -i before doing anything else.

The common mistake

Running only df -h, seeing plenty of space, and going to look for a hardware fault instead.

Read the docs

2 Scenario: what do you do next?

Alerts fire: / is at 100% on an application host and the service is throwing write errors. You have a shell. There is no immediate suspicion about which directory is responsible.

Step 1. First move?

  1. Delete everything in /var/log immediately to buy space. You may destroy the evidence of the incident you are being paged about, and if a process holds the files open you will not even get the space.
  2. Reboot to clear temporary files. It may free the space by killing the writer, and you will have no idea what happened.
  3. Extend the volume first and investigate later. Sometimes correct under pressure, but doing it before you know the cause means a runaway writer simply fills the new space too.
  4. Find the space before freeing anything: df -h to confirm which filesystem, df -i to rule out inodes, then du -xh / --max-depth=2 | sort -rh | head to walk down. -x keeps it on one filesystem so you are not measuring /proc and network mounts. Two commands separate the three causes (blocks, inodes, deleted-but-open) before you delete anything you cannot get back.

Step 2. du totals about 12 GB on a 100 GB filesystem, and df -i is fine. What now?

  1. Increase the filesystem's reserved-blocks percentage. That reduces usable space, making the problem worse.
  2. Run fsck on the root filesystem. It needs the filesystem unmounted or a reboot, and there is no evidence of corruption.
  3. Assume a hidden mount is masking a directory and unmount everything. Worth remembering as a rarer cause, but unmounting blindly on a production host is dangerous; check findmnt first.
  4. The space is in files that have been deleted but are still open. lsof +L1 names the holders; truncate through /proc/<pid>/fd/N for an immediate reclaim, or restart the holding process if truncating is not safe. du and df disagreeing, with inodes healthy, has essentially one cause.

Step 3. The service is healthy again. What do you leave behind?

  1. Add a cron job that deletes logs over 100 MB every hour. It will silently delete evidence during future incidents and does not fix the descriptor being held.
  2. Fix the rotation so the writer is signalled or the file is truncated in place, alert on disk usage at a level that gives hours of warning rather than at 100%, and add a growth-rate alert so a runaway writer is caught before the ceiling. The rotation bug is the cause; the two alerts turn the next occurrence into a warning instead of an outage.
  3. Double the disk and close the ticket. It buys time proportional to the leak rate and nothing else.
In short

Run df -h, df -i and du -x before freeing anything, use lsof +L1 to find the deleted-but-open files, then fix log rotation and alert before the disk is full.

Why

Disk-full is the most common on-call page there is, so interviewers expect a rehearsed, ordered method rather than improvisation. The sequence — confirm, classify, reclaim, then fix the cause — is the answer they are listening for.

The common mistake

Deleting logs first. It destroys the evidence, and if the writer still holds the file open it frees nothing at all.

Read the docs

3 Pick the strongest answer

You get paged: /var/log is at 94% in df -h, but du -sh /var/log reports 41 GB less than df's used figure. Nothing else is mounted under it. Where is the space and what is the fastest safe way to reclaim it?

  1. Hard links make du undercount; run du -l to count each link and the numbers will match. Hard links share one inode and one set of blocks; du counting them once is correct, and du -l would overcount rather than explain missing blocks.
  2. A process is holding a deleted file open, most likely a log removed by rotation; lsof +L1 (or (deleted) links in /proc/*/fd) names it, and truncating it through /proc/<pid>/fd/<n> returns the blocks without a restart. du walks names and cannot see an unlinked inode; df asks the filesystem for allocated blocks, which stay allocated while a descriptor is open.
  3. The ext4 journal is holding the space; increase the journal size or wait for a checkpoint. The journal is a fixed-size region reserved at mkfs; it does not grow with deleted files and it is already excluded from df's free count.
  4. The difference is the root reserve; run tune2fs -m 0 to get it back. The reserve is 5% and does not appear as used space; a 41 GB gap between du and df is allocated blocks with no name.
In short

A process still holds a deleted file open; lsof +L1 finds it, and truncating it through /proc//fd frees the space without a restart.

Why

unlink removes a name; the blocks are freed only when the link count reaches zero and the last open descriptor closes. Rotation scripts that rm a live log create exactly this: df keeps counting the blocks, du cannot find them, and the daemon keeps writing. Truncating through /proc/<pid>/fd/N is the immediate, reversible fix; the systemic fix is copytruncate or a reopen signal in logrotate. The signal interviewers want is knowing why du and df disagree, not just the command.

The common mistake

Restarting the service to free the space, or deleting more files. The first costs an outage you did not need; the second frees nothing if the holder is still open.

Read the docs

4 Pick the strongest answer

Quick one: ln app.log app.hard and ln -s app.log app.soft, then rm app.log. What happens when you open each of the two remaining names, and why?

  1. Both fail: removing the original name frees the inode and everything that referred to it. rm is unlink: it removes one name. The inode survives while any other name (or open descriptor) references it.
  2. The hard link breaks and the symlink works, because symlinks record the inode number and hard links record the path. It is the other way round: hard links are inode references, symlinks are paths.
  3. Both keep working: the kernel repoints the symlink at the hard link when the original name goes. A symlink stores a path string, not an inode number; nothing updates it when the target is renamed or removed.
  4. app.hard still opens the data: a hard link is a second directory entry for the same inode, so rm only dropped the link count from 2 to 1 and the blocks stay. app.soft fails with ENOENT: a symlink is its own small file holding the path app.log, and that path no longer resolves. Names live in directory entries and point at inodes; the inode and its blocks are freed only when the last name and the last open descriptor are gone.
In short

The hard link still opens the data, because it is another name for the same inode; the symlink dangles, because it only stored the path that was removed.

Why

This is the inode question in its most common interview form. The strong answer says 'a name is not the file' and reasons from the link count, then connects it to the deleted-but-open case, which is the same rule seen from the operations side.

Read the docs

5 Read the output

What is holding 44 GB, and what is the safest way to get it back right now?

$ df -h /var
Filesystem      Size  Used Avail Use% Mounted on
/dev/nvme0n1p2   50G   50G     0 100% /var

$ du -sh /var
6.2G    /var

$ sudo lsof +L1 /var 2>/dev/null | head -3
COMMAND    PID  USER   FD   TYPE DEVICE  SIZE/OFF NLINK     NODE NAME
app       9112   app    7w   REG  259,2 46203551744     0 13107201 /var/log/app/debug.log (deleted)
  1. The filesystem needs an fsck to reclaim orphaned blocks. Nothing is corrupt; the blocks are legitimately allocated to an open inode.
  2. A deleted debug.log the app still has open on fd 7. Truncate it in place with : > /proc/9112/fd/7 to reclaim the space immediately without restarting the service. NLINK 0 with a live descriptor is the signature; writing through /proc//fd truncates the same inode the process is holding.
  3. The page cache is holding the data; drop caches to release it. Page cache is memory, not disk blocks; dropping it frees no filesystem space.
  4. Delete /var/log/app/debug.log again. The name is already gone; there is nothing left to unlink.
In short

A deleted debug.log that the app still holds open on fd 7; truncate it with : > /proc/9112/fd/7 to free the space without a restart.

Why

Knowing that a full disk can be freed without a restart is genuinely useful, and it is the kind of detail that marks someone who has held a pager. The follow-up is always "and how do you stop it happening" — which is the rotation configuration, not the truncate.

Read the docs

6 Pick the strongest answer

A service writes a file, gets a successful return from write(), and the host loses power a second later. The file is empty on reboot. Is this a bug in the filesystem?

  1. Yes — write() is defined to return only after the data is on stable storage. That would make every write synchronous and unusably slow; POSIX explicitly does not promise this.
  2. No. A successful write() only means the data reached the page cache. Durability requires fsync() (and fsync on the parent directory for the name itself), and only then may the application report the write as committed. Write-back caching is the default because it is fast; the application chooses when it needs the guarantee.
  3. Only if the filesystem was mounted without the sync option, which should always be set in production. sync does force it, at a catastrophic cost to throughput; the right tool is a targeted fsync.
  4. No, and fsync would not help either; only a battery-backed controller can guarantee durability. Hardware caches matter, but fsync is the interface that pushes through them on any correctly behaving device.
In short

write() only puts your data in memory, and only fsync() makes it survive a power cut.

Why

This is the foundation under every storage question in a senior loop. Being able to say precisely what write() promises, what fsync() adds, and why the directory fsync matters puts you ahead of most candidates.

The common mistake

Believing a successful write() means the bytes are on the disk. It means they reached the page cache.

Read the docs

7 Read the output

A database's commit latency has jumped. Read this for me: which device is the problem, and what in this output says so?

$ iostat -xz 1 3          # third sample shown
Device     r/s   rkB/s  rrqm/s %rrqm r_await rareq-sz    w/s    wkB/s  wrqm/s %wrqm w_await wareq-sz   f/s f_await aqu-sz  %util
nvme0n1 1820.0 58240.0     0.0  0.00    0.21    32.00 6240.0 199680.0     0.0  0.00    0.34    32.00 142.0    1.12   2.65  61.20
sdb       38.0  4864.0     0.0  0.00   48.72   128.00  412.0  52736.0    96.0 18.90  212.41   128.00   0.0    0.00  89.41 100.00
  1. nvme0n1: 142 flushes per second means fsync is hammering it. f/s counts cache flushes from fsync; 142 per second completing in 1.12 ms is a database doing its job on a fast device.
  2. nvme0n1: it does 8,000 IOPS and 250 MB/s, far more than sdb, so it is the busy one. Throughput is utilization, not saturation; an NVMe device at 8k IOPS with 0.3 ms await has enormous headroom.
  3. Neither: sdb is only moving 52 MB/s, well under what any disk can do. A spinning disk saturates at a few hundred random IOPS regardless of bandwidth; 450 random IOPS with 128 KB requests and a 89-deep queue is exactly that.
  4. sdb: writes wait 212 ms on average and reads 49 ms, with an average queue of 89 requests and the device busy 100% of the time; that is a saturated spinning disk. nvme0n1 is healthy with sub-millisecond awaits, a short queue, and fsync flushes completing in ~1 ms. Saturation shows as await and aqu-sz; sdb's values are two orders of magnitude worse than nvme0n1's, and %util 100 on a single-queue disk confirms it.
In short

sdb is the problem: 212 ms write waits, a queue of 89 requests and 100% busy mean a saturated spinning disk, while nvme0n1 has sub-millisecond waits.

Why

Read iostat -x as utilization (%util, r/s, w/s, bandwidth), saturation (await, aqu-sz) and, elsewhere, errors. Saturation is what causes latency: sdb's 212 ms write await with a queue of 89 is a device that cannot keep up, while nvme0n1's numbers are those of a device with headroom no matter what %util says. The next steps are pidstat -d to find who is writing to sdb and moving the database's write path off it.

Read the docs

8 Find what's broken

After a maintenance window in which a disk controller was replaced, this host boots into emergency mode. Separately, a security scan flags that users can run setuid binaries from /tmp. Which two lines are responsible?

# /etc/fstab
UUID=3f1e8b9c-6d2a-4c1e-9a7f-0b3d5e8f1a2c  /                   ext4   errors=remount-ro                                    0 1
UUID=9A2C-1F3E                             /boot/efi           vfat   umask=0077                                           0 1
/dev/sdc1                                  /data               xfs    defaults,noatime                                     0 2
UUID=7b44d0e1-2f3a-4b5c-8d9e-1f2a3b4c5d6e  /var/cache/metrics  ext4   defaults,noatime,nofail,x-systemd.device-timeout=10  0 2
UUID=c0de1234-5678-4abc-9def-0123456789ab  /mnt/backup         ext4   defaults,nofail                                      0 2
tmpfs                                      /tmp                tmpfs  defaults,size=8G                                     0 0
/swapfile                                  none                swap   sw                                                   0 0
In short

Line 4 names the disk as /dev/sdc1 with no nofail, so a device name change breaks the boot, and line 7 mounts /tmp without nosuid,nodev.

What's broken
  • Line 4: The data volume is referenced by kernel device name (/dev/sdc1), which changed when the controller was replaced, and the line has no nofail; systemd waits for the device, the mount fails, local-fs.target fails, and boot drops to emergency mode.
  • Line 7: A world-writable tmpfs mounted with defaults allows setuid execution, device nodes and execution from /tmp.
Why

Device names are assigned in discovery order and change with hardware; fstab must use identifiers that live on the filesystem. Without nofail a missing mount is a hard dependency of local-fs.target, and that is the single most common reason a host lands in emergency mode after hardware work. Line 5 is the correct pattern for a non-critical volume, line 2's errors=remount-ro is the safe default for an ext4 root, and line 8 is an ordinary swap file. /tmp with defaults keeps suid and dev enabled on a filesystem anyone can write, which the nosuid,nodev options exist to prevent.

Read the docs

9 Scenario: what do you do next?

02:40. A payments API host pages with disk /var at 100%. The service is still serving but logs write /var/log/payments/app.log: no space left on device and its audit trail is silently dropping entries. df -h /var shows 100% used; df -i shows 12% inodes used. Another engineer on the call proposes rm -rf /var/log/* to buy room.

Step 1. What do you do first?

  1. Extend the logical volume by 50 GB with lvextend. Possible later, but you do not know yet whether the consumer is a runaway that will fill 50 GB in an hour.
  2. Restart the payments service to free whatever it holds. A restart on a payments host at 02:40 without knowing the cause drops traffic and may not fix anything; it is the last lever, not the first.
  3. Find where the blocks are before deleting anything: du -xsh /var/* | sort -h for the largest names, and lsof +L1 for deleted-but-open files, comparing the du total with df. The two commands split the possibility space: named files you can see versus unlinked files you cannot; deleting blindly may free nothing and destroys the audit trail you are trying to save.
  4. Run rm -rf /var/log/* now; logs are expendable. If the space is in an open deleted file this frees nothing, and it deletes the audit trail the incident is about.

Step 2. du sums to 9 GB on a 120 GB volume. lsof +L1 shows the payments process holding /var/log/payments/app.log.3 (deleted) at 108 GB, fd 12, opened in append mode; last night's logrotate used rm after the daemon failed to reopen. What is your mitigation?

  1. Truncate through the descriptor: : > /proc/<pid>/fd/12. Space returns immediately, the service keeps running, then confirm with df and that new audit lines are being written. Reversible, instant, no traffic impact; the file is a rotated log the process should not be writing to anyway.
  2. Delete app.log.1 and app.log.2 as well to free more space. They are tiny compared with the 108 GB phantom; you would be deleting evidence for no capacity.
  3. Restart the service so it drops the descriptor. It works, but it costs an outage on a payments path when a zero-downtime fix exists.
  4. Increase the ext4 reserved-blocks percentage so the service gets priority. Reserved blocks protect root's writes, not a service user's; and the volume is genuinely full of one file.

Step 3. Space is back and audit lines are flowing. What is the systemic fix you propose in the postmortem?

  1. Make rotation safe for this daemon (copytruncate, or a postrotate reopen signal that is verified in staging), alert on df-minus-du divergence and on deleted-but-open file size, and page on disk-full prediction rather than at 100%. Mechanisms that remove the failure mode, detect it early, and turn a 02:40 page into a daytime ticket.
  2. Double the size of /var on every host. A bigger volume fills more slowly with the same bug.
  3. Tell the team to check lsof after rotation. A reminder, not a mechanism; the next rotation will be run by someone who was not on this call.
In short

Find the space before deleting anything, truncate the deleted-but-open log through /proc//fd, then make log rotation signal or truncate the writer and alert on df-minus-du.

Why

Disk-full incidents on Linux have three shapes and one habit fixes all of them: compare df with du before deleting anything. Space that df sees and du cannot belongs to deleted-but-open files (lsof +L1 or /proc/<pid>/fd shows them; truncating or signalling the writer frees it). Space df reports as used with inodes exhausted (df -i) means millions of tiny files. Interviewers score the discipline of reading both numbers, mitigating without a restart, and proposing a mechanism (safe log rotation, prediction-based alerting) rather than a bigger disk.

10 Quick recall

df says the filesystem is full but du accounts for far less. What is the usual cause?

In short

A process still holds a deleted file open, so its blocks are not freed.

Accepted

a deleted file still held open by a process · deleted open file · deleted but open file descriptor

Why

Unlinking a file removes the directory entry, but the blocks are only freed when the last descriptor closes. du walks names and sees nothing; df counts blocks and sees it all. lsof +L1 lists the culprits, and restarting the holder returns the space instantly.

Read the docs

Next lesson Memory: RSS vs cache, the OOM killer, swap, and pressure
Drill · Filesystems and storage
0:00

Loading…