Engrain by ByteRush

WEB.16.02 Mid-level· 12 minCore — asked often

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.

Dropping, reconnecting and resyncing a chatStep 1 of 4

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
  1. The chat connects and has seen messages up to seq 120. The phone switches from Wi-Fi to 4G; the socket closes.
  2. The user sends "On my way" while offline. The client keeps it in an outbox instead of losing it.
  3. After a backoff delay, the client reconnects and first sends { type: resync, after: 120 }.
  4. 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?

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.”

Stays on your device. Nothing is uploaded.
Follow-up How do you handle a dropped WebSocket connection without losing messages?
Sequence numbers, resync from the last seen sequence on reconnect, de-duplication, and an outbox for unsent messages with client-side ids.
Follow-up How do you authenticate a WebSocket connection?
Browsers cannot set headers on the handshake: use a cookie (and check Origin), or a short-lived token in the first message or the URL, then verify it on the server.
Follow-up How do you scale WebSockets across servers?
Sticky sessions or a connection gateway, plus a pub/sub layer (such as Redis) so a message on one server reaches users on others.

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.
Your solution
Ctrl/⌘ + Enter

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
The handshake is a GET with Upgrade: websocket and a random Sec-WebSocket-Key; the server proves it understood with Sec-WebSocket-Accept Source: RFC 6455: The WebSocket Protocol.
Cookies are sent with the handshake, so servers must check 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
Order and de-duplicate with server-assigned sequence numbers, not client clocks. Give outgoing messages a client id too, so the server can ignore a resend after reconnecting.
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

Close code 1006 means the connection dropped with no close frame. Heartbeats every 20–30 seconds find dead connections and keep proxies from closing idle ones.
Also watch 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
Scale with a gateway or sticky sessions and pub/sub between servers.
WebTransport, over HTTP/3, adds many streams and unreliable datagrams for games and media: Chrome 97, Firefox 114, Safari 26.4 Source: MDN: The WebSocket API.
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?