skip to content

On a Node.js TCP server that calls socket.setTimeout(60000) on every net.Socket, why do connections from powered-off devices stay open for hours, and what fixes it?

level: seniorimportance: should knowfreq 40%

answer

  1. a notification, not a close
  2. who calls destroy()?
  3. writes count as activity
  4. let the kernel probe the peer
  5. maxConnections as a ceiling

basics

~20 s

socket.setTimeout() only emits 'timeout' after idle time and never closes the socket, so the handler must call socket.destroy(). A powered-off device sends nothing at all, so also enable socket.setKeepAlive() to let the kernel detect the dead peer.

solid answer

~40 s

In Node 24, `socket.setTimeout(ms)` arms an inactivity timer that emits `'timeout'` and does nothing else: the documentation says the connection is not severed and you must call `socket.end()` or `socket.destroy()` yourself. Three things keep dead device sockets alive: a `'timeout'` handler that is missing or only logs; a handler that calls `socket.end()`, which half-closes and then waits for a peer that will never answer; and server writes such as periodic commands, which count as activity and keep resetting the timer. Fix it by calling `socket.destroy()` on `'timeout'`, and by enabling TCP keepalive with `socket.setKeepAlive()` or the server's `keepAlive` option, so the kernel probes silent peers and Node gets an error and `'close'` when probes go unanswered. Since 24.19.0 `setKeepAlive()` also accepts `interval` and `count`. Set `server.maxConnections` as a ceiling.

code

javascript · 23 lines
javascript
import net from 'node:net';

const IDLE_MS = 60_000;

const server = net.createServer((socket) => {
  socket.setKeepAlive({ enable: true, initialDelay: 30_000, interval: 5_000, count: 3 });
  socket.setTimeout(IDLE_MS);
  socket.on('timeout', () => {
    socket.destroy();
  });
  socket.on('error', (err) => {
    console.error(`device socket error: ${err.code}`);
  });
  socket.on('data', (chunk) => {
    // frame and handle device readings here
  });
});

server.maxConnections = 20_000;
server.on('drop', (info) => {
  console.warn(`dropped connection from ${info?.remoteAddress}`);
});
server.listen(7070);

go deeper

for a junior

Recall that 'timeout' is only a notification: the socket stays open until your handler calls destroy() or end().

for a middle

Explain the difference between end() and destroy() for a vanished peer, and that keepalive is off by default and enabled with setKeepAlive() or the server's keepAlive option.

for a senior

Diagnose the pile-up from all three causes, including writes resetting the idle timer, and combine keepalive, destroy() on timeout, a read deadline and maxConnections into one policy.

for a principal

Decide the fleet's dead-peer budget: how long a silent device may hold a slot, and whether keepalive tuning or an application heartbeat owns that guarantee across every socket service.

