Diagnose file descriptor exhaustion on a dedicated server

Diagnose file descriptor exhaustion on a dedicated server

Diagnose file descriptor exhaustion on a dedicated server

If your database interface suddenly reports “Too many open files” while CPU usage, memory usage, and available disk space look normal, file descriptors may be the bottleneck. Sockets, regular files, pipes, and event notification objects all consume descriptors. Counting database connections alone overlooks log files and background tasks. Start by capturing the process state, then determine whether legitimate concurrency has reached a limit or resources are not being released.

This article uses a systemd service on Debian 12 as its example. Run the commands in an administrative session with the necessary permissions. Login credentials for an AmdByte dedicated server are available in the control panel after payment; use SSH to connect to Linux. These steps do not depend on a particular memory tier and require no changes to the disk layout.

Identify which limit was reached

EMFILE means the current process has reached its descriptor limit; ENFILE means the system-wide open file table cannot allocate further entries. These are separate limits. If the application wraps the error message, preserve the underlying error code and the operation that failed, such as opening a log, accepting a connection, or creating a pipe.

First, enter the actual service unit name in the same shell. Subsequent commands reuse this variable:

read -r -p 'Service unit: ' UNIT
PID=$(systemctl show "$UNIT" -p MainPID --value)
test "${PID:-0}" -gt 0 && test -d "/proc/$PID" || exit 1
systemctl show "$UNIT" -p MainPID -p LimitNOFILE -p LimitNOFILESoft
grep 'Max open files' "/proc/$PID/limits"
cat /proc/sys/fs/file-nr
cat /proc/sys/fs/file-max
cat /proc/sys/fs/nr_open

The three columns in file-nr report allocated file handles, allocated but unused handles, and the maximum, respectively. On modern Linux, the second column is usually zero. This is not simply the sum of all processes’ descriptor counts, because multiple descriptors can refer to the same open file object. The nr_open setting caps the hard descriptor limit that can be set for an individual process.

In an interactive terminal, ulimit -n describes only the current shell’s limit. It does not establish the effective limit of a background service. For a running process, use the target process’s /proc/PID/limits as the authority.

Inventory open objects

A total descriptor count alone cannot locate a leak. The following sample groups targets into sockets, pipes, anonymous objects, and other files, while separately counting objects that have been deleted but remain open. Descriptors may close during sampling, so skipping entries that disappear is expected behavior.

sudo python3 - "$PID" <<'PY'
import collections
import os
import sys

root = f"/proc/{int(sys.argv[1])}/fd"
counts = collections.Counter()
deleted = 0
for entry in os.scandir(root):
    try:
        target = os.readlink(entry.path)
    except FileNotFoundError:
        continue
    if target.startswith("socket:"):
        kind = "socket"
    elif target.startswith("pipe:"):
        kind = "pipe"
    elif target.startswith("anon_inode:"):
        kind = "anon_inode"
    else:
        kind = "file_or_device"
    counts[kind] += 1
    deleted += target.endswith(" (deleted)")
print(dict(counts))
print("sampled_total", sum(counts.values()))
print("deleted_targets", deleted)
PY

Take one sample before requests begin, one while concurrency is stable, and one after requests finish. Record the request volume, connection pool limit, and process ID alongside each sample. An idle connection pool may retain sockets, so a count that does not return to zero is not necessarily a leak. What matters is whether it settles within the expected range.

If socket keeps growing, use sudo ss -tanp to check the owning processes and connection states. TIME-WAIT connections usually no longer consume descriptors in the original process, so their count is not direct evidence of a leak. A large number of CLOSE-WAIT connections alongside a growing descriptor count calls for checking whether the application closes its end after the peer closes the connection.

The main process may only be a manager. If worker processes handle requests, inspect each actual worker. A low descriptor count in the manager does not prove that the whole service is healthy.

Reproduce the limit in isolation

This test lowers the limit only inside a newly created Python child process. It does not change the production service or attempt to exhaust the system-wide file table. The script repeatedly opens /dev/null, holds the descriptors until an error occurs, and then closes them all.

python3 - <<'PY'
import errno
import os
import resource

soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
cap = 64 if soft == resource.RLIM_INFINITY else min(64, soft)
resource.setrlimit(resource.RLIMIT_NOFILE, (cap, hard))
held = []
try:
    while True:
        held.append(os.open(os.devnull, os.O_RDONLY))
except OSError as exc:
    print("errno", exc.errno)
    print("is_emfile", exc.errno == errno.EMFILE)
    print("opened_by_test", len(held))
finally:
    for fd in held:
        os.close(fd)
PY

The number of descriptors opened by the test is usually below the limit because standard input, standard output, and other existing descriptors already occupy slots. This experiment validates the error-handling path. It does not measure production service capacity or prove that the application releases resources correctly.

Add an application-level test as well: actively cancel a request after the connection is established, and verify that the exception path closes the socket or returns the connection to the pool. Passing the normal response path does not cover cancellation, timeout, or retry paths.

Change the service limits

First, calculate the peak descriptor demand per process, accounting for the number of workers, connection pools, inbound connections, logs, and temporary files, then leave headroom. Database connection limits and descriptor limits do not have a one-to-one relationship, and pool capacity should not be increased without bounds.

Record the effective configuration before making changes:

systemctl cat "$UNIT"
systemctl show "$UNIT" -p LimitNOFILE -p LimitNOFILESoft
sudo systemctl edit "$UNIT"

You can enter the following configuration in the editor. 65536 is only an example; confirm the actual capacity requirement and the system’s hard-limit ceiling before using it:

[Service]
LimitNOFILE=65536:65536

The value before the colon is the soft limit; the value after it is the hard limit. After saving, run sudo systemctl daemon-reload, but note that this does not change the limits of an already running process. Schedule a restart that the application can accommodate, then run:

sudo systemctl restart "$UNIT"
PID=$(systemctl show "$UNIT" -p MainPID --value)
test "${PID:-0}" -gt 0 && test -d "/proc/$PID" || exit 1
grep 'Max open files' "/proc/$PID/limits"
systemctl is-active "$UNIT"

If the process lowers its own limits, the unit configuration and runtime values may still differ. You must check the new process. To roll back, remove only the settings added by this change, then reload the configuration and restart the service. Do not delete an entire override file that contains other valid settings.

Verify descriptor recovery after load

Repeat the test with the same request volume, recording the peak count, the stable count after requests finish, and the error count. Connection pool warm-up may raise the baseline in the first run. Subsequent runs should settle rather than leave a new step upward after every test.

Verification should cover at least four points:

If raising the limit merely delays the error, return to leak investigation rather than increasing it again. When submitting diagnostic records, retain the error codes, process limits, counts by category, and load phases. Avoid uploading a complete raw listing containing client addresses and application paths. The final conclusion should answer two questions: are resources released as designed, and are the limits sufficient for the workload that has actually been tested?

Frequently asked questions

Why does raising ulimit in a terminal not fix the service?

The change does not retroactively affect a running service and usually does not reach system-level systemd services. Inspect /proc/PID/limits, set LimitNOFILE in the relevant unit, restart it, and check the new process.

Does increasing LimitNOFILE fix a connection leak?

No. It only increases the number of descriptors the process can hold. If sockets keep accumulating after requests finish, fix close paths, pool recycling and timeout handling, then verify the descriptor trend after load subsides.

EPYC 7543P Dedicated Server

From $457/mo

Server Specifications and Rental Pricing

Compare ECC memory options and direct-attached NVMe configurations, then choose add-ons and a billing term.