Skip to content

Lesson 8 of 9 · 24m

Reconnects, Resume, and Ordering: Making Loss Explicit

Clients will disconnect constantly; correct systems make gaps detectable, resynchronizable, and bounded in cost.

A reconnect is not an edge case. It is the normal lifecycle of a mobile client. If your design assumes a clean continuous stream, production will disassemble that assumption one subway ride at a time.

Reconnect with backoff and jitter

function backoff(attempt) {
  const base = Math.min(30000, 500 * 2 ** attempt);
  return base * (0.5 + Math.random() * 0.5);
}
async function connect(attempt = 0) {
  const ws = new WebSocket("wss://app.example/realtime");
  ws.onopen = () => { attempt = 0; };
  ws.onclose = (e) => e.code === 1008 ? showSignedOut() : setTimeout(() => connect(attempt + 1), backoff(attempt));
}

Jitter prevents synchronized reconnect storms. Cap the delay, but do not cap attempts silently in a way that leaves the UI dead forever. Show state: connecting, degraded, offline. Users forgive slowness more readily than mystery.

Sequence numbers expose gaps

Every stream that matters needs ordering metadata:

{ "type":"room:event", "room":"42", "seq":10842, "id":"evt_..." }

The client tracks the highest contiguous sequence per room. If it sees 10844 after 10842, it knows 10843 is missing. At that point the client can request a gap fill if the server retains recent events, or invalidate local state and fetch a snapshot.

No sequence number means no way to distinguish loss from silence. Heartbeats do not solve this; they only prove the connection is alive.

Resume is snapshot plus deltas

The universal recovery pattern is boring because it works:

1. reconnect and authenticate
2. send last known cursor / seq / Last-Event-ID
3. server replays retained events after that cursor
4. if cursor is too old, server sends snapshot + current cursor
5. client applies snapshot, then buffered deltas

Do not assume the broker can replay everything. Redis pub/sub cannot. Kafka can, but replaying a compacted high-volume stream to every reconnecting browser may be economically absurd. Often the right answer is a cheap application snapshot endpoint plus a short retention buffer.

Ordering scopes matter

Global ordering is expensive and usually unnecessary. Per-room or per-document ordering is enough for most collaborative features. A user's own operations need causal ordering: if the client sends two edits, receiving the ack or event for the second must not imply the first succeeded unless the protocol says so.

IDs enable idempotency. A client retrying msg.client_id = abc should not create two chat messages. The server stores or remembers the client mutation ID long enough to deduplicate retries.

Buffering on the client is part of correctness

While fetching a snapshot, live events keep arriving. Buffer them, apply the snapshot, then apply only events newer than the snapshot cursor. If you render live events immediately, users see future state layered over stale state — duplicated rows, missing edits, and impossible UI.

Field notes

  • Reconnect tests must include server restarts, expired auth tokens, proxy timeouts, and laptop sleep, not just ws.close() in devtools.
  • Auth often expires mid-connection. Decide whether the socket dies immediately or receives a reauth challenge; silent privilege drift is worse.
  • Sequence numbers must be generated in the ordering authority, usually a database transaction or single ordered stream.
  • If a client cannot reconstruct correct state after a gap, close the stream loudly. Silent corruption is the worst outcome.

Was this lesson helpful?

Sign in to rate