Video in progress

Strong Middle 📁 IO and NIO

"Too many open files" showed up on prod. How do you investigate and fix it?

First separate the cause: a real leak (the descriptor count grows steadily) or the limit simply being small (it climbs under load and then falls). With lsof//proc/<pid>/fd you see what is open, you fix a leak in the code, and you raise the limit through ulimit -n or the systemd/container settings.

📖 Answer

The steps; this is how I usually go:

  1. The current state and the limit:
ls /proc/$PID/fd | wc -l
grep "open files" /proc/$PID/limits
  1. What is open:
lsof -p $PID | awk '{print $5}' | sort | uniq -c | sort -rn   # by type: REG, IPv4, sock...
lsof -p $PID | grep REG | awk '{print $9}' | sort | uniq -c | sort -rn | head

If the same file is open hundreds of times, there is a stream in the code that isn't closed. If there are many CLOSE_WAIT sockets, the HTTP client isn't closing the response body or isn't returning the connection to the pool.

  1. The trend over time. Micrometer provides the process.files.open and process.files.max metrics. A sawtooth on the graph is load; steady growth is a leak.

Common causes:

  • Files.lines/Files.list not closed;
  • in RestTemplate/HttpURLConnection, the error response stream isn't read and closed;
  • creating a new HttpClient or OkHttpClient on every request;
  • deleted but still open log files (lsof | grep deleted): the disk fills up too.

For the limit: LimitNOFILE=65536 in systemd, --ulimit nofile=65536:65536 in Docker. But if there is a leak, raising the limit only delays the crash.