Interview frequency: …
Short answer
An HTTP connection is upgraded to a bidirectional socket, and periodic Ping messages check that the connection is alive and close dead sockets (Zombie Connections).
Explanation
WebSocket connections begin with a regular HTTP request containing the Upgrade: websocket header. After the upgrade, the connection becomes a bidirectional TCP stream. Because a sudden client disconnection (such as Wi-Fi being turned off) may not send a TCP FIN packet, the server should send Ping messages every 30 seconds; if the client does not reply with Pong, treat the connection as dead and call socket.terminate() to release resources.
Code example
import { WebSocketServer } from "ws";
const wss = new WebSocketServer({ port: 8080 });
setInterval(() => {
wss.clients.forEach(ws => {
if (!ws.isAlive) return ws.terminate();
ws.isAlive = false;
ws.ping();
});
}, 30000);Common mistakes
- Skipping Ping/Pong, which can leave thousands of dead sockets open on the server and consume memory.