In this lesson, you will learn how to implement a heartbeat mechanism to detect and prune "zombie" WebSocket connections that appear active but have actually dropped.
Why Heartbeats?
In a standard WebSocket setup, a client’s network might drop unexpectedly (like switching from Wi-Fi to cellular) without the server receiving a "close" frame. The server, unaware of this, keeps the socket instance alive, consuming memory and preventing the user from successfully reconnecting elsewhere. We solve this by implementing a Ping-Pong cycle.
The Ping-Pong Strategy
We use setInterval to periodically send a "ping" frame to all connected clients. If a client is still healthy, it automatically responds with a "pong" frame. To track this, we attach a isAlive property to each socket object.
// 1. Mark socket as alive on initial connection
socket.isAlive = true;
// 2. Listen for the pong response
socket.on('pong', () => {
socket.isAlive = true;
});
// 3. The heartbeat interval (e.g., every 30 seconds)
const interval = setInterval(() => {
wss.clients.forEach((ws) => {
if (ws.isAlive === false) return ws.terminate();
// Assume dead until proven alive by pong
ws.isAlive = false;
ws.ping();
});
}, 30000);
How it Works
- Initialize: Every socket starts with
isAlive = true. - Ping: The server sends a ping to every client. Crucially, we set
isAlive = falseimmediately after sending the ping. - Pong: If the client is connected, the browser/client library receives the ping and automatically sends back a pong. This triggers our
on('pong')listener, which flipsisAliveback totrue. - Prune: If the interval fires again and
isAliveis stillfalse, it means we never received the pong. We assume the connection is stale and callws.terminate()to clean up resources and prevent memory leaks.
This keeps your connection pool lean and ensures your server only maintains truly active sessions.
Key Takeaway: A heartbeat mechanism uses periodic pings to verify client responsiveness, allowing you to proactively terminate stale connections that fail to respond with a pong.