Node.js worker_threads leak file descriptors when using fs.watch on large directories leading to EMFILE and process OOM
Environment
Node.js 16.20 app (Linux x86_64), heavy background processing using worker_threads; parent thread spawns workers that create fs.watch watchers on user-upload directories containing thousands of files; app runs in Docker container on Ubuntu 22.04
Symptoms
After sustained runtime the Node process exhausts file descriptors and memory grows until OOM or EMFILE errors appear; creating new worker threads fails; graceful shutdown hangs
Observations
lsof shows thousands of inotify fd entries created by workers; /proc/<pid>/limits shows fd count increasing over time; worker thread exit handlers sometimes not invoked; explicit watcher.close() is invoked in code paths, but after rapid restarts watchers remain in kernel list; increasing ulimit temporarily postpones failure
Already attempted
Added explicit watcher.close() in error/finally blocks, upgraded Node minor versions, moved some watchers to parent thread, increased fs.inotify.max_user_watches and ulimit -n; behavior improves but leak still accrues under high churn
Question
How to eliminate the fd/inotify watcher leak and design a robust watcher strategy with worker threads for directories with thousands of files?
Verified community troubleshooting
No answers yet..
Incident analysis
Most likely causes
Summary
Suggested Fixes
Continue troubleshooting
Related troubles
Matched from the title, description and tags
- Programming23% match
Node.js/Express app hits EMFILE under high concurrency — many sockets/files left open
Solved1 answer - Programming22% match
Node.js worker_threads hang under high CPU when using SharedArrayBuffer + Atomics.notify in clustered app
Open1 answer - Web Development21% match
Next.js API processes hit 'Too many open files' under load behind PM2 — 500s only in production
Open0 answers