What are heartbeats (ping/pong) in WebSockets and why are they needed?
Understand WebSocket heartbeats and ping/pong frames: how they detect dead connections, keep idle sockets alive through proxies, and trigger reconnects.
Expected Interview Answer
Heartbeats are small ping/pong control frames exchanged periodically to confirm a WebSocket connection is still alive. They are needed to detect half-open or dead connections and to keep idle connections from being closed by proxies, load balancers, and firewalls.
A TCP connection can silently die — the network drops but neither side gets a close event, leaving a half-open socket that looks connected but delivers nothing. One side sends a ping frame on an interval and expects a pong back within a timeout; if the pong never arrives, that side treats the connection as dead and closes or reconnects it. Heartbeats also generate traffic on otherwise idle connections so intermediaries with idle timeouts don't tear them down. WebSocket has built-in ping/pong opcodes, and libraries like Socket.IO implement their own heartbeat on top.
- Detects half-open connections that appear alive but are dead
- Keeps idle connections open through proxy and firewall timeouts
- Triggers timely reconnection when a peer goes silent
- Measures round-trip latency as a side benefit
- Frees server resources tied to zombie sockets
AI Mentor Explanation
Heartbeats are like the umpire and scorer periodically signaling to each other to confirm play is still on. If the scorer stops responding to signals, the umpire knows something is wrong long before the innings ends, rather than discovering much later that the scoreboard has been dead and no runs were ever recorded during the silence.
Step-by-Step Explanation
Step 1
Start a ping timer
One side sends a ping control frame at a fixed interval, for example every 25 seconds.
Step 2
Expect a pong
The peer must reply with a pong frame within a timeout window.
Step 3
Track responsiveness
Reset a countdown each time a pong arrives; the connection is considered healthy.
Step 4
Declare dead on timeout
If no pong arrives before the timeout, mark the socket dead and close it.
Step 5
Reconnect or clean up
Trigger reconnection on the client, or release server resources for the zombie socket.
What Interviewer Expects
- The concept of a half-open or dead connection
- How ping/pong control frames confirm liveness
- Why idle connections get closed by proxies without traffic
- Choosing sensible interval and timeout values
- Awareness that WebSocket and Socket.IO both provide heartbeats
Common Mistakes
- Assuming a socket is alive just because no close event fired
- Setting the heartbeat interval longer than proxy idle timeouts
- Sending pings but never enforcing a pong timeout
- Confusing application-level pings with the WebSocket ping opcode
- Making heartbeats so frequent they waste bandwidth and battery
Best Answer (HR Friendly)
“Heartbeats are tiny check-in messages that two sides of a real-time connection send back and forth to confirm they're still connected. They catch silent failures where the link dies without warning and keep the connection from being closed by network equipment when nothing else is being sent.”
Code Example
function startHeartbeat(ws, interval = 25000, timeout = 5000) {
let pongTimer
const ping = setInterval(() => {
ws.send(JSON.stringify({ type: 'ping' }))
// If no pong before the timeout, assume the connection is dead
pongTimer = setTimeout(() => ws.close(), timeout)
}, interval)
ws.addEventListener('message', (e) => {
const msg = JSON.parse(e.data)
if (msg.type === 'pong') clearTimeout(pongTimer)
})
ws.addEventListener('close', () => {
clearInterval(ping)
clearTimeout(pongTimer)
})
}Follow-up Questions
- What is a half-open connection and why is it hard to detect?
- How do you pick the heartbeat interval relative to proxy timeouts?
- What is the difference between the WebSocket ping opcode and an app-level ping?
- How can heartbeats be used to measure latency?
- What should happen when a pong times out?
MCQ Practice
1. What primary problem do WebSocket heartbeats solve?
A silent network failure can leave a socket that looks open but is dead; ping/pong reveals it when no pong returns.
2. Why can heartbeats keep an idle connection open?
Intermediaries close connections with no activity; the periodic frames count as activity and reset idle timers.
3. What should happen if a pong is not received before the timeout?
A missing pong within the timeout indicates the peer is unreachable, so the socket should be closed and reconnected.
Flash Cards
What is a heartbeat in WebSockets? — A periodic ping/pong exchange that confirms the connection is still alive.
What is a half-open connection? — A socket that appears connected but is actually dead because the network dropped without a close event.
Why do heartbeats keep idle connections open? — They add periodic traffic so proxies, load balancers, and firewalls don't close the connection on idle timeout.
What happens on a missed pong? — The side treats the connection as dead within the timeout and closes or reconnects it.