Explaining Disk Usage Discrepancies Between df and du
System DesignModel answerLast updated
Analyze why df and du report different disk space utilization on Linux systems and walk through a step-by-step troubleshooting process.
You are an SRE on call for a high-traffic production system. An alert triggers showing that the primary partition (/) on a database worker node has reached 98% storage capacity according to df -h.
When you log into the machine and execute du -sh /*, the total calculated space across all top-level directories is vastly smaller than the space marked as used by df.
Address the following:
- Underlying Architecture: Explain how
dfandduretrieve space allocation data at the kernel and VFS/filesystem levels, and why their data sources differ. - Root Causes: Identify the primary operating system mechanisms and scenarios that lead to large discrepancies between these commands.
- Investigation Workflow: Outline a non-disruptive, step-by-step diagnostic process to pinpoint the exact source of missing space on a running system.
- Remediation & Hazards: Describe how to reclaim storage safely without causing service downtime or data corruption, highlighting commands or actions to avoid.
Hints
Hint 1
Consider what happens to a file's underlying blocks when a path entry is deleted via unlink() while a process still maintains an active file descriptor.
Hint 2
Think about how mounting a block device over a non-empty directory affects file visibility during directory tree walks.
Hint 3
Differentiate between the used block count reported by superblock structures and total disk capacity adjusted for reserved system blocks.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Architectural Difference: How df and du Work
The divergence between df and du stems from how each tool queries the VFS (Virtual Filesystem) layer:
-
df(Disk Free): Queries the filesystem metadata directly by issuing thestatvfs()orstatfs()system call. The filesystem superblock maintains aggregate counters of total allocated data blocks, free blocks, and inodes.dfcomputes usage as: $$\text{Used Blocks} = \text{Total Blocks} - \text{Free Blocks}$$ Becausedfinspects low-level block allocation maps, it counts every allocated block on the storage device, regardless of whether those blocks have valid names in the directory tree. -
du(Disk Usage): Performs a user-space directory tree traversal (usinglstat()/fstatat()). It aggregates thest_blocksattributes of reachable directory entries, taking care to count unique inodes only once to handle hard links properly. Becausedurelies entirely on namespace traversal, it can only report on blocks linked to accessible directory paths.
Primary Causes of Discrepancies
1. Unlinked Files Kept Open by Processes (Deleted-but-Open Files)
When a file is deleted via rm or unlink(), the operating system removes the directory entry pointing to the inode and decrements the inode's hard link counter (i_nlink). However, POSIX semantics dictate that a file's data blocks are not returned to the free block pool until both of the following conditions are met:
i_nlink == 0(no path references exist).open_ref_count == 0(no active file descriptors reference the inode).
If an active process (such as a database engine or log generator) maintains an open handle to a deleted file, the space remains allocated:
ducannot see the file because its directory entry is gone.dfincludes these blocks because the filesystem superblock still marks them as in-use.
2. Hidden Files Behind Mount Points
If data was written to a path (e.g., /var/log) before another partition or volume was mounted over that directory, the underlying files become obscured by the overlay mount.
- Standard
duscans traverse into the mounted filesystem, missing the underlying storage consumption on the parent partition (/). dffor the root filesystem (/) continues to count the obscured blocks allocated on its block device.
3. Execution Scope and Permission Deficits
- Missing Root Permissions: Running
duas a non-root user silently fails (or emits errors ignored via2>/dev/null) when trying to read restricted directories like/root,/var/spool/rsyslog, or/proc. Unchecked permission errors causeduto underestimate total usage. - Crossing Filesystems: Running
du -sh /*without restricting the search to a single filesystem causesduto traverse into virtual file systems (/proc,/sys) and secondary mounts (/mnt,/data), distorting calculations.
4. Filesystem-Specific Features and Accounting
- Reserved Blocks (e.g., ext4): By default,
ext4reserves 5% of blocks forrootto prevent total system deadlock and reduce fragmentation. Reserved blocks affect the Percentage Used calculation indf(Used / (Used + Available)), but do not add to the absolute "Used" block count. - Copy-on-Write (CoW) & Metadata: Filesystems like Btrfs or ZFS use snapshots, inline extents, and compression. Here, summing individual file sizes with
duwill rarely match overall block pool allocations reported bydf.
Safe Diagnostic Workflow
To diagnose a live production host safely without causing service interruptions, execute the following commands in order:
Step 1: Establish Baseline & Rule Out Inode Exhaustion
Check both block usage and inode allocation:
df -hT /
df -i /
If inode usage (df -i) is at 100%, applications will fail with No space left on device even if block usage (df -h) has remaining capacity.
Step 2: Measure True Filesystem Usage as Root
Execute du constrained strictly to the target filesystem (-x) using low priority to prevent I/O saturation:
sudo nice -n 19 ionice -c 3 du -xsh / 2>/tmp/du_errors.log
Check /tmp/du_errors.log to verify no directories were skipped.
Step 3: Identify Open Unlinked Files
Find deleted files held open by active processes using lsof or by searching /proc:
# Option A: lsof looking for deleted files with link count of 0
sudo lsof +L1 /
# Option B: Direct /proc inspection (faster on systems with massive PID counts)
sudo find /proc/[0-9]*/fd -lname "* (deleted)" -ls 2>/dev/null
Look for large file descriptors associated with daemons (e.g., java, mysqld, nginx).
Step 4: Expose Obscured Mount Points
If deleted-open files do not explain the gap, inspect the root filesystem beneath existing mount points using a bind mount:
# Create a temporary view of the raw root filesystem without child mounts
sudo mkdir -p /mnt/raw_root
sudo mount --bind / /mnt/raw_root
# Scan the raw filesystem to find shadowed data
sudo du -xsh /mnt/raw_root/* | sort -h | tail -n 10
# Clean up
sudo umount /mnt/raw_root
sudo rmdir /mnt/raw_root
Remediation Strategies and Precautions
Once open deleted files are identified:
Preferred Method: Application-Aware Re-open
- Trigger a graceful reload signal (
SIGHUPorsystemctl reload <service>) so the application closes its existing file handles and opens fresh log files.
Emergency Method: Live Truncation via /proc
If restarting the application would cause unacceptable downtime, truncate the open file descriptor directly through the /proc virtual filesystem:
# Syntax: > /proc/<PID>/fd/<FD_NUMBER>
# Example: Truncate file descriptor 4 of process 1234
sudo truncate -s 0 /proc/1234/fd/4
# Alternatively, using shell redirection:
sudo sh -c '> /proc/1234/fd/4'
This instantly frees the underlying data blocks on disk without breaking the application's active file descriptor.
Common Pitfalls to Avoid:
- Never use
kill -9immediately: Forcefully killing a process with open handles can skip database crash recovery flushes or corruption guards. - Do not attempt to
rmthe file entry again: The filename is already removed from the namespace; callingrmagainst/proc/$PID/fd/$FDwill fail or destroy the file descriptor reference needed for live truncation. - Avoid aggressive unmounting (
umount -for-l): Force unmounting live production mount points can corrupt underlying filesystems or freeze dependent application threads.