Skip to main content
All articles

/2 min read

WebSocket reconnection with backoff and heartbeats

Exponential backoff, jitter, max attempts, ping/pong health checks, and resuming state after reconnect.

By Juliano Alves

WebSockets drop when networks flap, laptops sleep, or deploys restart servers. Clients need predictable reconnection behavior—not infinite tight loops hammering your origin.

Exponential backoff with jitter#

let attempt = 0;
const base = 500;
const max = 30_000;

function delayMs() {
  const exp = Math.min(max, base * 2 ** attempt++);
  const jitter = exp * (0.5 + Math.random() * 0.5);
  return jitter;
}

Reset attempt on successful onopen.

Heartbeats#

Proxies may kill idle sockets. Client sends ping frames (or app-level {type:'ping'}) every 25–45s; server responds. If two pings miss, close and reconnect.

State on resume#

After reconnect, re-sync server state: send last seen message ID or cursor so the server replays missed events or sends a snapshot.

Summary#

Treat WebSockets as best-effort streams: backoff reconnects, heartbeats for middlebox survival, and explicit resync after every new connection.

Have a project in mind?

contato@julianoalves.me

Rio de Janeiro · UTC−3