Video in progress

When load goes up, the log shows a "Too many open files" error. How do you find the cause?

The process has run out of its file descriptor limit: on Linux, sockets, files and pipes are all descriptors. First I check the limit and the current count, then look at what they are with lsof and work out whether there is a leak or the limit is simply small.

📖 Answer

PID=$(pgrep -f shop-api.jar)
cat /proc/$PID/limits | grep "open files"   # soft and hard limit
ls /proc/$PID/fd | wc -l                     # how many are open now
lsof -p $PID | awk '{print $5}' | sort | uniq -c | sort -rn   # by type
lsof -p $PID -a -i TCP | grep CLOSE_WAIT | wc -l

Typical findings:

  • the limit is 1024, the default on many distros. That is far too little for a service with hundreds of connections. For a systemd service use LimitNOFILE=65536, in Docker --ulimit nofile=65536:65536. In Kubernetes the limit comes from the container runtime settings;
  • thousands of sockets in CLOSE_WAIT: this is definitely a bug in the code. The other side closed the connection and the app did not close its side. Often an HTTP client drops the response body without reading or closing it;
  • the number keeps growing as time passes: a Files.lines(), InputStream or JDBC resource was opened without try-with-resources.
// leaks: the stream is never closed
long n = Files.lines(path).count();

// correct
try (var lines = Files.lines(path)) {
    long count = lines.count();
}

Do not stop at raising the limit: if the number keeps growing, even 65 thousand will run out one day. The JVM itself also exposes process_files_open_files and process_files_max_files in metrics, and it is useful to set an alert on them.