The symptom and the explanations#
The example is fictional. From 09:40 UTC the thumbnailer service logged OSError: [Errno 24] Too many open files on about 3% of requests, on every instance. grep 'Max open files' /proc/PID/limits showed a soft limit of 1,024. Three explanations fit:
- Descriptors leak. Release
v3.8, deployed at 07:15, added a code path that writes a temporary file per request. If some path never closes it, every request served leaves a descriptor behind. - Concurrency outgrew the limit. A partner began bulk uploads at 09:30 over long-lived connections. Each open connection holds a socket, and a few hundred of them, plus each request's files, can reach 1,024 with nothing leaked.
- The limit fell.
v3.8also moved to a new base image and service unit. If the old unit setLimitNOFILE=65536and the new one sets nothing, the same load now meets a lower limit.
RLIMIT_NOFILE is one more than the highest descriptor number a process may open, and a call that needs a descriptor beyond it, such as open(2) or accept(2), fails with EMFILE. getrlimit(2) · open(2) · accept(2) The error rate rose under all three, so the error rate cannot choose. Choose the observation where explanations disagree
What each explanation predicts#
| Observation | Leak | Concurrency | The limit fell |
|---|---|---|---|
EMFILE errors | rise | rise | rise |
| Open descriptors at steady request rate | climb | flat | flat |
| Open descriptors against established connections | gap widens | track each other | track each other |
| Open descriptors after load drops | stay high | fall | fall |
| Kind of descriptor that grows | one kind, often files, pipes or CLOSE-WAIT sockets | sockets | the usual mix |
Max open files against last week | same | same | lower |
The third and fourth rows separate the leak from the other two: a leaked descriptor belongs to no request, so it survives the request and the connection. The last row splits concurrency from a changed limit. A graph of process_open_fds alone looks the same under all three for the first hours, because it rises whenever traffic rises.
A socket that the peer has closed and the application has not sits in CLOSE-WAIT, the TCP state that waits for the local user to close. RFC 9293 A growing count of them is a leak of sockets that shows in ss without reading the code.
The lab: a leak and a crowd under the same limit#
The script runs a small TCP server whose descriptor limit is 64. A child process, with its own limit, plays the clients. In the leak world, four connections at a time carry eight requests per step, and each request opens a file it never closes. In the busy world nothing leaks, and ten more clients connect at every step. It needs Python 3.8 or later on Linux.
import collections, os, resource, socket, sys
if len(sys.argv) < 2 or sys.argv[1] not in ("leak", "busy"):
sys.exit("usage: python3 fds.py leak|busy")
world = sys.argv[1] # "leak" or "busy"
srv = socket.create_server(("127.0.0.1", 0))
port = srv.getsockname()[1]
# The load generator is a child process with its own descriptors. It reads one
# byte per command: "+" opens a connection to the server, "-" closes the oldest.
r, w = os.pipe()
if os.fork() == 0:
os.close(w)
conns = collections.deque()
while (c := os.read(r, 1)) != b"":
if c == b"+":
conns.append(socket.create_connection(("127.0.0.1", port)))
else:
conns.popleft().close()
os._exit(0)
os.close(r)
resource.setrlimit(resource.RLIMIT_NOFILE, (64, 64)) # the server's limit, like `ulimit -n 64`
open_conns, leaked = collections.deque(), []
def connect():
os.write(w, b"+")
open_conns.append(srv.accept()[0])
def disconnect():
os.write(w, b"-")
open_conns.popleft().close()
def handle():
if world == "leak":
leaked.append(open("/etc/hostname")) # reads a file per request and never closes it
def fds():
# readlink needs no descriptor of its own, so this still works at the limit.
# Descriptors 0 to 2 (the terminal) are left out.
kinds = collections.Counter()
for fd in range(3, 64):
try:
target = os.readlink(f"/proc/self/fd/{fd}")
except FileNotFoundError:
continue
kinds["file" if target.startswith("/") else target.split(":")[0]] += 1
return f"fds {sum(kinds.values()):2d} (socket {kinds['socket']:2d}, file {kinds['file']:2d})"
served = 0
for step in range(1, 11):
try:
if world == "leak": # 4 connections at a time, 8 requests per step
for _ in range(4): connect()
for _ in range(8): handle(); served += 1
else: # 10 more concurrent connections per step
for _ in range(10): connect(); handle(); served += 1
status = "ok"
except OSError as e:
status = e.strerror
print(f"step {step:2d}: served {served:3d} connections {len(open_conns):2d} {fds()} {status}")
if world == "leak":
while open_conns: disconnect()
if status != "ok":
break
while open_conns: disconnect()
print(f"load stopped: connections 0 {fds()}")
Save it as fds.py. Before running python3 fds.py leak and python3 fds.py busy, write down the prediction: in leak, descriptors climb by eight per step while connections stay at four, and stay up when the load stops; in busy, descriptors stay two above the connection count and fall to two when the load stops. Python 3.11 printed:
step 1: served 8 connections 4 fds 14 (socket 5, file 8) ok
step 2: served 16 connections 4 fds 22 (socket 5, file 16) ok
step 3: served 24 connections 4 fds 30 (socket 5, file 24) ok
step 4: served 32 connections 4 fds 38 (socket 5, file 32) ok
step 5: served 40 connections 4 fds 46 (socket 5, file 40) ok
step 6: served 48 connections 4 fds 54 (socket 5, file 48) ok
step 7: served 55 connections 4 fds 61 (socket 5, file 55) Too many open files
load stopped: connections 0 fds 57 (socket 1, file 55)
step 1: served 10 connections 10 fds 12 (socket 11, file 0) ok
step 2: served 20 connections 20 fds 22 (socket 21, file 0) ok
step 3: served 30 connections 30 fds 32 (socket 31, file 0) ok
step 4: served 40 connections 40 fds 42 (socket 41, file 0) ok
step 5: served 50 connections 50 fds 52 (socket 51, file 0) ok
step 6: served 59 connections 59 fds 61 (socket 60, file 0) Too many open files
load stopped: connections 0 fds 2 (socket 1, file 0)
The two extra descriptors are the listening socket and the pipe to the client process. Both worlds failed with the same error at the same 61 descriptors plus the three standard streams. They differ in what the count followed: requests served in the first, connections open in the second, and in what was left when the load stopped. The prediction would have failed if the leak's count had fallen when its connections closed, or if the busy server's count had run ahead of its connections. The script has no randomness; change the eight requests per step or the limit of 64 and the leak's slope and the step that fails move with them.
Read it on a real system#
All of these read only. Sample the count a few times a minute apart, at a steady request rate, and once after traffic falls:
ls /proc/PID/fd | wc -l
grep 'Max open files' /proc/PID/limits
ss -tn state established '( sport = :8080 )' | tail -n +2 | wc -l
ss -tn state close-wait | tail -n +2 | wc -l
/proc/PID/limits shows the soft and hard limit of a running process, which can differ from what ulimit -n prints in your shell. proc_pid_limits(5) ss filters sockets by state and port. ss(8) To see which kind of descriptor grows, group the link targets in /proc/PID/fd; a socket shows as socket:[inode], a pipe as pipe:[inode], and a file as its path. proc_pid_fd(5)
ls -l /proc/PID/fd | awk 'NR > 1 {print $NF}' | sed -E 's/:\[[0-9]+\]$//; s|^/.*|file|' | sort | uniq -c
Prometheus client libraries export process_open_fds and process_max_fds for the process they run in. Client library process metrics Plot the ratio beside your server's count of open connections:
process_open_fds{job="thumbnailer"} / process_max_fds{job="thumbnailer"}
Where the limit comes from depends on how the process starts. A systemd unit sets it with LimitNOFILE=, and the systemd documentation notes that the hard limit now defaults to 524,288 and that select(2) cannot handle descriptors above 1,023, which is why raising the soft limit past 1,024 needs care. systemd.exec On ECS, a task definition's ulimits set it, and Fargate defaults the nofile soft and hard limits to 65,535. ECS task definition parameters
Where the check misleads#
ENFILE, "Too many open files in system", is a different limit: the whole system's table, not one process's. Read which errno the log carries before reading per-process counts. errno(3)
A pool that grows to its maximum and stops looks like a leak until it stops. A connection pool of 500 that fills over an hour after a restart climbs at steady load, then flattens; watch past the pool's configured size before calling it a leak.
A leak on an error path grows with errors, not with requests. If the count climbs only while a dependency fails, plot it against the error count instead of the request count.
Raising the limit hides a leak for longer and does not end it. The time between restart and the first EMFILE grows with the limit under a leak and stays at zero under a load that never reaches the new limit. Once the kind of descriptor is known, the code review question is who owns it. Who owns the resource an AI reviewer says leaks?
Sockets also run out in ways that are not descriptors: a client that opens many short connections to one destination can exhaust its ephemeral ports first. Cannot assign requested address
Questions#
How do I check the open file limit of a running process?
Read /proc/PID/limits and find the Max open files line, which shows the soft and hard limit that process has now. ulimit -n shows only your own shell's limit.
Does raising ulimit -n fix too many open files?
It fixes a limit that is too low for the connections the service must hold. It only delays a leak. Watch the descriptor count at steady load after the change: flat means the limit was the problem, still climbing means a leak.
What is the difference between EMFILE and ENFILE?
EMFILE is one process reaching its own descriptor limit, RLIMIT_NOFILE. ENFILE is the system-wide limit on open files. The first is fixed per process or per service; the second involves every process on the host.