WebSockets: two-way real time that survives a bad network
How the WebSocket upgrade works, full-duplex messaging, heartbeats, reconnecting with backoff and resyncing missed messages, message ids and ordering, authentication on connect, scaling with sticky sessions and pub/sub, and WebTransport.
Comes up in: Frontend system design, Web fundamentals, Machine coding
Learn#
Meena’s support chat loses messages whenever customers switch from Wi-Fi to mobile data. The socket closes silently, and anything sent or received in the gap is gone.
A WebSocket is a long-lived connection where both sides can send messages at any time: full duplex. It starts as an HTTP request with Upgrade: websocket; the server answers 101 Switching Protocols, and from then on the connection carries small framed messages instead of HTTP.
The protocol does not survive network changes or remember anything. Reconnection is your job: notice the close, wait with backoff (JS.11.06), connect again, and ask the server for what you missed. Number every message with a sequence, so the client can say “after 120” and drop duplicates.
Network
- ws closed (code 1006)
State
- lastSeq = 120
- outbox: []
The chat connects and has seen messages up to seq 120. The phone switches from Wi-Fi to 4G; the socket closes.
Read the steps as text
- The chat connects and has seen messages up to seq 120. The phone switches from Wi-Fi to 4G; the socket closes.
- The user sends "On my way" while offline. The client keeps it in an outbox instead of losing it.
- After a backoff delay, the client reconnects and first sends { type: resync, after: 120 }.
- The server replays 121–123. The client drops any seq it already has, then flushes the outbox.
Predict#
Predict first
A phone loses signal in a tunnel. The WebSocket's close event fires… when?
TCP does not notice a silent network loss until it tries to send. That is why apps send heartbeats: small ping messages every 20–30 seconds, closing and reconnecting if no reply arrives. People expect the browser to know at once.
Interview angle#
Say it like this — about 30 seconds
“A WebSocket starts as an HTTP upgrade and then gives a full-duplex message channel. To survive drops, I send heartbeats to detect dead connections, reconnect with exponential backoff and jitter, and number messages so the client can resync: on reconnect it sends the last sequence it saw, the server replays what was missed, and the client drops duplicates. Outgoing messages wait in an outbox with client ids. For auth, I send a short-lived token on connect and check the Origin header.”
Follow-up How do you handle a dropped WebSocket connection without losing messages?
Follow-up How do you authenticate a WebSocket connection?
Follow-up How do you scale WebSockets across servers?
Practice#
On your own
Build the reconnecting chat client: resync on every open, skip duplicates, queue outgoing messages, and reconnect with backoff. The tests use fake sockets.
Done when
- Every open sends a resync with the last seen sequence, then flushes the outbox in order.
- Duplicate or old sequences are not passed to
onMessage. - Closes schedule reconnects with growing attempts;
close()stops reconnecting.
Remember#
Try to answer each card before you open it. Then add them to your reviews.
What response code completes a WebSocket upgrade?
101 Switching Protocols.
Why send heartbeats on a WebSocket?
To detect dead connections that still look open.
How does a client get messages it missed while offline?
It reconnects and asks the server for messages after its last sequence number.
Why can't you put an Authorization header on a browser WebSocket?
The browser WebSocket API does not allow custom handshake headers.
Go deeper
Four layers. Stop at the one your interview needs; each ends with a quick check.
The core ideaEvery round
Upgrade: websocket and a random Sec-WebSocket-Key; the server proves it understood with Sec-WebSocket-Accept Source: RFC 6455: The WebSocket Protocol.Origin to stop other sites from connecting as the user.Check yourself: Which header must a WebSocket server check to stop cross-site hijacking?
Origin.
How it works underneathSenior rounds
Check yourself: Why use a sequence number per conversation rather than timestamps?
Sequences are gap-free and ordered by the server; clocks differ between devices.
Edge cases and trapsWhere people slip
bufferedAmount: sending faster than the network drains fills memory.Check yourself: What does close code 1006 mean?
Abnormal closure: the connection dropped without a close frame.
In productionStaff-level answers
Check yourself: What does WebTransport add over WebSockets?
Multiple streams and unreliable datagrams over HTTP/3, without head-of-line blocking.
Finished the five steps? Mark it, and its cards join your reviews.
Last checked 2026-11-01. Spot a mistake? Use “Report an error” below — fixes are listed on the corrections page.
Interview questions this answers
- How do you handle a dropped WebSocket connection without losing messages?
- How do you authenticate a WebSocket connection?