Skip to content

Reconnect and resume

When a live connection drops, the client reopens it with capped, jittered backoff, then resumes from the last message it processed so the gap is replayed rather than lost, and falls back to a full refetch when it can't be.

On this page

What it is

A live connection to the server, over a WebSocket or a server-sent event stream, is going to break: a phone changes networks, a laptop sleeps, a proxy times out an idle socket, a server restarts. Socket.IO's documentation states that temporary disconnections are unavoidable whatever the connection quality, and Discord's gateway documentation calls them a semi-regular event that clients should expect. Reconnect and resume is the client-side pattern for living with that: notice the drop, reopen the connection without stampeding the server, and pick up the stream where it stopped so the screen doesn't quietly miss anything.

Detecting the drop. For a WebSocket, the browser fires a close event carrying a CloseEvent with three fields: code (the close status code), reason (a server-specific string) and wasClean (true if the closing handshake completed). A connection attempt that fails fires error and then close with wasClean false, so each attempt ends in either open or close, and close is the one place to hang reconnection logic. A drop the network doesn't report, such as a laptop lid closing, may produce no event for a long time, which is why a heartbeat with a timeout is the second detector.

For an EventSource, the HTML standard does the first half for you. On a network error the browser normally sets readyState back to CONNECTING, fires error, waits the stream's reconnection time (which the server can set with a retry: field, in milliseconds), optionally a little longer, and reopens; the standard lets it give up instead when it knows a retry would be futile. If the stream carried id: fields, the new request includes a Last-Event-ID header with the last one received. It also defines when the browser stops: a response that isn't a 200 with the event-stream content type fails the connection, readyState becomes CLOSED, and no further reconnect is attempted; your code has to create a new EventSource.

Reconnecting without a stampede. When a server restarts, all the clients attached to it drop at the same moment, and if they all retry on the same schedule they come back in a spike. The AWS Architecture Blog's analysis of this describes capped exponential backoff (multiply the wait by a constant after each failed attempt, up to a maximum) and shows in simulation that backoff on its own still leaves clusters of calls. Adding jitter spreads them: with full jitter the client sleeps a random time between zero and the current backoff value. In its 100-client simulation, jitter cut the number of calls by more than half compared with plain exponential backoff, and finished sooner. Our advice for the browser: a base of about a second, a cap of 30 seconds or so, full jitter, and reset the attempt counter once a connection has stayed open for a while so a flaky hour doesn't leave you at the cap for good.

Two signals let you skip the wait. The window's online event fires when the browser regains network access and navigator.onLine flips to true, which is a good moment to retry immediately; MDN notes it doesn't prove a particular site is reachable, so the backoff loop still has to handle a failure after it. And the close code can tell you not to retry at all: a 1008 policy violation or an authentication rejection is unlikely to pass on the second try, so surface the error instead of backing off into it.

ts
let lastSeq = 0;            // last message we applied
let attempt = 0;
let socket: WebSocket | undefined;
let stoppedByUser = false;

function connect() {
  socket = new WebSocket(WS_URL);

  socket.addEventListener('open', () => {
    // ask for everything after what we have
    socket!.send(JSON.stringify({ type: 'resume', sessionId, seq: lastSeq }));
  });

  socket.addEventListener('message', (e) => {
    const msg = JSON.parse(e.data);
    if (msg.type === 'resumed') { attempt = 0; setStatus('live'); return; }
    if (msg.type === 'invalid_session') { void fullResync(); return; }
    if (msg.seq <= lastSeq) return; // replayed duplicate
    apply(msg);
    lastSeq = msg.seq;
  });

  socket.addEventListener('close', (e: CloseEvent) => {
    if (stoppedByUser || e.code === 1008) return; // retrying won't help
    setStatus('reconnecting');
    scheduleReconnect();
  });
}
let reconnectTimer: ReturnType<typeof setTimeout> | undefined
function scheduleReconnect() {
  const cap = 30_000, base = 1_000;
  const ceiling = Math.min(cap, base * 2 ** attempt);
  const delay = Math.random() * ceiling; // full jitter
  attempt++;
  reconnectTimer = setTimeout(connect, delay);
}

window.addEventListener('online', () => {
  if (socket?.readyState === WebSocket.CLOSED) { clearTimeout(reconnectTimer); connect() };
});

Resuming the stream. The resume half needs the server to number its messages and keep recent ones available for replay. Discord's gateway is the textbook version: each dispatched event carries a sequence number s, the client stores the session_id from the Ready event and the last s it received, and after a drop it opens a fresh connection and sends a Resume payload with its token, session ID and seq. The gateway then replays the events the client missed in the same form it would have delivered them live, followed by a Resumed event; if the session can't be resumed it answers Invalid Session and the client starts over with a full Identify.

