Skip to content
Loopedin Labs

Too many open files (EMFILE)

Your server stops accepting connections, and the logs blame files.

Mini Rush · practice

Three questions before you read

Guessing first makes the answers stick. No sign-in.

Raising the limit is sometimes right. Check whether the count levels off first.

What it means

Every open file, socket, pipe, eventfd and epoll instance uses one file descriptor. A process can hold only as many as its RLIMIT_NOFILE soft limit allows. Past that, open(), socket() and accept() fail with EMFILE, "Too many open files". Servers usually hit this through sockets: each client connection, upstream connection and DB pool slot is an fd.

There are three levels:

LimitScopeError
soft nofileper process, which can raise it up to the hard limitEMFILE
hard nofileper process ceiling, capped by fs.nr_openEMFILE
fs.file-maxwhole systemENFILE "in system"

Debug commands

pid=$(pgrep -f myapp | head -1)
grep 'open files' /proc/$pid/limits      # soft and hard limits in effect
ls /proc/$pid/fd | wc -l                  # descriptors open right now
sudo lsof -p $pid | awk '{print $5}' | sort | uniq -c | sort -rn   # by type
ss -tanp | grep "pid=$pid," | awk '{print $1}' | sort | uniq -c    # TCP states
cat /proc/sys/fs/file-nr                  # system-wide: allocated, 0, max

To tell a leak from real load, run the count every minute. If it tracks traffic and levels off, it's load. If it climbs and never drops, something is leaking.

Where to raise it

Where you set the limit depends on what starts the process.

systemd service (limits.conf doesn't apply):

sudo systemctl edit app
# [Service]
# LimitNOFILE=65535
sudo systemctl daemon-reload && sudo systemctl restart app

Login shells and cron, through pam_limits in /etc/security/limits.conf:

appuser  soft  nofile  65535
appuser  hard  nofile  65535

Docker:

docker run --ulimit nofile=65535:65535 myimage

In Kubernetes, pods inherit the container runtime's defaults, and the pod spec has no field to set them. Change the runtime's settings on the node, or raise the soft limit inside the entrypoint, up to the hard limit.

Leaks to look for

  • Many CLOSE_WAIT sockets: the peer closed and your code never called close(). Common causes are unread or unclosed HTTP response bodies, and connections skipped on error paths.
  • Files opened in a loop without with, try-with-resources or defer f.Close().
  • A new HTTP client or DB pool created for every request instead of being reused.

Common wrong fix

Setting nofile to a million and moving on. If the count only ever climbs, a higher limit just delays the crash from hours to days, and each leaked socket still holds kernel memory and a slot on the other end. Raise the limit when real concurrency needs it. When the graph only goes up, fix the leak.