Connection reliability

Add an idle timeout

Close connections that stop making progress and distinguish inactivity from a total request deadline.

10 minute lesson

~~~

A client can connect and send nothing forever. Each idle connection holds a file descriptor, buffer memory, and a slot in your per-client state. Enough of them and the server can’t serve anyone — the cheapest denial of service there is.

An idle timeout bounds how long the socket remains inactive. In Node, socket.setTimeout() starts an inactivity timer that resets on every read or write.

Add a ten-second inactivity timeout:

socket.setTimeout(10_000)
socket.on('timeout', () => {
  socket.end('408 timeout\n')
})

Node does nothing on its own when the timer fires — it only emits the timeout event. You decide the response. Here socket.end() sends a final line and closes our side. If you’d rather not trust the peer to complete the close, follow up with socket.destroy() after a short grace period.

Verify it

Connect with netcat and wait:

nc 127.0.0.1 4000
# ...say nothing for ten seconds...
# 408 timeout

While waiting, open a second nc in another terminal and use it normally. Confirm the server closes the idle socket while continuing to accept and serve other clients. The timeout is per connection, not per server.

Idle is not the same as slow

The timer resets on any activity. A hostile client can send one byte every nine seconds and hold your connection open indefinitely while never completing a request — the slowloris pattern. An idle timeout alone doesn’t catch it.

If your protocol needs a total request deadline, track it separately: record a timestamp when the request starts and enforce a maximum age regardless of activity. Idle timeout says “you went quiet”. A deadline says “you took too long overall”. Robust servers need both.

Picking the number

Choose a timeout from protocol needs, not from a random blog post. An interactive command protocol where humans type can justify 30 to 60 seconds. Machine-to-machine request/reply traffic can be far stricter.

A timeout that is too short can break slow but legitimate clients — a person testing with nc, a device on a congested link. Start generous, log how long real connections actually sit idle, then tighten with data.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →