A WebSocket heartbeat is the keep-alive mechanism that stops a persistent connection from silently closing when no data is flowing across it. If you've ever watched a live sports score freeze mid-match, or had a chat message deliver three minutes late, a dead connection with no heartbeat is often the culprit. Understanding how the mechanism works makes you a sharper developer and a better-informed user of real-time software.
What problem does a WebSocket heartbeat solve?
A WebSocket keeps a persistent, two-way connection open between a client and a server. That's its defining quality. But networks aren't patient. Load balancers, NAT gateways, and corporate firewalls all enforce their own idle-timeout rules, typically somewhere between 30 seconds and 5 minutes. When a connection sits quietly, those intermediaries assume it's dead and close it without telling either end.
The result is a "half-open" connection. The client thinks it's still connected. The server thinks it's still connected. Neither is sending data. The next message one of them tries to send simply vanishes. The user sees a stale screen or an error. This is what a heartbeat prevents.
How the ping-pong frame mechanism works
The WebSocket protocol (defined in RFC 6455) includes two built-in control frame types designed exactly for this purpose: the ping frame and the pong frame. The exchange is simple.
- One side (usually the server) sends a ping frame at a regular interval, say every 30 seconds.
- The receiving side is required by the protocol to respond with a pong frame immediately.
- If no pong arrives within a timeout window, the sender assumes the connection is dead and closes it deliberately, then triggers a reconnect.
Ping and pong frames carry an optional payload of up to 125 bytes. Most implementations send an empty payload or a short timestamp. The payload content doesn't matter; the round-trip itself is the signal.
Some applications implement an "application-level heartbeat" instead, sending a small JSON message like {"type":"ping"} over the data channel rather than using the protocol's native frames. This works, but it's heavier. Protocol-level pings are processed by the WebSocket layer directly and don't reach the application code on the receiving end, which keeps overhead low.
Choosing the right interval
The heartbeat interval is a trade-off. Set it too long and an idle-timeout will close your connection before the heartbeat fires. Set it too short and you're burning bandwidth and CPU sending meaningless frames thousands of times a minute across a large user base.
A common starting point is 25 seconds. This sits safely below most infrastructure timeouts, which rarely drop below 30 seconds. AWS Application Load Balancer defaults to a 60-second idle timeout, so a 25-second heartbeat gives you a comfortable buffer. Cloudflare's WebSocket proxy enforces a 100-second idle limit, which is more forgiving. The right number depends on your specific stack.
The timeout window for expecting a pong response is typically 5 to 10 seconds. If a pong hasn't arrived within that window, the connection is considered broken regardless of what either side believes.
Who sends the ping: client or server?
RFC 6455 permits either side to send pings. In practice, servers almost always initiate them. There are two reasons for this. First, the server typically has authoritative knowledge of its infrastructure's timeout rules. Second, a server managing thousands of simultaneous connections can stagger its ping schedule, sending heartbeats in batches rather than simultaneously, which smooths the CPU spike.
Browsers handle this differently. The WebSocket API exposed to JavaScript doesn't give client code direct access to the protocol-level ping/pong frames. Browser vendors implement automatic ping responses internally, but they don't expose a way to programmatically send pings from JavaScript. If you need a client-initiated heartbeat in a browser app, you're using an application-level message, not a protocol frame. Native apps (iOS, Android, desktop) using lower-level WebSocket libraries do have access to the protocol frames directly.
Heartbeats in real-world systems
Live trading platforms and sports data feeds are particularly sensitive to silent connection failures. A 3-second delay in a price update can cost real money. These systems often run heartbeat intervals as low as 10 seconds, with pong timeouts of 3 seconds and automatic reconnect logic that fires in under a second.
The reconnect strategy matters as much as the heartbeat itself. A naive reconnect that fires immediately on every failure can hammer a struggling server. A well-designed client uses exponential backoff: wait 1 second, then 2, then 4, then 8, up to a maximum of perhaps 30 seconds. This prevents the "thundering herd" problem where thousands of clients simultaneously try to reconnect after a brief server hiccup.
This kind of connection resilience is closely related to how load balancers manage persistent connections, since sticky sessions and connection draining rules can interact unpredictably with heartbeat logic during deployments or failovers.
Debugging a broken heartbeat
When a heartbeat stops working, the symptoms are almost always the same: the UI freezes, messages stop arriving, but the connection indicator (if one exists) still shows green. The browser's DevTools Network tab is your first stop. Under the WS (WebSocket) sub-tab in Chrome or Firefox, you can see every frame, including ping and pong frames, with timestamps. A ping with no corresponding pong is a clear sign the other end went silent.
Server-side, most WebSocket libraries log connection lifecycle events. Node.js's ws library, for instance, emits a pong event on each response and exposes an isAlive flag you can set and clear in a termination check loop. That loop is typically run every 30 seconds using setInterval. Any client whose isAlive flag is still false when the interval fires gets its socket terminated and removed from memory.
Three things cause most heartbeat failures in production. Network path changes (a user switches from Wi-Fi to mobile data) break the underlying TCP connection without sending a close frame. Memory pressure on the server causes the event loop to stall, delaying pong responses past the timeout window. And misconfigured reverse proxies buffer or drop control frames entirely, which is a subtle but real failure mode worth checking when heartbeats work in development but not in staging.

