Linux Tips guides, explanations and reader checklists on whilenetworking.com

Troubleshooting Slow Filesystem Performance: Analyzing Inodes with ‘inotifywait’

When a Linux system exhibits sluggish file access speeds, the issue is rarely just disk I/O or RAM exhaustion. Often, the culprit lies in inode exhaustion or…

When a Linux system exhibits sluggish file access speeds, the issue is rarely just disk I/O or RAM exhaustion. Often, the culprit lies in inode exhaustion or filesystem metadata contention. While df -i provides a snapshot of available inodes, it does not reveal which processes are actively spawning files at a rate that overwhelms the filesystem’s ability to track them. This is where inotifywait, part of the inotify-tools package, becomes an indispensable diagnostic tool. By monitoring file system events in real-time, administrators and developers can identify runaway applications or misconfigured services creating excessive files, leading to performance degradation.

This guide walks you through a realistic troubleshooting scenario where a web server’s /var/www/uploads directory begins stalling under load. We will use inotifywait to capture the specific process responsible for the inode churn, analyze the filesystem state, and apply corrective measures safely.

Understanding Inode Pressure and Real-Time Monitoring

Before diving into commands, it is crucial to understand what you are measuring. An inode is a data structure on a Linux filesystem that stores metadata about a file—such as its size, ownership, permissions, and timestamp—but not the filename itself. Every file, including directories themselves, consumes one inode. When a directory fills up with files but still has free disk space (bytes), it reaches “inode exhaustion.”

However, performance issues often occur before total exhaustion. If a process creates thousands of small temporary files per second, the VFS (Virtual File System) layer spends excessive time updating in-memory inode lists and flushing metadata to disk. This causes latency even if df shows 90% inode usage remaining.

inotifywait allows you to attach a listener to a specific directory. It reports events like CREATE, MODIFY, or DELETE. By filtering these events, you can pinpoint exactly which PID (Process ID) is triggering the high-frequency file creation that is choking your system.

Prerequisites and Environment Setup

To follow along with this lab scenario, ensure your environment meets the following requirements:
* Operating System: Any modern Linux distribution (Ubuntu, Debian, CentOS, RHEL).
* Package Installation: inotify-tools must be installed. On Debian/Ubuntu, run sudo apt update && sudo apt install inotify-tools. On RHEL/CentOS/Fedora, use sudo dnf install inotify-tools or sudo yum install inotify-tools.
* Permissions: You generally need root privileges to monitor system directories like /var, but for this lab, we will create a safe, isolated test directory (/tmp/inode-lab) where you have write permissions.

Scenario: Identifying the File Creation Storm

Imagine a junior engineer reports that the web server’s upload directory is unresponsive. Users experience timeouts when uploading images because the filesystem is lagging. The df -h command shows ample disk space, but df -i indicates inode usage is climbing rapidly (e.g., 85% used).

The goal is to identify the application generating this noise without killing critical services prematurely. We will set up a monitoring session on our test directory /tmp/inode-lab.

Step 1: Initialize the Monitor

Open a terminal and start inotifywait in watch mode with verbose output. This command listens for any file creation event and prints the process name, PID, and the specific file path.

# Start monitoring the test directory
sudo inotifywait -m -r -e create /tmp/inode-lab --format '%T %e %w%f by %e' &

Explanation of flags:
* -m: Monitor mode (continuous listening).
* -r: Recursive monitoring (watch subdirectories too).
* -e create: Only report file creation events to reduce noise.
* --format: Customizes the output to show timestamp, event type, file path, and process name.
* &: Runs the command in the background so you can continue working in the terminal.

Step 2: Simulate the Problem

In a real workplace scenario, this might be triggered by a misconfigured backup script or a buggy application writing logs to the wrong location. In our lab, we will simulate a “bad actor” using a simple loop that creates files rapidly. This mimics a memory leak in an application that spawns subprocesses which then create temp files.

In another terminal window (or a new tab), run this simulation script:

# Simulate high inode usage by creating 10,000 files quickly
for i in {1..10000}; do touch /tmp/inode-lab/file_$i.tmp; done

Step 3: Analyze the Output

Return to your first terminal. You will see a stream of output resembling the following illustrative example:

2023-10-27 14:05:01.123 CREATE /tmp/inode-lab/file_9821.tmp by (unknown)
2023-10-27 14:05:01.124 CREATE /tmp/inode-lab/file_9822.tmp by (unknown)
...
2023-10-27 14:05:02.050 CREATE /tmp/inode-lab/file_10000.tmp by python3

In this example, the loop might appear as (unknown) or bash, but in a production environment with specific software, you might see node, java, mysqld, or a custom script name. The key insight is that inotifywait isolates the source of the event. If the process name is consistent (e.g., always postgres), you know exactly which service to investigate in /var/log/syslog or via ps aux.

Verifying Filesystem State and Cleanup

Once the culprit is identified, do not immediately halt the process if it is a critical system service. Instead, analyze the impact. Run df -i /tmp/inode-lab to confirm inode usage has spiked.

If the files are temporary (like .tmp), the immediate fix is often cleanup. However, simply deleting them might not resolve the underlying bug causing the creation.

Safe Cleanup Procedure:
1. Identify the process ID (PID) from the inotifywait output.
2. Check what the process is doing: ps -p <PID>.
3. If it is a runaway loop or test script, terminate it gracefully: kill <PID>.
4. Clean up the files: sudo rm /tmp/inode-lab/*.

Common Errors and Fixes:
* Error: inotifywait: no such directory
* Fix: Ensure the directory exists (mkdir -p /path) and that you have permissions to write to it.
* Error: Permission denied when monitoring /var/log
* Fix: Use sudo or monitor a user-writable subdirectory instead of core system logs unless you are an administrator.
* Output too fast: If the terminal scrolls faster than you can read, add --show-current-time and reduce verbosity, or pipe the output to a log file: inotifywait ... > /var/log/inode-watch.log 2>&1.

Student Practice Task: The Debugging Challenge

To reinforce these skills, here is a practical task for students or junior engineers.

Task: Create a directory /home/student/test-inodes. Write a Python script that creates a file every 50 milliseconds for 10 seconds. In a separate terminal, use inotifywait to capture the event stream.
Goal: Calculate the files-per-second rate from your log and identify if the process name matches the Python interpreter running your script.
Deliverable: A brief report noting the PID of the writer and the estimated inode creation rate.

Industry Application: Production Logging Best Practices

In a production environment, the most common cause of inode exhaustion is misconfigured logging. Applications often write to /var/log or shared mount points instead of rotating logs properly.

Checklist for Preventing Inode Issues:
* [ ] Verify that rsyslog or journald rotation policies are active (/etc/logrotate.conf).
* [ ] Ensure applications do not append to log files without truncation or rotation.
* [ ] Monitor high-traffic directories with inotifywait during stress tests before going live.
* [ ] Use find with -delete on temp directories (e.g., /tmp) periodically if they are not cleaned by cron.

Conclusion

Slow filesystem performance is often a symptom of metadata overload rather than disk space issues. By leveraging inotifywait, you gain the ability to observe file system events in real-time, isolating the specific processes responsible for inode churn. This approach moves troubleshooting from guessing based on high-level metrics like CPU load to precise forensic analysis at the filesystem level. Remember to always verify process ownership before terminating services and to implement robust log rotation policies to prevent future recurrence.

Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.