## What socket.setTimeout() actually does `socket.setTimeout(timeout[, callback])` on a `net.Socket` from `node:net` starts an **inactivity timer**. By default a socket has no timeout. When the timer expires the socket emits `'timeout'`, and that is all. The Node documentation is explicit: the connection is not severed, and the user must call `socket.end()` or `socket.destroy()`. The optional callback is just a one-time `'timeout'` listener. Passing `0` disables the timer. Clients have the same switch: `net.createConnection({ timeout })` calls `socket.setTimeout()` before connecting, and `'timeout'` is still only a notification there. The current value is readable as `socket.timeout`, which is `undefined` until a timeout is set, a quick check when auditing which sockets actually have one. So a server that sets a 60-second timeout and attaches no handler, or a handler that only logs, keeps every idle connection open indefinitely. With thousands of devices on flaky power or cellular links, that becomes thousands of file descriptors and their per-connection state. ## Three ways dead sockets survive 1. **No real handler.** `'timeout'` fires, nothing closes the socket, and it stays open. 2. **The handler calls `socket.end()`.** `end()` half-closes: it flushes queued writes and sends the end of transmission, then waits for the peer to end its side too. A device that has lost power never answers, so the socket lingers until the kernel eventually gives up on the unacknowledged data, which can take many minutes. 3. **The server keeps writing.** Node refreshes the idle timer on writes as well as reads. A server that pushes a command or ping to each device every 30 seconds never lets a 60-second timer expire, even though the device has been silent for hours. The writes are accepted into the kernel's send buffer and simply go unacknowledged. ## The fixes | Tool | What it catches | Notes | |---|---|---| | `socket.destroy()` in the `'timeout'` handler | Peers that stop sending, when the server is also quiet | Use `destroy()`, not `end()`, for a peer you believe is gone | | `socket.setKeepAlive()` or `net.createServer({ keepAlive: true })` | Peers that vanished without closing, even when nobody sends | The kernel sends probes; failure surfaces as an error, typically `ETIMEDOUT`, then `'close'` | | An application-level read deadline | Devices that must report every N seconds | Track the last received reading, not any socket activity | | `server.maxConnections` and the `'drop'` event | Runaway connection counts from any cause | A ceiling and a signal, not a cure | Keepalive is **off by default**: both `net.Socket` and `net.createServer()` document `keepAlive` as `false`. `socket.setKeepAlive(true, initialDelay)` turns it on; `initialDelay` is the idle time in milliseconds before the first probe. Node also sets the probe interval and count, by default `1000` ms and `10` probes. Node 24.19.0 added `interval` and `count` arguments and an options-object form, `socket.setKeepAlive({ enable, initialDelay, interval, count })`, so you can choose how quickly a dead peer is declared gone. The values are applied in whole seconds, rounded down. Whether to rely on keepalive probes or an application heartbeat is a protocol design choice covered in the TCP material on keepalive; in Node the point is that keepalive is opt-in. ## Putting it together on the IoT server - Enable keepalive when each connection arrives, with a delay shorter than any idle timeout a firewall or NAT in the path might apply. - Set an idle timeout based on what the devices promise, and `destroy()` on `'timeout'`. - If the server writes regularly, enforce a read deadline instead: remember when the last reading arrived and destroy sockets that have been silent too long. - Keep an `'error'` listener on every socket, because keepalive failures arrive as errors. - Set `server.maxConnections` so a bug or a reconnect storm cannot exhaust descriptors; when the limit is reached Node closes new connections and emits `'drop'` (in cluster mode it routes them to another worker by default). - Watch the count with `server.getConnections()`, or by tracking sockets in a `Set` removed on `'close'`. ## Things that do not help - **`server.close()`** stops accepting new connections and keeps existing ones; it never closes a stale device socket. - **`socket.setNoDelay()`** changes when small writes are sent; it has nothing to do with detecting dead peers. - **`socket.unref()`** only lets the process exit while the socket is open; the socket itself stays open. - **A longer timeout.** It only delays the pile-up.

  • Why prefer socket.destroy() over socket.end() in the 'timeout' handler?
    `socket.end()` only half-closes: it flushes pending writes, sends the end of transmission and waits for the peer to end its side. A peer that is gone never does, so the socket can linger while the kernel retries unacknowledged data. `socket.destroy()` releases the socket at once and emits `'close'`, which is what you want for a peer you have decided is dead.
  • What does the server see when keepalive probes go unanswered?
    After the configured number of unanswered probes the kernel declares the connection dead. Node then emits `'error'` on the socket, typically with code `ETIMEDOUT`, followed by `'close'` with `hadError` set to `true`. That is why the `'error'` listener must exist: without one, a single dead device would crash the process.
  • How do you set keepalive for every accepted connection without touching each socket?
    Pass `keepAlive: true` and `keepAliveInitialDelay` to `net.createServer()`; Node enables keepalive on each socket as the connection is accepted. To choose the probe interval and count you still call `socket.setKeepAlive()` in the connection listener, using the Node 24.19.0 options.

  • socket.setTimeout() closes the connection when the idle time elapses.
  • Calling socket.end() on 'timeout' frees a dead device's socket immediately.
  • TCP keepalive is enabled by default on sockets a net.Server accepts.
  • Only incoming data resets the idle timer, so server writes cannot keep it from firing.
  • server.close() disconnects idle clients so they can reconnect.

Assumes Node.js 24; the interval and count arguments and the options-object form of socket.setKeepAlive() were added in v24.19.0, while earlier releases applied Node's default 1000 ms interval and 10 probes.