FULL AI ANALYSIS

Node.js worker_threads leak file descriptors when using fs.watch on large directories leading to EMFILE and process OOM

Generated Oct 27, 2026, 9:31:39 AM

Analysis summary

This looks like both an API misuse and an environmental limitation. fs.watch maps to inotify on Linux and creating many watchers (especially across worker threads) consumes kernel inotify resources and fds; rapid creation/destruction can expose race conditions where watchers are not fully closed before worker termination, leaving kernel resources until process exit. Node's fs.FSWatcher must be closed, and worker_threads sharing of watchers can be problematic. Using a single watcher with event aggregation or a polling-based watcher (chokidar with polling) for network/massive trees, and reusing watchers across workers avoids large fd counts. Also ensure workers are terminated gracefully and join before watchers are closed.

Possible causes

Creating many fs.watch (inotify) watchers across worker threads exceeds kernel inotify resources and races leave watchers orphaned

90%

Node's watcher objects are garbage-collected without explicit close during worker termination, leaving kernel fds until process exit

55%

Underlying filesystem (NFS/overlayfs in container) does not support inotify reliably, forcing fallback that leaks handles under churn

30%

A Node core bug in this Node minor version causing watchers not to unbind correctly across worker boundaries

20%

Suggested fixes

1

Diagnostic step 1

Refactor: use a single watcher (or a small pool) in the parent thread that broadcasts events to workers, avoiding per-worker watchers.

2

Diagnostic step 2

Use a battle-tested library such as chokidar with polling when watching very large trees or on non-local filesystems; configure usePolling and interval.

3

Diagnostic step 3

Ensure every fs.FSWatcher.close() is called synchronously before terminating a worker; add explicit handshake to confirm close completion.

4

Diagnostic step 4

Monitor /proc/<pid>/fd and inotify counts; keep fs.inotify.max_user_watches only as a mitigation, not a fix.

5

Diagnostic step 5

If suspecting a Node bug, reproduce on a minimal test and open an issue with a repro; run on a newer Node LTS if possible.