How to Fix Linux ulimit: Too Many Open Files Error
In this tutorial, you'll learn about How to Fix Linux ulimit: Too Many Open Files Error. We cover key concepts, practical examples, and best practices.
Your application crashes with Too many open files or EMFILE — the process has reached the system limit on open file descriptors.
The Problem
java.io.IOException: Too many open files
Or:
socket: Too many open files
Or:
Error: EMFILE: too many open files, watch
Step-by-Step Fix
Step 1: Check current limits
ulimit -n
Expected for default:
1024
Step 2: Check hard and soft limits
ulimit -Sn # soft limit
ulimit -Hn # hard limit
Step 3: Check current open file count
# For a specific PID
ls -la /proc/<PID>/fd | wc -l
# For current user
lsof -u $USER | wc -l
Step 4: Increase limit temporarily
ulimit -n 65535
Step 5: Increase limit permanently for a user
Edit /etc/security/limits.conf:
user soft nofile 65535
user hard nofile 65535
Or for all users:
* soft nofile 65535
* hard nofile 65535
Step 6: Increase system-wide limit
sudo sysctl fs.file-max=2097152
Make permanent in /etc/sysctl.conf:
fs.file-max=2097152
Step 7: Apply changes
Re-login or:
sudo sysctl -p
Verify:
ulimit -n # should show 65535
Step 8: Configure for systemd services
For systemd services, add to the service unit:
[Service]
LimitNOFILE=65535
Then:
sudo systemctl daemon-reload
sudo systemctl restart myservice
Prevention Tips
- Set appropriate open file limits in provisioning scripts
- Monitor open file counts with
lsof - Fix file descriptor leaks in application code
- Close file handles, database connections, and sockets properly
- Set limits higher than expected peak usage
Common Mistakes with ulimit error
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world LINUX code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro