skip to content

After a Node.js socket server calls server.close() and every client disconnects, why might the process never exit, and how do you find the leaked timer?

level: seniorimportance: should knowfreq 40%

answer

  1. something ref'd is still active
  2. intervals count like sockets
  3. ask the process what is alive
  4. the starter of a timer stops it

basics

~20 s

A ref'd timer nobody cleared, often a setInterval started at boot, keeps the event loop alive after the server has gone. process.getActiveResourcesInfo() then lists 'Timeout'; the fix is clearing that timer where the server closes, not calling process.exit().

solid answer

~40 s

Node exits only when nothing ref'd is left in the event loop, and an active `setInterval` or a long `setTimeout` counts. A sweeper or metrics interval started at boot and never stored keeps the process up after `server.close()` has finished, which looks like a hung shutdown. To confirm it, log `process.getActiveResourcesInfo()` from the `server.close()` callback: it returns the types of resources keeping the loop alive, and a `'Timeout'` entry points at a timer. To find which one, look for `setInterval` and `setTimeout` calls whose return value is discarded, or record creation stacks with an `async_hooks` `init` hook while debugging. The fix is ownership: keep the handle and call `clearInterval` where the server closes. `unref()` suits pure housekeeping but hides the leak rather than fixing it, and `process.exit()` can cut off pending output.

code

javascript · 12 lines
javascript
const net = require('node:net');
const { getActiveResourcesInfo } = require('node:process');

const server = net.createServer((socket) => socket.end('bye\n'));
const sweeper = setInterval(() => { /* evict idle clients */ }, 10_000);

server.listen(0, () => {
  server.close(() => {
    console.log(getActiveResourcesInfo()); // includes 'Timeout': the sweeper
    clearInterval(sweeper); // without this line the process never exits
  });
});

go deeper

for a junior

Know that an uncleared setInterval or setTimeout keeps a Node process running, and that the fix is to keep the timer's handle and clear it.

for a middle

Explain the ref'd-resource rule behind process exit and use process.getActiveResourcesInfo() to see which resource types still hold the loop open.

for a senior

Walk through the diagnosis end to end, choose between clearing and unref'ing, and spot the long-running variant: per-request timers that leak memory and fire late.

for a principal

Turn it into a standard: background timers are created by components with a stop method, shutdown calls them in order, and a hung exit is a defect, not a reason for process.exit().

## Why the process stays up A Node.js process exits on its own when its event loop has nothing left to wait for. `server.close()` stops the server accepting connections, and its callback runs once every existing connection has ended. If the process is still running after that, something else in the loop is still **ref'd**, and an active timer is the most common culprit, because a timer counts exactly like an open socket: - a `setInterval` that fires forever unless someone calls `clearInterval`, - a long `setTimeout`, such as a retry scheduled for five minutes from now, - a pending `setImmediate` that keeps rescheduling itself. From the outside this looks like a hung shutdown: the logs say the server closed, then nothing happens until the orchestrator gives up and kills the process. ## The usual culprits - **Housekeeping intervals started at module load**: idle-client sweepers, cache expiry, metrics flushes. The return value is often discarded, so nothing can clear it. - **Retry and backoff timers** created by a client library or your own helper, still waiting for their next attempt. - **Per-request deadline timers** that are only cleared on the slow path and forgotten when the work finishes early. - **Timers inside tests**, which can keep a test process from exiting after its last test. ## Confirming the leak 1. **Ask Node what is keeping it alive.** `process.getActiveResourcesInfo()` returns an array of strings naming the types of resources currently keeping the event loop alive. Log it from the `server.close()` callback; a `'Timeout'` entry means an active, ref'd timer. 2. **Read the rest of the list.** Other entries name other resources, such as a handle that is still closing or a socket still open; do not expect an empty list inside the close callback. A `'Timeout'` entry is the timer to hunt for. 3. **Find which timer.** Search for `setInterval` and long `setTimeout` calls whose return value is not stored. In a large codebase, an `async_hooks.createHook` `init` hook sees each new resource with its `type`, so recording a stack trace whenever the type is `'Timeout'` points at the creator. That API is Experimental and the documentation does not recommend it, citing performance and safety costs, so keep such a hook to a local debugging session. 4. **Verify the fix** by checking that the process exits on its own and that `getActiveResourcesInfo()` no longer lists the timer. Two cautions while reading the output. The list names resource **types**, not the code that created them, so it tells you that a timer is alive, not which one. And unref'd timers do not appear, because they are not keeping the loop alive; an unref'd leak has to be found by reading code. ```js const net = require('node:net'); const { getActiveResourcesInfo } = require('node:process'); const server = net.createServer((socket) => socket.end('bye\n')); const sweeper = setInterval(() => { /* evict idle clients */ }, 10_000); server.listen(0, () => { server.close(() => { console.log(getActiveResourcesInfo()); // includes 'Timeout' clearInterval(sweeper); // now the process exits }); }); ``` ## Fixing it properly | Fix | What it does | When it is right | |---|---|---| | `clearInterval` / `clearTimeout` on shutdown | removes the timer and releases its callback | the default: the code that starts a timer stops it | | `timer.unref()` | the timer no longer keeps the loop alive | housekeeping that may silently stop at exit | | `AbortSignal` with `node:timers/promises` | aborting clears the timer and rejects the wait | async loops that already take a signal | | `process.exit()` after close | ends the process regardless | not a leak fix: it hides the cause and can cut off pending output | Clearing is preferred over unref because it states ownership. An unref'd interval still runs, still holds its closure, and the next person to read the code cannot tell whether stopping it was ever considered. ## The same leak in a process that never exits A long-running server never needs to exit, so the leak shows up differently. A per-request `setTimeout(onDeadline, 30_000)` that is not cleared when the response finishes keeps its timer and its closure, with whatever request data it captured, alive for the full 30 seconds; at high request rates that is a large standing population of timers, and every one of them still fires on a request that has already been answered. Clear it in a `finally` block, or use a promise timer with a signal that is aborted when the work ends. Tracking the memory side of that leak is covered with heap analysis.

  • Why is process.exit() in the close callback a poor fix for the hang?
    It ends the process whatever is pending, so the leak is hidden rather than found, and work still in flight, such as asynchronous writes to stdout or a pipe, can be cut off. It also turns a clean, observable exit into a forced one, and the next leaked resource will be hidden the same way.
  • The server never needs to exit. Can an uncleared per-request setTimeout still hurt it?
    Yes. Each timer, its callback and whatever the callback captured stay alive until it fires, so a 30 second deadline on every request keeps 30 seconds of request data in memory, and every callback still runs for a request that has already been answered. Clear the timer when the work finishes.

  • Node kills any timers that are left once server.close() has completed
  • Calling process.exit() after close is the proper fix for a hang
  • A leaked interval only matters in short scripts, never in servers
  • unref() and clearInterval() leave the process in exactly the same state
  • process.getActiveResourcesInfo() names the line of code that created each timer