TL;DR
WebSockets guarantee nothing about delivery. How to detect dead connections, reconnect with backoff and jitter, and resume with sequence numbers so no message goes missing.
A live dashboard looks fine right up until it is wrong. The prices keep ticking, the chat keeps scrolling — and one message never arrived. Nothing errored. The socket was open, the frames were flowing, and a fill, a chat message, or a state transition simply vanished between the server and the screen. That is the normal failure mode of WebSockets.
A WebSocket feels like a persistent, two-way pipe — and a pipe feels reliable. It is not. The protocol that defines it, RFC 6455, published in December 2011, defines framing, the handshake, control frames, and closing — and nothing else that matters for delivery. It provides no message acknowledgement, no resume or replay, and no redelivery. Sending a message over a WebSocket is fire-and-forget. Guaranteed delivery has to be built at the application layer.
The short version: treat the connection as unreliable transport, not as a delivery guarantee. Sequence every message, buffer replays on the server, resume from a cursor on reconnect, fall back to a snapshot when the cursor is stale, reconnect with jittered backoff, resubscribe deterministically, and make every handler idempotent.
Context: what RFC 6455 actually promises
Start with the contract, because most WebSocket bugs are a misunderstanding of it. RFC 6455 gives you a framed, full-duplex channel over one TCP connection: an HTTP upgrade handshake, text or binary frames, and ping, pong, and close control frames.
Ordering holds, but only within one connection. A single TCP stream delivers bytes in order, so frames on one connection arrive in the order they were sent. A reconnect opens a brand-new connection with no memory of the old one. There is no ordering guarantee across reconnects, and a replay of missed messages can arrive out of order relative to live traffic unless the application sequences messages itself.
Ping and pong are the protocol's only health check, and the spec is deliberately loose about them. On receipt of a ping, an endpoint must send a pong, and a ping may serve as a keepalive. But endpoints only may send pings — the spec sets no ping interval and no timeout, and a pong may be sent unsolicited, without any ping at all. Nothing in the protocol notices a dead peer for you.
The close codes are precise about a narrow set of cases. Code 1000 means a normal closure, 1001 means the endpoint is going away, 1008 is a policy violation, and 1011 is an unexpected server condition. Code 1006 is reserved and must not be sent in a close frame at all — it designates an abnormal closure, one where no close frame was received. Codes 1005 and 1015 are likewise reserved and never sent. In practice 1006 is the code seen most often in failure, and the least informative. The protocol guarantees framing and in-connection order — nothing about delivery, liveness, or recovery.
The four ways messages go missing
Messages go missing in four ways, and each needs a different fix.
The first gap is the dead connection that looks alive. A socket can be half-open: the network path is gone, but no FIN or RST arrived, so readyState still reports open and sends succeed into a void. This is the first of the four problems in Iurii Rogulia's "WebSocket Reconnection Done Right: Backoff, Jitter, and Replay", published in August 2026. The fix is an application-level heartbeat: ping on a schedule, and treat a missing pong as a dead connection. The popular ws library for Node.js does not ping automatically — its documentation shows the application pinging manually, with an example interval of 30,000 milliseconds, and terminating sockets whose isAlive flag was not reset by a pong. That 30 seconds is example code, not a default; pong messages are sent automatically in response to pings, as the spec requires.
The second gap is the outage window itself. While the client is disconnected, the server keeps publishing. Messages sent during that window are gone unless the server kept them somewhere. The fix is a server-side buffer keyed by sequence number, covered in the resume section below.
The third gap is the lost subscription. Subscriptions are per-connection state: when a connection dies, the server forgets which rooms, tickers, or accounts the client wanted, and a reconnected client that waits for messages waits forever. The fix is discipline rather than machinery: resubscribe deterministically in the onopen handler, in a fixed order, from a list the client owns, sent on every open including the first.
The fourth gap is the replay itself. A replay can deliver messages out of order against live traffic, and a retried send can deliver a duplicate. Both need the same two defences: sequence numbers so the client can order and de-duplicate, and idempotent handlers so processing a message twice is harmless. Socket.IO's acknowledgements are callback-based — the last argument to emit() is a callback the receiver invokes — and a retried emit needs idempotency handling, or the duplicate becomes a double charge.
One distinction decides how much machinery a feed needs. Snapshot feeds — order books, tickers — self-heal: the next snapshot corrects any gap. Event feeds — fills, chat, state transitions — do not: a missed event is a correctness bug no later message repairs.
The options
Four honest options form a ladder: each buys a specific property and costs a specific amount of complexity.
Option one is fire-and-forget plus a polling fallback. The client treats the socket as a best-effort stream and periodically re-fetches authoritative state over plain HTTP. This is cheap, and it is the right answer for snapshot feeds, where the poll corrects any gap. Its cost is staleness between polls and the load of the polling itself.
Option two is application heartbeats plus a disciplined reconnect. You add the ping timer and the reconnect loop, so dead connections are detected quickly and the client comes back on its own. This fixes the first and third gaps — detection and resubscription — and it is the minimum viable posture for any production WebSocket client. What it does not fix is the outage window: messages published while disconnected are still lost.
Option three is sequence numbers plus a server buffer plus a resume handshake, and it is the standard pattern for event feeds. The server assigns a monotonic sequence number to every message, keeps a buffer of recent messages, and the client tracks the last sequence number it processed. On reconnect the client sends its cursor; the server replays everything after it, or says the cursor is stale and the client falls back to a REST snapshot. This is the pattern the websocket.org reconnection guide documents, and the one this article recommends as the default for event feeds. Its cost is real — the server must store the buffer and every handler must be idempotent — but it is the only option that closes the outage window.
Option four is to buy the pattern from a platform instead of building it. Socket.IO's connection state recovery, available since 4.6.0, is the clearest example: enable connectionStateRecovery with maxDisconnectionDuration — the docs example is two minutes — and on unexpected disconnect the server stores the socket id, rooms, and data, restores them, and replays missed packets. The client reads socket.recovered to learn whether recovery succeeded. The mechanism is explicit: the server sends a private session id in the handshake and an offset at the end of each packet, and the client sends both back on reconnect. But the documentation warns that recovery "will not always be successful", so a full resync path is still needed. Adapter support is uneven: in-memory yes, Redis no, Redis Streams yes, MongoDB yes since 0.3.0, Postgres and cluster still work in progress. Check your adapter before you promise recovery. Discord's gateway is the textbook production version of the same design: every dispatch carries a sequence number, the client resumes with its token, session id, and sequence number, and an Invalid Session forces a fresh Identify.
Choosing between a queue and a log behind your socket is the same decision as event-driven vs request-driven — a durable log gives you replay, a queue deletes the evidence.
Reconnects: backoff, jitter, and deterministic resubscribe
A reconnect loop fails in exactly one way: every client reconnects at the same instant. A server restart or network blip drops ten thousand clients at once, and if they all reconnect immediately, the storm is a self-inflicted denial-of-service on a server that is already recovering. RFC 6455 section 7.2.3 anticipates this: clients should use backoff after abnormal closures, the first reconnect delayed by a random amount — 0 to 5 seconds is reasonable — and later attempts increasingly longer, e.g. truncated binary exponential backoff.
Jitter is what makes the backoff work: without it, clients still synchronise and arrive in waves. Full jitter — a random delay between zero and the current exponential cap — spreads arrivals smoothly. Rogulia names the thundering herd as the second of its four problems; the fix is exponential backoff plus full jitter, capped so a client does not wait minutes after a brief blip.
Socket.IO ships these defaults: reconnection on by default, delay 1,000 ms, maximum 5,000 ms, exponential backoff. But the io server disconnect and io client disconnect reasons do not auto-reconnect, because those are deliberate disconnections — your code has to handle them explicitly.
Keep the subscription list in the client, in a fixed order, and send it from the onopen handler on every connection. One list, one handler, one code path. The code below is the whole loop.
const MAX_DELAY = 30000; // cap: 30 seconds between attempts
let attempt = 0;
let socket = null;
let lastSeq = 0; // highest sequence number processed so far
const subscriptions = new Set(['prices:BTC', 'fills:account-7']);
function connect() {
socket = new WebSocket('wss://example.com/stream');
socket.addEventListener('open', () => {
attempt = 0;
// Resubscribe deterministically, in a fixed order, on every open.
for (const topic of subscriptions) {
socket.send(JSON.stringify({ type: 'subscribe', topic }));
}
// Resume from the last processed sequence number.
socket.send(JSON.stringify({ type: 'resume', after: lastSeq }));
});
socket.addEventListener('message', (event) => {
const msg = JSON.parse(event.data);
if (typeof msg.seq === 'number') lastSeq = Math.max(lastSeq, msg.seq);
handleMessage(msg); // must be idempotent: replays can duplicate
});
socket.addEventListener('close', (event) => {
// 1000 (normal) and 1001 (going away) are deliberate closes.
// Anything else — including 1006, abnormal closure — reconnects.
if (event.code === 1000 || event.code === 1001) return;
scheduleReconnect();
});
}
function scheduleReconnect() {
// Truncated binary exponential backoff with full jitter:
// the wait is random between 0 and the capped exponential delay,
// so a fleet of clients never reconnects in the same instant.
// First attempt: 0 to 5 seconds, matching RFC 6455 section 7.2.3.
const exponential = Math.min(MAX_DELAY, 5000 * Math.pow(2, attempt));
const wait = Math.random() * exponential;
attempt += 1;
setTimeout(connect, wait);
}
connect();Two details matter. The attempt counter resets only on a successful open, so a flapping connection escalates its delay. And a 1000 or 1001 means someone meant to end the session — do not reconnect against it.
The resume handshake: sequence numbers and the resync fallback
The resume handshake is a small protocol. The client sends its cursor — the last sequence number it processed. The server has three possible answers. Replayed events, in order: apply them, advance the cursor, continue. Nothing missed: the server sends nothing. Or the cursor is stale — older than the buffer — and the server must say so explicitly. That third answer is the one most hand-rolled implementations forget, and a client that silently continues from a stale cursor has a hole nothing will ever fill.
The fallback for a stale cursor is a full resync, usually a REST snapshot: fetch the current state, replace local state wholesale, and set the cursor to the snapshot's sequence number. The snapshot carries the sequence number it was taken at, and the client resumes the stream from there — without that shared number, the client can replay events it already contains or miss events that happened after the snapshot.
The buffer itself is a design decision, not an afterthought. How long you keep messages determines how long a client can be away and still resume: a two-minute buffer, like Socket.IO's documented example, covers a brief blip; a one-hour buffer costs an hour of traffic. The buffer is server-side state with a TTL, and the same reasoning as state and caching decisions applies — size it from the disconnection durations you actually see.
Idempotency protects the effects, not just the state: a replayed event must be safe to process again, and a retried send must be safe to receive twice. The established pattern is the idempotency key: the client generates a unique key — Stripe's documentation suggests a V4 UUID, up to 255 characters — and the server stores the first result and replays it for retries with the same key and the same parameters. Stripe keeps keys for at least 24 hours for API version 1, and the same key with different parameters is an error, not a retry.
// Client: ask the server to replay everything after lastSeq.
socket.send(JSON.stringify({ type: 'resume', after: lastSeq }));
// Server reply — one of two shapes, and the client must handle both:
socket.addEventListener('message', (event) => {
const msg = JSON.parse(event.data);
if (msg.type === 'replayed') {
// Missed events, in order, starting after lastSeq.
for (const item of msg.events) applyEvent(item); // idempotent
lastSeq = msg.events.at(-1)?.seq ?? lastSeq;
return;
}
if (msg.type === 'cursor-stale') {
// The buffer no longer reaches back to lastSeq.
// Do not guess: fetch a fresh snapshot and start from its seq.
fetch('/api/snapshot')
.then((r) => r.json())
.then((snap) => { replaceState(snap.state); lastSeq = snap.seq; });
return;
}
});If the connection drops mid-replay, the client reconnects and resumes from its updated cursor, and the server replays the remainder. The handshake is restartable at every step.
Trade-offs head to head
For a snapshot feed — a ticker, an order book, a presence list — option one or two is enough. The feed self-heals, and a replay buffer buys nothing the next snapshot does not already provide.
For an event feed where a gap is tolerable — activity notifications, non-critical alerts — option two is the sweet spot: heartbeats plus a disciplined reconnect, no server-side buffer to operate.
For an event feed where a missed message is a correctness bug — fills, chat, state transitions — option three is the only honest answer: sequence numbers, a buffer, a resume handshake, and a resync fallback, with idempotent handlers throughout. It is the most expensive option, and the only one that closes the outage window. Socket.IO recovery or a Discord-style resume can buy most of it pre-built, but neither removes the resync fallback — budget for that path regardless.
Managed platforms change the shape of the problem without removing it. AWS API Gateway WebSocket APIs provide no built-in resume or replay — the backend owns that entirely. The gateway assigns a connectionId at $connect, typically stored in DynamoDB; a stale id returns a GoneException. Two hard quotas shape the design: the idle connection timeout is 10 minutes and the maximum connection duration is 2 hours, neither adjustable, and the gateway closes such connections with code 1001. The platform gives you scale and a connection registry; the resume story is still yours.
The costs, summarised: option one costs a polling interval and some staleness; option two, a heartbeat timer and a reconnect loop; option three, a buffer, a cursor, a handshake, a resync path, and idempotency everywhere; option four, a dependency and its adapter limits — and it still costs the resync path. For most teams the honest answer is a mix: snapshot feeds on option one or two, event feeds on option three.
Architecture Decision
Decision: Sequence numbers plus a server-side replay buffer plus a resume handshake, with jittered-backoff reconnects and a REST snapshot resync fallback, as the default for event feeds; snapshot feeds use heartbeats plus reconnect plus periodic polling.
Context: WebSocket clients in production lose messages four ways — half-open connections, the outage window, lost subscriptions, and out-of-order or duplicated replays — and RFC 6455 guarantees none of the properties that would prevent them. Event feeds cannot self-heal, so a missed event is a correctness bug.
Options considered: Fire-and-forget with polling; heartbeats plus reconnect only; sequence numbers with a buffer and resume handshake; Socket.IO recovery or a Discord-style resume; a managed gateway such as AWS API Gateway WebSocket APIs.
Why this one: It is the only option that closes the outage window. The handshake has three explicit answers — replay, current, or stale cursor — so every failure state has a defined behaviour instead of a silent hole, and building it directly keeps the team in control of buffer sizing rather than inheriting an adapter's limits.
What it costs you: A buffer to store and size, a cursor to track, a snapshot endpoint for resync, idempotent handlers everywhere, and monitoring for evictions and resync rates. Expect a week of focused work, not an afternoon.
When to reverse it: If the feed turns out to be snapshot-shaped, drop the buffer and the handshake and fall back to heartbeats plus polling. If a platform's built-in recovery matures to cover your adapter, adopt it and delete the hand-rolled handshake. If clients almost always fall back to resync, the buffer is too short: lengthen it, or resync on every reconnect.
Recommendation and when NOT to use this
The recommendation is the decision above, with one addition: test it by breaking it. Kill the connection mid-replay, kill it during the resync fetch, drop the server while a thousand clients are connected — and watch the reconnect storm not happen, because the jitter spreads it. A resume protocol tested only on a clean disconnect is a demo, not a system.
Do not build this for a feed that does not need it. A dashboard that refreshes every thirty seconds does not need a replay buffer, and a notification stream where a missed notification is an annoyance does not need idempotency keys. Match the machinery to the cost of a missed message.
And do not use WebSockets at all when the shape is wrong. If updates flow in one direction, server-sent events give you automatic reconnection and a simpler protocol. If the interaction is request and response, plain HTTP — see our REST vs GraphQL vs gRPC guide — is easier to cache and to debug. WebSockets earn their complexity when the client also sends messages on the same channel, when sub-second latency matters in both directions, and when the connection is genuinely long-lived. A chat room qualifies. A form that occasionally polls for a status does not.
Never trust the socket. Trust the sequence number, the cursor, the snapshot, and the idempotency key.
Why This Matters
Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.
Trade-offs to Consider
Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.
When NOT to Use This
Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.
Decision Framework
Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.