Lesson 18 / 32
Heartbeats and Dead Connections
Detect half-open connections with ping/pong heartbeats and keep proxies from closing idle sockets.
By Rahul Agarwal · 15 years in web development
Half-open connections
TCP does not tell you when the other side silently vanishes. If a phone switches from Wi-Fi to mobile data, or a laptop lid closes, no FIN or close frame is sent. The server's socket looks OPEN, and writes may even succeed for a while because they only go into kernel buffers. This is a half-open connection. Without detection, servers collect thousands of ghost sockets and clients think they are live while missing every update. The fix is a heartbeat: the server sends a ping every N seconds (often 20-30) and marks the socket. If no pong arrives before the next round, it calls terminate(), which destroys the socket immediately instead of waiting for a close handshake that will never finish. Heartbeats also stop load balancers from closing idle connections. Browsers answer pings automatically, but browser code cannot see them, so clients that must detect a dead server send an application-level { "type": "ping" } and expect a reply.
The standard ws heartbeat
Each round marks every socket as not alive and pings it; the pong handler marks it alive again. A socket still marked dead at the next round is terminated.
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', (ws) => {
ws.isAlive = true;
ws.on('pong', () => {
ws.isAlive = true; // the browser answered our last ping
});
});
const interval = setInterval(() => {
for (const ws of wss.clients) {
if (!ws.isAlive) {
ws.terminate(); // no pong since the last round: connection is dead
continue;
}
ws.isAlive = false;
ws.ping();
}
}, 30_000);
wss.on('close', () => clearInterval(interval));Choose the interval from the path
Pick a heartbeat shorter than the smallest idle timeout between client and server; many load balancers default to 60 seconds. Shorter intervals detect failures faster but wake mobile radios more often and drain battery.
The attendance roll call
A teacher who only notices absent students when they complain will never notice the ones who quietly left. Calling the roll every period, and marking anyone who does not answer, is the heartbeat.
Quick check: Why does the heartbeat code call `ws.terminate()` instead of `ws.close()` on a dead socket?
- `close()` is not available on server sockets
- `terminate()` sends a nicer close code
- The peer is gone, so a close handshake would never complete; terminate destroys the socket immediately
- `terminate()` lets the client reconnect faster
Answer
The peer is gone, so a close handshake would never complete; terminate destroys the socket immediately — `close()` starts a handshake and waits for the peer's close frame. A vanished peer will never reply, so the socket would linger. `terminate()` frees it at once.