download

Why does a long-running service fail with EMFILE after hours?

Systems~8 minReviewed 2 Dec 2026Free · No sign-in

Question

An ingestion worker parses uploaded config files in a loop. After four hours it crashes with OSError: [Errno 24] Too many open files (EMFILE), even though it parses one file at a time.

  1. Why do open file descriptors keep climbing until EMFILE?
  2. Fix parse_header so the descriptor closes on early returns and exceptions alike.
  3. How do you confirm a descriptor leak on a live Linux host?
"CODE · PYTHON"
import os

def parse_header(path):
    fd = os.open(path, os.O_RDONLY)
    raw = os.read(fd, 64)
    if not raw.startswith(b"CFG:"):
        return None
    os.close(fd)
    return raw.decode("utf-8").strip()
Show hints (3)
  1. "FOLLOW EARLY EXITS"

    Trace what happens when a file does not start with b"CFG:", or when os.read raises an error. Does os.close(fd) run?

  2. "PER PROCESS LIMIT"

    The OS caps open descriptors per process (RLIMIT_NOFILE). What happens once leaked descriptors fill every slot?

  3. "SCOPE BOUND CLEANUP"

    Use Python's with open(...) context manager, or wrap raw os.open in try / finally.

Show checked explanation

Every malformed file hits return None before os.close(fd), and any os.read exception skips os.close(fd) too. Raw integer descriptors stay open until the process hits its per-process limit (RLIMIT_NOFILE) and fails with EMFILE. Fix it with with open(...) (or try/finally for raw FDs), and check /proc/<pid>/fd on Linux.

"SOLUTION · PYTHON"
from pathlib import Path
import tempfile


def parse_header(path):
    with open(path, "rb") as fh:
        raw = fh.read(64)
    if not raw.startswith(b"CFG:"):
        return None
    return raw.decode("utf-8").strip()


with tempfile.TemporaryDirectory() as d:
    good, bad = Path(d, "good.cfg"), Path(d, "bad.cfg")
    good.write_bytes(b"CFG:v1\n")
    bad.write_bytes(b"BAD\n")
    print(parse_header(good), parse_header(bad))
"OUTPUT"
CFG:v1 None

Reproduced real EMFILE (errno 24) on the buggy os.open starter and checked early-return and exception-path cleanup on CPython 3.12.10 (Windows x64). Checked by an editor other than the author.

Walkthrough

An OS file descriptor (or Windows handle) is a kernel table slot pointing to an open file, socket, or pipe. Each process has a per-process limit on open slots (RLIMIT_NOFILE on Unix, often a 1,024 soft limit by default; C runtime limits apply to os.open on Windows too). When no free slot remains, open, socket, and accept all fail with EMFILE (Too many open files).

In the starter, os.open returns a plain integer. Plain integers have no destructor. Whenever an uploaded file lacks the CFG: prefix, parse_header returns None and leaks that descriptor. The same leak happens if os.read raises an exception. Notice the process does not crash on the first bad file; it leaks silently for hours until the descriptor table fills up.

Wrapping file access in with open(path, "rb") as fh: binds closing to the block exit, so Python calls fh.close() on normal return, early return, and exceptions. If you truly need raw os.open, pair it with try: ... finally: os.close(fd). In Rust or C++, RAII (std::fs::File implementing Drop) solves this automatically at scope exit.

OS check (Linux)what it shows
ls /proc/<pid>/fd | wc -lCurrent count of open descriptors for the process
lsof -p <pid>Exact open files, sockets, and pipes held by the process
cat /proc/<pid>/limitsSoft and hard Max open files (RLIMIT_NOFILE) limits

On a live host, watching the count in /proc/<pid>/fd climb steadily toward Max open files while request concurrency stays flat confirms a leak.

Common mistakes

  • Fixing EMFILE by raising ulimit -n from 1,024 to 65,536. That only buys extra hours before the leaked descriptors hit the new ceiling.
  • Relying on garbage collection to close leaked files. Plain integer FDs are never closed by GC, and file objects on non-refcounted runtimes or inside tracebacks can stay open too long.
  • Forgetting that TCP sockets, pipes, and epoll instances all share the same per-process descriptor table. A file leak also stops the server from accepting new HTTP connections.
  • Confusing EMFILE (process hit its own RLIMIT_NOFILE) with ENFILE (the whole kernel hit its system-wide open-file limit).

Follow-up questions

  • "What happens to a deleted file on Linux if your service still holds an open descriptor to it?" The directory entry disappears, so ls hides it, yet the kernel keeps the inode and disk blocks allocated until the last open descriptor closes. lsof +L1 reveals these deleted-but-open files eating disk space.
  • "You open a file in Python, then call subprocess.run(...). Could the child process inherit your descriptor?" Since PEP 446 (Python 3.4+), Python marks new file descriptors non-inheritable (O_CLOEXEC) by default. In C or raw syscalls without O_CLOEXEC, child processes inherit open descriptors and keep files or listening sockets alive.
  • "How does Rust prevent this exact bug without a with statement?" std::fs::File implements Drop, which closes the OS handle as soon as the File variable leaves scope, including on ? early error returns.

What a strong answer covers

Spots the early-return and exception leaks on raw fd, uses with or try/finally for scope-bound cleanup, inspects /proc/<pid>/fd and lsof, and explains why raising ulimit -n only delays failure.

Open in interactive practice deck →

Original OfferVibe question. open(2) · getrlimit(2) · Python with statement.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.