The “Too many open files” error is a frequent stumbling block for Linux system administrators, database developers, and backend engineers. It typically manifests when an application attempts to open a file descriptor that exceeds the limit imposed on either the individual process or the entire system. Unlike generic out-of-memory errors, this issue stems specifically from resource exhaustion at the socket or inode level. To resolve it effectively, you must understand the distinction between soft limits (enforced per process via ulimit) and hard limits (system-wide caps), as well as filesystem-specific constraints like fs.file-max. This guide provides a step-by-step approach to diagnosing and fixing these errors in production environments without disrupting service availability.
Understanding the Three Layers of File Descriptor Limits
Before applying fixes, it is crucial to recognize that Linux enforces three distinct layers of limits. Confusing these layers often leads to premature solutions or missed root causes.
- Process Soft Limit (
ulimit): This is the maximum number of open file descriptors a specific user process can have. It acts as a safety valve for individual applications. - System Hard Limit (
fs.file-max): This defines the total number of file descriptors allowed across the entire kernel. Even if every process has a low limit, the system will reject new connections once this global cap is reached. - Filesystem Inode Limits: While less common for standard “too many open files” errors, some filesystems or mount options may restrict inode usage, indirectly affecting file handling capabilities.
When an error occurs, checking which layer is breached is the first diagnostic step. You can identify the current process limit using the ulimit command in your shell. Note that this only shows the limit for your current session; it does not reflect system-wide settings.
Diagnosing the Source of the Error
To troubleshoot effectively, you must determine whether the issue is isolated to a single application (e.g., MySQL, Nginx) or if the entire system is saturated. The most reliable method is to inspect open file descriptors for specific processes using lsof or /proc.
Run the following command to list all processes sorted by the number of open files:
ps -eo pid,comm,rss --sort=-%O | head -n 20
# Note: The %O column shows open file count if available in your ps version.
# A more robust method using lsof:
lsof +c1 | awk '{print $9}' | sort -rn | uniq -c | sort -rn | head -n 10
In an illustrative output, you might see a process like mysqld holding 45,000 open files while the system limit allows only 42,000. Alternatively, if all processes have low counts but connections are still failing, the issue likely lies with the kernel’s fs.file-max.
Adjusting Process Limits via ulimit and Configuration Files
For most applications, the immediate fix involves raising the soft and hard limits for the user running the service. The standard practice is to set both the soft limit and the hard limit to the same value to prevent the shell from automatically capping the soft limit below the hard limit.
Step 1: Modify System-Wide User Limits
Edit the /etc/security/limits.conf file. Add the following lines at the end of the file, replacing youruser with the actual username (e.g., mysql, nginx, or a dedicated service user):
# Set soft and hard limits for specific users
youruser soft nofile 65535
youruser hard nofile 65535
Explanation: The nofile keyword refers to open file descriptors. Setting both values ensures the application can request up to 65,535 files without hitting a soft limit wall.
Step 2: Verify and Apply in Current Session
If you are testing on your own machine or logging into a server as root, you can apply these changes immediately for your current shell session using the ulimit command:
ulimit -n 65535
ulimit -S n 65535 # Set soft limit
ulimit -H n 65535 # Set hard limit
Expected Result: Running ulimit -n should now return 65535. If you are managing a service like MySQL, remember that changes to /etc/security/limits.conf only take effect upon the next service restart or user login. You must edit the specific service configuration file (e.g., /etc/my.cnf) and add:
[mysqld]
open_files_limit = 65535
Raising System-Wide Kernel Limits
If individual process limits are not the culprit, or if you have raised them but still hit a ceiling, the kernel’s global file descriptor limit is likely the bottleneck. This setting is controlled by the fs.file-max parameter.
Step 1: Check Current System Limit
Use the following command to view the current system-wide limit:
cat /proc/sys/fs/file-max
Illustrative Output: 2097152. While this number seems high, it is often shared among thousands of processes. If your application expects exclusive access or if many lightweight connections are open (e.g., in a high-concurrency web server), you may need to increase this dynamically.
Step 2: Apply Temporary Changes
To make changes without rebooting, use the sysctl command:
sysctl -w fs.file-max=2097152
Note: These changes persist only until the next reboot. For production environments, you must add this to your persistent configuration file /etc/sysctl.conf.
Step 3: Make Changes Persistent
Edit /etc/sysctl.conf and append the line:
fs.file-max = 2097152
After saving the file, apply the changes immediately with sysctl -p. This reloads all parameters defined in that file. Verify the new value using cat /proc/sys/fs/file-max again.
Verifying and Monitoring File Descriptor Usage
Increasing limits is not a “set and forget” task; continuous monitoring is essential to prevent future outages. You should establish a baseline for normal usage versus peak usage.
Practical Verification Steps
- Check Process Limits: Ensure the service user has the correct limits by running
ulimit -nafter logging in as that user. - Monitor Real-Time Usage: Use
lsofor/proc/<pid>/fdto track open files during peak load periods. - Review Logs: Check application logs (e.g.,
/var/log/mysql/error.logor Nginx error logs) for messages indicating “Too many open files” before the actual crash occurs.
Common Mistakes and Fixes
- Mistake: Editing
limits.confbut restarting the service as root instead of the specific user.- Fix: Ensure the service is started under the configured user (e.g.,
systemctl restart mysqlruns as themysqluser). Re-check/etc/passwdand/etc/groupto confirm ownership.
- Fix: Ensure the service is started under the configured user (e.g.,
- Mistake: Increasing limits but failing to reload systemd unit files that might have hardcoded resource constraints.
- Fix: Check the service unit file (e.g.,
/etc/systemd/system/mysqld.service) for anyLimitNOFILE=directives and remove or update them if necessary, then runsystemctl daemon-reexec.
- Fix: Check the service unit file (e.g.,
Student Practice Task: Simulating a High-Load Scenario
To solidify your understanding, try this exercise in a safe lab environment (such as a virtual machine):
- Create a simple script that opens files sequentially to simulate a leak or high demand.
bash
#!/bin/bash
for i in {1..100}; do
open_file="/tmp/test_$i"
echo "test content $i" > "$open_file"
sleep 0.1
done - Run the script and check your limit:
ulimit -n. If it returns a low number (e.g., 1024), you will hit the error quickly if you modify the logic to hold files open longer. - Adjust your limits as described above and re-run the simulation. Observe how the behavior changes once the limit is raised.
Conclusion
Resolving “Too many open files” errors requires a systematic approach that distinguishes between process-specific constraints and kernel-wide caps. By adjusting ulimit in /etc/security/limits.conf, updating application-specific configurations, and raising the system’s fs.file-max, you can ensure your Linux infrastructure handles high-concurrency workloads reliably. Remember to always verify changes in both temporary and persistent contexts, and monitor usage patterns to prevent future exhaustion. As with any system configuration, always test these changes in a non-production environment first to avoid unintended side effects on dependent services.
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.

