How to Implement WebSocket Heartbeats and Reconnects
Detect half-open connections with ping frames, reconnect with jittered backoff, resync state after gaps, and test recovery without waiting for real outages.
On this page
Introduction
A WebSocket connection looks like a persistent pipe until it is not. Networks fail silently: a laptop changes Wi-Fi, a NAT gateway drops its mapping, a load balancer reaps an idle connection, and the client is left writing to a socket no one is reading. Without explicit liveness detection the client discovers the failure only when a write eventually times out, which can take many minutes, and the user sees a frozen interface the whole time. Heartbeats solve detection: a periodic ping with a deadline turns a silent failure into a prompt one. Reconnection solves recovery: an automatic retry loop with bounded, jittered backoff restores the pipe without user action. Resync solves correctness: after a gap, the client must catch up on what it missed rather than continuing from a stale view. This tutorial implements all three for a browser client and a Go server, using protocol control frames rather than application messages, and finishes with tests that simulate each failure without waiting for a real outage.
Heartbeat with control frames
RFC 6455 defines ping and pong as control frames: nine-byte-class messages that the peer must answer automatically at the protocol layer. They are invisible to application message handlers, which makes them a clean liveness channel that cannot interfere with the data protocol. The browser cannot send pings directly through the JavaScript API, so a browser client has two options: rely on the server to ping and treat the absence of any inbound traffic as failure, or send a small application-level heartbeat when the API cannot be used. Server-side clients in Go, Python, or Rust should always use real control frames. The interval must be shorter than the shortest idle timeout anywhere on the path: cloud load balancers commonly close connections idle for sixty seconds, so pinging every twenty to thirty seconds keeps the mapping alive. The deadline matters more than the ping itself: if a pong has not arrived within the interval plus slack, the connection is declared dead, because at that point continuing to write would only queue bytes into a void.
Client implementation
The client below wraps the browser WebSocket API with a heartbeat driven by the absence of inbound frames, exponential backoff reconnection, and a resync message carrying the last sequence number seen.
type Listener = (msg: { seq: number; kind: string; data: unknown }) => void;
export class ReconnectingSocket {
private ws: WebSocket | null = null;
private lastSeq = 0;
private attempt = 0;
private timer: number | undefined;
private watchdog: number | undefined;
constructor(private url: string, private onMessage: Listener) {}
connect() {
this.ws = new WebSocket(this.url);
this.ws.onmessage = (e) => {
this.resetWatchdog();
const msg = JSON.parse(e.data as string);
this.lastSeq = msg.seq;
this.onMessage(msg);
};
this.ws.onopen = () => {
this.attempt = 0;
this.resetWatchdog();
this.send({ kind: 'resync', since: this.lastSeq });
};
this.ws.onclose = () => this.scheduleReconnect();
this.ws.onerror = () => this.ws?.close();
this.resetWatchdog();
}
private resetWatchdog() {
clearTimeout(this.watchdog);
this.watchdog = setTimeout(() => this.ws?.close(), 45_000);
}
private scheduleReconnect() {
clearTimeout(this.watchdog);
const base = Math.min(30_000, 500 * 2 ** this.attempt);
const delay = Math.round(base * (0.5 + Math.random() * 0.5));
this.attempt = Math.min(this.attempt + 1, 8);
this.timer = setTimeout(() => this.connect(), delay);
}
send(obj: object) { this.ws?.send(JSON.stringify(obj)); }
close() { clearTimeout(this.timer); clearTimeout(this.watchdog); this.ws?.close(); }
}
The watchdog closes the socket when nothing, not even a pong or a periodic server ping, has arrived for forty-five seconds. The jitter in the backoff prevents thousands of clients from retrying in lockstep after a server restart, which would otherwise recreate the outage the moment it ends.
Server implementation
The server pings every client on a fixed interval and reads with a deadline, so dead connections are reaped promptly instead of occupying a file descriptor and a goroutine forever. The gorilla connection is illustrative; the pattern is identical in other libraries.
func readPump(conn *websocket.Conn, out chan<- inbound) {
conn.SetReadLimit(64 << 10)
conn.SetReadDeadline(time.Now().Add(60 * time.Second))
conn.SetPongHandler(func(string) error {
conn.SetReadDeadline(time.Now().Add(60 * time.Second))
return nil
})
for {
_, msg, err := conn.ReadMessage()
if err != nil { close(out); return }
out <- parse(msg)
}
}
func pingPump(conn *websocket.Conn, done <-chan struct{}) {
ticker := time.NewTicker(25 * time.Second)
defer func() { ticker.Stop(); conn.Close() }()
for {
select {
case <-ticker.C:
conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
if err := conn.WriteMessage(websocket.PingMessage, nil); err != nil { return }
case <-done:
return
}
}
}
Each pong extends the read deadline, so a live client keeps the connection while a dead one hits the deadline and the read loop exits within one interval. The write deadline on the ping protects against a stuck TCP send buffer, which would otherwise block the ping loop indefinitely on a half-open connection, exactly the case heartbeats exist to detect.
State resynchronization
Reconnection restores the pipe but not the data. Every message the server sends should carry a monotonically increasing sequence number per stream. On reconnect the client reports the last sequence it processed, and the server answers in one of two ways. For small gaps the server replays the buffered messages, which requires keeping a bounded replay buffer, typically the last few hundred messages or the last minute of traffic, sized from the expected reconnect duration. For large gaps the server responds with a reset marker followed by a full snapshot, and the client rebuilds its view. The reset path matters: a client that was offline for an hour must not receive ten thousand replay messages, and the sequence numbering lets the server make that decision mechanically. Idempotent processing on the client side is still required, because at-least-once delivery during reconnect can duplicate messages that were sent but not acknowledged as processed. Acknowledgment semantics belong to the application protocol; the transport only guarantees ordering within one connection.
Test the failure paths
Every failure mode in this design is testable without a real outage. Kill the connection server-side and assert the client reconnects within the expected backoff window. Freeze the server without closing the socket, by suspending the process or blocking writes, and assert the client watchdog fires within the deadline, which validates the detection logic rather than just the close handling. Advance a fake clock to test backoff timing deterministically instead of sleeping through thirty-second delays. Assert the resync flow by dropping the connection mid-stream, delivering messages during the gap into a capture buffer, reconnecting, and verifying the client both receives the replay and preserves ordering. Finally, run a herd test: start one hundred clients, kill the server, restart it, and assert the reconnect arrivals are spread across the jitter window rather than arriving in one synchronized spike.
const sock = new ReconnectingSocket(url, collector.push);
vi.useFakeTimers();
sock.connect();
server.dropConnection(1);
vi.advanceTimersByTime(500);
expect(sock.connected()).toBe(false);
vi.advanceTimersByTime(500);
expect(sock.connected()).toBe(true);
expect(collector.messagesFromSeq(0)).toHaveLength(3);
Common pitfalls
- No watchdog on the client. The browser fires onclose for some failures but not half-open ones, so the UI silently freezes until a write fails.
- Relying on TCP keepalive alone. Default kernel keepalive intervals are far longer than user-facing freshness requires and are invisible to application code.
- Fixed reconnect delay without jitter. Every client retries on the same schedule, recreating the outage in a synchronized loop.
- Reconnecting without resync. The connection is up but the view is stale, which is worse than a visible error because it lies to the user.
- Unbounded replay buffers. Replaying an hour of traffic on reconnect starves fresh messages; cap the buffer and fall back to snapshot.
- Blocking ping writes. A ping without its own write deadline stalls on a broken send buffer and stops the heartbeat from doing its job.
Conclusion
A reliable WebSocket layer is three mechanisms stacked: control-frame heartbeats with hard deadlines to detect dead connections fast, jittered exponential backoff to recover them without herd effects, and sequence-based resync to make recovery correct rather than merely connected. Use protocol ping and pong frames where the API allows, size intervals against the shortest idle timeout on the path, and keep replay buffers bounded with a snapshot fallback. Then test each failure by injecting it directly, because an outage is a poor environment for discovering that the reconnect path was never exercised. The result is a connection layer whose failures are brief, visible, and recoverable instead of long and silent.
Sources: MDN: Writing WebSocket servers, RFC 6455: WebSocket protocol, WHATWG: WebSockets standard.
FAQ
- Why not just use application-level heartbeat messages?
- Application heartbeats work but are visible to your protocol, consume framing overhead, and can be blocked by buggy intermediaries that filter message types. Control frames are part of the base protocol and transparent to application code.
- What interval should the heartbeat use?
- Half of the shortest idle timeout on the path, and at least a few seconds. Cloud load balancers commonly drop idle connections after 60 seconds, so a 20 to 30 second ping interval is a safe default.
- Should the client or server send pings?
- Both directions are legal. Servers commonly ping to reap dead connections efficiently, while clients ping to keep intermediaries from idling out. A robust deployment does both with independent deadlines.
Report a problem with this articleOpens a pre-filled issue on GitHub.