Sub topic 7
Why Inodes Run Out: Mail Queues, Session Files, and Caches
This chapter assumes you can read df and df -i output and run find and du under sudo. It also assumes you know that an inode is the record a filesystem keeps for each file or directory, and that a filesystem has a limited number of them. Here you will learn which workloads create millions of small files, how to confirm that one of them is the cause, and how to clean up and prevent a repeat.
The pattern behind inode exhaustion
A filesystem can refuse new files in two ways. Either it has no free blocks, or it has no free inodes. Inode exhaustion is the second case. df -h reports plenty of free space, but touch newfile fails with No space left on device.
Every file, directory, and symbolic link uses one inode, regardless of size. A workload that creates huge numbers of tiny files uses up inodes long before it uses up blocks. Three conditions usually combine:
- The software creates one file per item, such as one per message, session, or cached object.
- The files are small, so the block count stays low.
- Nothing removes old files, or the cleanup job has stopped working.
Small files still cost blocks. A file with 100 bytes of data occupies at least one block, typically 4 KiB. A million such files use about 4 GB of blocks, which is still modest on a large disk. The inode table is the limit that gets hit first.
Common sources
Mail queues
Mail transfer agents such as Postfix store each queued message as its own file. Postfix keeps them under /var/spool/postfix, in directories such as deferred, active, and incoming. Messages go into hashed subdirectories to keep each one small.
A mail queue grows fast when a server is misused as a spam relay, a local script sends error mail in a loop, or cron jobs mail their output to a mailbox no one reads. Messages that cannot be delivered are retried for days, so the queue keeps growing during that time.
Check the queue size before you delete anything:
postqueue -p | tail -n 1
sudo find /var/spool/postfix -xdev -type f | wc -lThe first command prints a summary line such as -- 48210 Kbytes in 120311 Requests. The second counts the files on disk. If the queue holds mail you must not lose, do not flush it blindly. Find out why it is growing first.
Session files
PHP stores each session as a file named sess_<id>. On Debian and Ubuntu these live in /var/lib/php/sessions. On other distributions the directory may be /var/lib/php/session or /tmp. A busy site, a crawler that ignores cookies, or a health check that opens a new session on every request can create hundreds of thousands of files in a day.
PHP's built-in garbage collection runs only with some probability on a request. It is often disabled in packaged setups, which use a scheduled job instead (on Debian and Ubuntu, a systemd timer or cron job named phpsessionclean). If that job fails or its session.gc_maxlifetime setting is too long, sessions pile up.
Other frameworks behave the same way when they use file-based sessions, for example storage/framework/sessions in a Laravel application.
Caches
Applications cache results as files because it is simple. Typical locations are:
- Application cache directories, such as Laravel's
storage/framework/cacheor a CMS'scache/directory. - Thumbnail and image-derivative caches generated on demand.
- Package manager caches, such as
~/.npm/_cacacheor/var/cache/apt. - Build tool and CI caches left behind in
/var/tmpor a workspace.
A cache that keys files by a hash of the request, including a query string a crawler can vary at will, can create a new file for every URL variation. Caches often have no expiry, because the code assumes someone else will clear them.
Other sources
Less common causes include the following:
- Container image layers and overlay directories under
/var/lib/docker. - Mail stored in the Maildir format (
~/Maildir), where each message is a file. - Monitoring or backup agents that write one small spool file per event.
- Core dumps and crash reports.
- Temporary files in
/tmpthat a crashed program never removed.
Confirming the diagnosis
Start with the inode view of every mount:
df -ihA filesystem at 100% in the IUse% column with space still free confirms the problem. Then find which directory holds the most entries. This loop counts entries under each directory in /var and prints the five largest:
for d in /var/*; do
printf '%s %s\n' "$(sudo find "$d" -xdev 2>/dev/null | wc -l)" "$d"
done | sort -n | tail -n 5Run it again one level down, on the directory that tops the list, and repeat until you reach the directory that holds the files. For example, if /var/spool leads, loop over /var/spool/* next.
Reproducing the failure safely
A loopback filesystem with a deliberately small inode table lets you see the symptom without touching a real server. This needs root and creates a 64 MB image file.
truncate -s 64M /tmp/inode-lab.img
mkfs.ext4 -q -F -N 2048 /tmp/inode-lab.img
sudo mkdir -p /mnt/lab
sudo mount -o loop /tmp/inode-lab.img /mnt/lab
sudo bash -c 'for i in $(seq 1 3000); do : > /mnt/lab/f$i || break; done'
df -h /mnt/lab
df -i /mnt/labThe loop stops partway with No space left on device. df -h shows almost all of the 64 MB free, while df -i shows IUse% at 100%. When you are done, run sudo umount /mnt/lab and rm /tmp/inode-lab.img.
Why the limit exists
How the limit works depends on the filesystem type:
| Filesystem | Inode allocation | What it means for you |
|---|---|---|
| ext4 | Fixed when the filesystem is created, commonly one inode per 16 KiB of space | You cannot add inodes later. Recovery means deleting files or recreating the filesystem with `mkfs.ext4 -i` or `-N`. |
| XFS | Allocated dynamically as needed, capped by a percentage of the disk (`imaxpct`) | Exhaustion is rare, but it can still happen on small filesystems with a low cap. |
| Btrfs | No fixed inode table | `df -i` shows `0` totals, so inode percentage checks are not meaningful. |
On ext4 you can see the inode count with sudo tune2fs -l /dev/sda1 | grep -i 'inode count'. Replace /dev/sda1 with your device. A volume created for a small root disk and later grown keeps the inode ratio set at creation. Check the inode count when you resize a volume that will hold small-file workloads.
Cleaning up
Deleting a huge number of files takes some care.
- Stop or pause the producer if you can, or it refills the space as you delete.
- Preview what will match before you delete anything.
- Delete by age, not everything, so that live sessions and in-flight messages survive.
Do not use rm /path/* on a directory with hundreds of thousands of entries. The shell expands the glob into more arguments than the kernel allows, and rm fails with Argument list too long. Use find, which handles the files itself:
sudo find /var/lib/php/sessions -type f -name 'sess_*' -mtime +1 -print | head
sudo find /var/lib/php/sessions -type f -name 'sess_*' -mtime +1 -deleteThe first command previews the first matches. The second deletes sessions not modified for more than a day. Choose an age at or above the application's session lifetime, so you do not log out active users.
For a mail queue, use the MTA's own tools, not rm, so its internal state stays consistent. For Postfix, postqueue -p lists the queue, and sudo postsuper -d ALL deferred deletes every deferred message permanently. Fix the cause of the queue (a compromised script, a bad relay setting) first, or it fills again within hours.
If the directory itself holds millions of entries, ls is very slow and sorts all names in memory. Use ls -f (which does not sort) or find instead.
Preventing a repeat
- Expire files automatically. Make sure the session cleanup job runs, set
session.gc_maxlifetimeto a sensible value, and give caches a time-to-live or a size limit. - Use a better backend. Move sessions and caches to Redis or Memcached, or to a database, where an entry is not a file.
- Use
systemd-tmpfiles. A rule in/etc/tmpfiles.d/can remove files older than a set age from a cache directory. For example,e /var/cache/myapp - - - 7dages out entries older than seven days. - Alert on inodes, not just space. The
check-disk.shscript from the threshold-alerting chapter warns on inode percentage as well as block percentage. - Give small-file workloads their own filesystem. A separate mount for
/var/spoolor an application's cache directory stops a runaway queue from filling the root filesystem. Create it with a higher inode count.
Exercise
A web server's root filesystem shows 41% used in df -h, but PHP reports No space left on device when it creates session files. df -i shows 100% inode use on /. Write the commands you would run to find the directory that holds the most files, and name one safe way to remove old session files.
Show answer
Run df -i to confirm the inode problem. Then count entries per directory with for d in /var/*; do printf '%s %s\n' "$(sudo find "$d" -xdev 2>/dev/null | wc -l)" "$d"; done | sort -n | tail -n 5, and repeat the loop one level down on the top result until you reach the directory (likely /var/lib/php/sessions). Preview old files with sudo find /var/lib/php/sessions -type f -name 'sess_*' -mtime +1 -print | head, then delete them with the same command ending in -delete instead of -print | head. Using an age filter keeps active sessions. Afterward, check that the session cleanup job is running.