Socket.IO added the same idea as connection state recovery in version 4.6.0. The server includes an offset at the end of each packet and a private session ID in the handshake; on reconnect the client sends both, and the server, if it still has the session, restores the socket's ID, rooms and data and delivers the missed packets. The server keeps that state for maxDisconnectionDuration, two minutes by default, and the docs ask for a finite value because the feature targets short interruptions. A recovered flag on both sides reports whether it worked, and the same page is explicit that recovery doesn't succeed in all cases, so you still need a path that resynchronizes client and server from scratch.

When to use it

Reach for resume whenever a screen shows a stream that would be wrong with a hole in it: a chat thread, a shared document's edits, a live order book, a notification feed, a collaborative cursor layer. Those are ordered streams, which is what a sequence-number buffer handles well, and the buffer's retention decides how long a gap it can bridge. A default of two minutes of retained state on the server, as above, is a reasonable picture of the window this pattern is built for.

Decide what the user sees and what happens to their outgoing actions while you're reconnecting. A strong answer names a visible but quiet reconnecting state (a banner or a status dot, not a modal), keeps the existing content on screen rather than blanking it, and queues outgoing messages locally with a client-generated ID so they can be sent once the socket is open and deduplicated if the first attempt actually made it. See Sync queues and client idempotency for that queue.

Plan the fallback at the same time as the happy path. The server's replay buffer is finite, so after a long gap (an overnight sleep, a session the server evicted) resume may be refused. The client should treat that refusal as a normal outcome: fetch a fresh snapshot of the state, note the version or sequence number the snapshot was taken at, and subscribe from there. An invalid-session reply, or a recovered flag that comes back false, is that signal.

When not to

Don't build resume for a one-shot request. A request that failed is retried with backoff where a retry is safe, and that's the end of it; there's no stream position to carry across. Likewise, if the client polls instead of holding a connection, there's no connection to reopen, and a poll that includes a cursor handles its own gaps. The transport choice itself is a separate topic: WebSockets, server-sent events and polling.

Don't build a replay buffer when a full refetch is cheap. A dashboard showing twenty numbers, a presence list, a settings page that happens to be live: on reconnect, request the current state and replace what's on screen. It's simpler than numbering events, costs the server a little more per reconnect, and has no gap-too-long failure mode. Resume earns its complexity when the state is large, the history matters (messages, edits) or reconnects are frequent.

Don't rely on the browser's automatic EventSource reconnection when you need control over the schedule or the failure. Its wait is the reconnection time (a browser default, or the server's retry value), any further backoff is the browser's decision rather than yours, and after a non-200 response it stops for good. For a one-way stream where that's acceptable it's the least code; for anything else, manage the lifecycle yourself.

Compared

ApproachHow it worksReach for it whenWhere it's the wrong fit

Browser-managed reconnect (EventSource)

Browser reopens after the retry delay and sends Last-Event-ID

A one-way server-to-client stream and you want almost no reconnect code

You need backoff, jitter or recovery after a non-200; it stops on those

Sequence-number resume (Discord gateway, Socket.IO 4.6+)

Client sends the last sequence or offset; server replays the gap from a bounded buffer

Ordered streams with short drops, where each missed event matters

Long gaps outrun the buffer; the server needs a buffer or log it can replay from

Full resync on reconnect

Client refetches the whole state and replaces the screen

Small state, rare drops, or a server with no replay buffer

Large state or frequent blips: heavy per reconnect and a visible flash

Snapshot then stream

Fetch a versioned snapshot, then subscribe from that version

Large state and gaps that may be long; the general shape that scales

More moving parts; you must order the snapshot against the stream

In a picture

Sends seq 41, 42lastSeq = 42

Step 1 of 4

A numbered live stream

The server numbers each message. The client applies them in order and remembers the highest sequence it has applied, here 42.

How to say it in an interview

The common mistake

Quiz

Your page uses an EventSource. The server restarts and the reconnect request gets a 503. What does the browser do?
You have capped exponential backoff on reconnect. A colleague asks why you also multiply the delay by Math.random(). What's the reason?
After a long sleep, the client reconnects and sends resume with seq 42. The server answers that the session is invalid. What should the client do next?
After a resume, the first replayed message has the same sequence number as the last one the client already applied. Why, and what should the client do?

Questions that use this

Related

Sources

  1. HTML Living Standard: Server-sent events
  2. MDN: Using server-sent events
  3. WebSockets Standard (WHATWG)
  4. MDN: CloseEvent
  5. MDN: WebSocket() constructor
  6. MDN: Window online event
  7. AWS Architecture Blog: Exponential Backoff and Jitter
  8. Socket.IO 4.x documentation: Connection state recovery
  9. Socket.IO changelog: Version 4.6.0
  10. Discord API documentation (docs repository): Gateway, Resuming
  11. OneUptime: Reconnect a Cleanly Closed WebSocket with Backoff
Sign in to report a mistake