← Back to Node.js, page 10

nodejs-0183 · Medium mid

What does the EMFILE error mean in Node.js, and how do you fix and prevent it?

EMFILE means the process hit its limit of open file descriptors. Sockets, files, pipes and watchers all use descriptors. Causes are opening many files at once without a limit, leaking handles that are never closed, or too many connections for a low ulimit. Fix it by limiting concurrency, always closing handles (finally, pipeline), and raising the ulimit when the real need is higher.

Full answer

What happens

  • Every open file, socket, pipe and watcher uses a file descriptor. The operating system gives each process a limit (ulimit -n, commonly 1024 on some systems, much higher in many containers). Over the limit, calls fail with EMFILE (too many open files in this process). ENFILE is the system-wide version.
  • A web server uses one descriptor per client connection, so a low limit also limits concurrent connections.

Causes

  1. Unbounded concurrency: Promise.all over thousands of file reads or requests opens them all at once.
  2. Leaks: files, streams or sockets that are not closed on error paths. fs.promises.open handles need close() (use try/finally or await using, and use pipeline for streams).
  3. File watchers on large trees (each watcher can use descriptors).
  4. A low ulimit for a busy server, or child processes that inherit descriptors.

Fix and prevent

  • Limit concurrency with a promise pool, p-limit or a queue. This is the main fix.
  • Close handles in finally blocks and on every error path.
  • Reuse connections with a keep-alive Agent instead of one socket per request.
  • graceful-fs (used by npm tools) queues operations and retries after EMFILE.
  • Raise the limit (ulimit -n, systemd LimitNOFILE, Docker --ulimit nofile) when the load really needs it, and monitor open descriptors (ls /proc/PID/fd on Linux, or the diagnostic report).
javascript
const { spawnSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');

const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'emfile-'));
const target = path.join(dir, 'data.txt');
fs.writeFileSync(target, 'hello');

// The child script runs with a low descriptor limit set by the shell.
const child = path.join(dir, 'child.js');
fs.writeFileSync(child, `
const fs = require('node:fs');
const target = process.argv[2];
const COUNT = 200;

async function allAtOnce() {
  const results = await Promise.allSettled(Array.from({ length: COUNT }, () => fs.promises.open(target)));
  const errors = results.filter((r) => r.status === 'rejected').map((r) => r.reason.code);
  await Promise.all(results.filter((r) => r.status === 'fulfilled').map((r) => r.value.close()));
  return { someOpensFailed: errors.length > 0, errorCodes: [...new Set(errors)] };
}

async function withLimit(limit) {
  let next = 0, done = 0;
  async function worker() {
    while (next < COUNT) {
      next++;
      const handle = await fs.promises.open(target);
      try { await handle.readFile('utf8'); done++; } finally { await handle.close(); }
    }
  }
  await Promise.all(Array.from({ length: limit }, worker));
  return done;
}

(async () => {
  console.log('all at once :', JSON.stringify(await allAtOnce()));
  console.log('pool of 10  :', await withLimit(10), 'files read, no errors');
})();
`);

const result = spawnSync('sh', ['-c', `ulimit -n 64; echo "descriptor limit: $(ulimit -n)"; ${JSON.stringify(process.execPath)} ${JSON.stringify(child)} ${JSON.stringify(target)}`], { encoding: 'utf8' });
console.log(result.stdout.trim());
fs.rmSync(dir, { recursive: true });

A shell sets a low descriptor limit (64) for a child process, so the failure is easy to reproduce. How many opens succeed depends on the descriptors that Node already uses, so the first line shows only whether some opens failed and the error codes, not a count. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): descriptor limit: 64 all at once : {"someOpensFailed":true,"errorCodes":["EMFILE"]} pool of 10 : 200 files read, no errors

Key points

  • EMFILE means the process descriptor limit is reached.
  • Unbounded concurrency and leaked handles are the main causes.
  • Limit concurrency with a pool or queue.
  • Close handles on every path.
  • Raise ulimit only when the need is real, and monitor the count.

Common mistakes

  • Using Promise.all over a huge array of file operations.
  • Not closing handles when an error is thrown.
  • Raising the limit without fixing a leak.
  • Watching a huge directory tree with many watchers.
  • Creating a new connection for every outgoing request.

Follow-ups

  • How do you count open descriptors of a running process on Linux?
  • What is the difference between EMFILE and ENFILE?
  • What does graceful-fs do?

Tips

  • Explain that sockets also count.
  • Say 'limit concurrency first, ulimit second'.
  • Mention closing in finally.