WebSocket: handshake, frames, ping/pong and closing
WebSocket (RFC 6455) turns an HTTP connection into a permanent two-way channel after a handshake with Upgrade and a 101 response. Messages travel as frames: text, binary and control (ping, pong, close). Code 1000 is a normal close, while 1006 is abnormal and never sent over the network. The protocol resends nothing, so the client reconnects with jitter and asks for missed events by id.
Networking · Real-time
After Wi-Fi comes back the chat shows new messages, but some went missing. Where did they go?
A user rides the metro: the network disappears for a minute and returns. The chat is online again, new messages arrive, but those that came during the drop never appeared. This is not a server bug: WebSocket does not deliver what was sent while the connection did not exist. The job of the client and the tester is to understand what the protocol guarantees and what the application must do. The lesson covers the handshake, frames, ping/pong and closing, and then proper reconnection.
How it works and why. HTTP is built as "request-response": the server sends nothing on its own. For chats, quotes and games this is inconvenient, so WebSocket (RFC 6455) turns one HTTP connection into a permanent two-way channel. The handshake is ordinary, and after it both sides can send messages at any moment without new requests and headers.
The life of a WebSocket connection
Figure 1. Authentication and the Origin check happen only at step 1: the protocol does not repeat them later.
The handshake is an ordinary HTTP/1.1 request with Upgrade. The server answers with 101: "switching to another protocol". The Sec-WebSocket-Accept value is computed from the client's key so that a random HTTP service cannot pose as a WebSocket server. The address starts with ws:// or wss:// (WebSocket over TLS; in production only wss).
Authentication happens right here, at the handshake. The browser WebSocket API does not allow custom headers (for example Authorization), so people use a cookie, a short-lived one-time ticket in the URL (an ordinary token in the query lands in logs and history) or a first message carrying the token. Origin is checked by the server: without it any foreign page opens a connection on behalf of the logged-in user (cross-site WebSocket hijacking).
Frames. A message consists of one or more frames: text (UTF-8), binary and control (ping, pong, close). Frames from the client are masked. Ping/pong checks that the connection is alive and keeps a proxy from closing it on idle timeout: usually the server sends ping and the browser answers pong automatically. Many applications add their own heartbeat messages, because ping/pong frames cannot be seen or sent from JS.
Closing is an exchange of close frames with a code that is worth being able to read:
Code
Meaning
1000
normal closure
1001
going away: the page was closed or the server is restarting
1008
policy violation (for example, no rights): retrying is pointless
1009
message too big
1011
internal server error
1006
abnormal closure: there was no close frame. It is never sent over the wire, the client sees it only locally
Client reconnection
Wrong
An instant retry in a loop
After a server crash thousands of clients reconnect at once and knock it down again. Missed events never come back.
Right
Backoff, jitter, resume
The delay grows and is randomly spread, there is an attempt limit, and after connecting the client asks for everything it missed by the last id.
Figure 2. A connection will break sooner or later, so reconnection and catching up are part of the design, not an addition for later.
Example: from lost messages to recovery. A client without recovery logic simply opens a new connection and listens on: everything that happened between the drop and the new connection is gone, and events in both directions are not repeated without acknowledgement. A working scheme has three parts: a delay with jitter (so thousands of clients do not knock at once), a different reaction to codes (do not retry 1008) and a request for what was missed by the id of the last message received:
let lastId = 0;
functionconnect(attempt = 0) {
const ws = newWebSocket('wss://example.com/ws');
ws.onopen = () => {
attempt = 0;
// ask for what was missed
ws.send(JSON.stringify({ type: 'resume', after: lastId }));
};
ws.onmessage = (e) => {
const msg = JSON.parse(e.data);
lastId = msg.id;
render(msg);
};
ws.onclose = (e) => {
// 1008 or 10 failed attempts in a row: stop retryingif (e.code === 1008 || attempt >= 10) return;
const cap = Math.min(30_000, 500 * 2 ** attempt);
// jitter: a random delay from 0 to capsetTimeout(() => connect(attempt + 1), Math.random() * cap);
};
}
Responsibility is shared here. The server must keep recent events or be able to give them by id; the client must remember where it stopped reading. Without the first, recovery is impossible; without the second, it duplicates messages. That is why messages have stable ids and handling is idempotent: a repeat of the same event does not put two messages on screen.
Limits and alternatives. WebSocket has no built-in redelivery, acknowledgement or ordering across connections. A balancer needs sticky connections or a shared subscription store, and proxies and firewalls sometimes cut WebSocket or close it on idle (see the lesson on proxies). If data flows only from the server, SSE is simpler (the next lesson). For WebSocket over HTTP/2 and HTTP/3 there are separate extensions (RFC 8441, RFC 9220), but most applications stay on the HTTP/1.1 handshake.
Common mistakes.
Assuming that messages during a drop "arrive on their own": without catching up they are lost.
Reconnecting instantly in a loop with no delay and jitter: after a server failure a connection storm forms.
Retrying after 1008 or an authentication error: pointless, and it loads the server.
Passing a long-lived token in the URL: it lands in proxy logs and history.
Not checking Origin on the server: it opens the way to cross-site hijacking.
Reading 1006 as "the server closed normally": it is exactly a drop with no close frame.
Check yourself
In a client onclose received code 1006. What does it mean and how does it differ from 1000 or 1001?
Answer
1006 means abnormal closure: there was no close frame, the connection dropped (network, a killed process, a proxy timeout). It is not sent over the wire, the client only sets it locally. 1000 and 1001 arrive in a close frame: normal closure and "going away" (the page is closing or the server is restarting). The reaction to 1006 is reconnecting with catching up.
Why can an Authorization token not be set from a browser WebSocket and what are the options?
Answer
The browser WebSocket API does not allow custom headers. Options: a cookie (Origin must be checked), a short-lived one-time ticket in the URL obtained through an ordinary HTTP request, or a token in the first message after connecting. A long-lived token in the query string is dangerous because it lands in logs.
Related lessons: “WebSocket, SSE or long polling: which to choose”, “How to test WebSocket: Playwright and load”, “Proxies, load balancers, CDNs and timeouts”.
In an interview.Junior: WebSocket opens a permanent two-way connection on top of an HTTP handshake with Upgrade and a 101 response. Both sides can send messages at any time, and the address starts with wss. Middle/Senior: Authentication and the Origin check happen at the handshake, because a browser does not allow headers. I keep the connection alive with ping/pong, tell close codes apart and treat 1006 as a drop. I reconnect with exponential delay and jitter, and then catch up on missed events by id: the protocol repeats nothing by itself.
WebSocket, SSE or long polling: which to choose
If data flows only from the server, SSE is enough, while intensive two-way interaction needs WebSocket. SSE is plain HTTP, and EventSource reconnects by itself and sends Last-Event-ID, so resuming from the point of the drop is almost free. With WebSocket the application handles reconnection, authorisation and catch-up. Polling stays for rare updates, and buffering proxies break SSE.
Networking · Real-time
An import progress bar must update live. WebSocket, SSE or just polling?
The product owner asks to show the progress of a long import live. A developer at once proposes WebSocket, because it is "for real time". But data flows only from the server to the client, and the client sends nothing. In that case WebSocket brings more complexity than benefit. The lesson compares four ways, shows how they differ and why the choice affects testing.
How it works and why. All four solve one thing: show the user a change on the server without a reload. They differ in who initiates the exchange and how much each event costs.
Four ways of real-time updates
Figure 1. The higher in the list, the simpler and more reliable; the lower, the more capabilities and responsibilities.
Short polling: the client asks every second. Simple, but wastes requests and adds a delay of up to the interval.
Long polling: a request hangs until an event appears (or a timeout passes), and after the response the client immediately makes a new one. Works wherever HTTP works, but every event costs a request with headers.
SSE (Server-Sent Events): one HTTP request with Content-Type: text/event-stream, the server streams events. Server to client only, text only. The browser EventSource reconnects itself and sends Last-Event-ID, so resuming from the break point is almost free.
WebSocket: two-way, text and binary, low latency, but its own protocol: reconnection, authorization, catching up and balancing of sticky connections are done by the application.
SSE versus WebSocket
SSE
Plain HTTP, server → client only, text only. The browser reconnects itself and sends Last-Event-ID. Passes proxies without special handling.
WebSocket
Its own protocol, two-way, text and binary, low latency. Reconnection, authorization and catching up are the application task.
Figure 2. The choice is set by the direction of data and by readiness to build infrastructure yourself.
The rule of choice. Data flows only from the server (notifications, progress, quotes, an LLM answer stream): SSE, and it is enough. Intensive two-way interaction (chat, shared editing, games, trading terminals): WebSocket. Rare updates and strict network limits: polling. Long polling remains a fallback when nothing else is available.
Example: import progress over SSE. This is what the stream looks like on the wire. The fields are id, event, data, and an empty line ends an event:
The implementation on the server and the client is minimal. Note X-Accel-Buffering: no: without it nginx may buffer the response, and all events appear in one chunk at the end, as if SSE "did not work":
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
// nginx must not buffer the response'X-Accel-Buffering': 'no',
});
res.write('id: 41\nevent: progress\ndata: {"percent":40}\n\n');
// clientconst es = newEventSource('/api/jobs/42/events');
es.addEventListener('progress', (e) => update(JSON.parse(e.data)));
If the connection drops, the browser opens it again and sends Last-Event-ID: 42, and the server continues from event 43. What you have to write yourself for WebSocket is already in the protocol here.
For testing the difference is significant. SSE is an ordinary HTTP response that can be intercepted and replaced as a response (route.fulfill with a text/event-stream body), and its body can be checked with curl -N. WebSocket needs separate APIs: see the lesson on testing WebSocket. When testing SSE, separately check behaviour on a drop, the presence of id and that the client does not duplicate an event on a retry.
Limits and alternatives.EventSource can only do GET and allows no custom headers, so for POST or Authorization people use fetch with body streaming (this is how streaming answers of LLM services work) and parse the format themselves. On HTTP/1.1 a limit of ~6 connections per domain applies, so several tabs with SSE can exhaust it; HTTP/2 multiplexes streams, so the problem does not exist. Proxies and CDNs that buffer the response break both SSE and long polling. Response compression can also accumulate events, so it is turned off for a stream.
Common mistakes.
Picking WebSocket "because it is real time" when data flows one way: extra reconnection, authorization, balancing.
Not switching off proxy buffering for SSE: events arrive in a batch, not one by one.
Not sending id in events: after a drop, catching up on what was missed is impossible.
Polling too often: each response is a full HTTP request with headers, and the load grows linearly with the number of clients.
Forgetting that a long connection with no traffic is closed by a proxy on idle: a periodic comment or heartbeat is needed.
Check yourself
A notification feed only reads events from the server. Which way do you choose and which two arguments do you give?
Answer
SSE. Data flows only from the server, and EventSource reconnects itself and sends Last-Event-ID, so catching up from the break point works out of the box. It is plain HTTP that passes proxies and balancers without special handling, and in tests it can be intercepted as a response. WebSocket would add complexity here with no need for a two-way channel.
SSE works on the stand, but behind nginx all events arrive together after a minute. What is the cause and how do you check?
Answer
The proxy buffers the response and releases it when the buffer fills or the connection closes. Buffering is switched off (proxy_buffering off for this location, or an X-Accel-Buffering: no header from the application) and checked with curl -N: events must appear one by one right after being sent.
Related lessons: “WebSocket: handshake, frames, ping/pong and closing”, “How to test WebSocket: Playwright and load”, “Proxies, load balancers, CDNs and timeouts”.
In an interview.Junior: Polling periodically asks the server, long polling holds a request until an event, SSE streams events from the server, WebSocket gives a two-way channel. For a server-only stream SSE is enough. Middle/Senior: I choose by data direction and infrastructure cost. SSE is plain HTTP with built-in reconnection and Last-Event-ID, WebSocket gives two-way but reconnection and catching up are on the application. For SSE I watch proxy buffering and the connection limit on HTTP/1.1, and in tests I intercept it like an ordinary response.
How to test WebSocket: Playwright and load
WebSocket is tested in Playwright through the websocket event and page.routeWebSocket, while load is measured with k6 or Artillery, not with browsers. The subscription must be made before navigation, and the test waits for an event with a predicate, not for time. A failure is emulated by closing with a code on the server's behalf, then reconnection and catch-up are checked. Load tests measure delivery latency and the reconnect storm.
Networking · Real-time
A chat works in the UI, but how do you check the messages themselves, a drop and 1000 simultaneous clients?
A test presses "Send" and the message appears in the list. That is not enough: it is unknown what actually went through the channel, what happens if the server closes the connection and whether the service survives a thousand connected clients. WebSocket does not fit an ordinary page.route, because it is not a request-response pair. The lesson shows four levels of verification and, for each, which tool serves and what it cannot do.
What to check. The handshake and authentication (rejection without a token), message format and order, idempotency on repeated delivery, UI behaviour on a drop and reconnection, size limit, channel permissions, closing with the right code. The protocol is covered in the lesson on handshake, frames and closing.
Four levels of WebSocket verification
Figure 1. The levels complement each other: observation shows real behaviour, replacement gives control, load checks scale.
Observation. Playwright emits a websocket event for every connection of the page. It has framesent, framereceived, close and socketerror, and the payload field is a string or a Buffer. The main rule: wait for an event, not for time.
Wait for an event or for a timer
Wrong
waitForTimeout(2000)
The test waits a fixed time hoping the message has arrived. It fails on slow CI and pointlessly slows down on fast machines.
Right
waitForEvent and web assertions
The test waits for the event or UI state itself and moves on as soon as it happens. It does not depend on machine speed.
Figure 2. A fixed pause is unstable by definition: delivery time depends on the network, the machine and the load.
// subscribe before navigation, or the connection is missedconst wsPromise = page.waitForEvent('websocket');
await page.goto('/chat');
const ws = await wsPromise;
const reply = ws.waitForEvent('framereceived', {
predicate: (e) => String(e.payload).includes('"type":"message"'),
});
await page.getByRole('textbox').fill('hello');
await page.keyboard.press('Enter');
expect(JSON.parse(String((await reply).payload)).text).toBe('hello');
The websocket event must be subscribed before navigation: the connection opens while the page loads, and whoever subscribes later misses it. The predicate in waitForEvent filters out service frames (heartbeats) so the test does not stop at someone else's message.
Replacement.page.routeWebSocket(url, handler) (since Playwright 1.48) intercepts the connection. Without connectToServer() there is no real server: the test answers itself and no backend is needed. With connectToServer() a proxy is created, in which messages can be peeked at or changed:
await page.routeWebSocket('wss://example.com/ws', (ws) => {
ws.onMessage((message) => {
if (message === 'ping') ws.send('pong');
});
// an event from the "server"
ws.send(JSON.stringify({ type: 'welcome' }));
});
// proxy mode: a real server plus a peekawait page.routeWebSocket(/\/ws$/, (ws) => {
const server = ws.connectToServer();
ws.onMessage((m) => server.send(m));
server.onMessage((m) => ws.send(m));
});
Simulating a failure. A drop is emulated by closing on behalf of the "server" with the required code and checking that the client reconnected and restored its state. Here a connection counter in the closure tells "the client retried" from "the client hung":
let connections = 0;
await page.routeWebSocket('wss://example.com/ws', (ws) => {
connections++;
// the "server" closes the first connection with an errorif (connections === 1) ws.close({ code: 1011, reason: 'boom' });
});
await page.goto('/chat');
// the client must connect a second timeawait expect.poll(() => connections).toBe(2);
awaitexpect(page.getByTestId('chat-status')).toHaveText('online');
The test does not call waitForTimeout: expect.poll and web assertions repeat the check until the condition holds. A "messages are not lost" test additionally checks that after reconnecting the client asked for the missed ones by the last id, rather than just opening a new stream.
Load. Playwright is not suitable for this: every browser is heavy, and the goal is thousands of light clients. Use k6 (the k6/websockets module) or Artillery (the ws engine): virtual users following the scenario "connect, subscribe, listen for N seconds".
Measure the number of simultaneous connections, delivery latency (time from the server event to receipt), the share of connection errors, behaviour on a server restart (a reconnection storm) and memory leaks on a long run. The single number "5000 clients connected" without delivery latency proves nothing.
Limits and alternatives. Replacement via routeWebSocket covers up the real integration: a mock does not know that the message schema changed on the server. So a few end-to-end tests stay without replacement, and the message contract is checked separately. Cloud real-time services and brokers have their own SDKs and tools. For the protocol level (does the server close with a code, does it limit frame size) no browser is needed: a client such as ws in Node is enough, which can send arbitrary frames and headers, something the browser API cannot.
Common mistakes.
Subscribing to the websocket event after goto: the connection is already open and the test waits until the timeout.
Asserting the first message received: the channel has heartbeats and other events, a predicate is needed.
Putting waitForTimeout instead of an event: the test is both slow and unstable.
Measuring load with a Playwright test: the resources go to browsers, not to the server.
Keeping only the mock: nobody checks the contract with the real server.
Check yourself
A test waiting for framereceived sometimes fails with a timeout although the message appears in the UI. What error do you look for in the code?
Answer
Most likely the websocket subscription happens after goto: the connection is already open and the test did not see it. The subscription (waitForEvent) is created before navigation. A second candidate: ws.waitForEvent('framereceived') is created after the action, and the reply arrived before the subscription. A third: the predicate catches the wrong message, for example a heartbeat.
How do you check that a client reconnects after the server closes the connection with code 1011, without a real backend?
Answer
Through page.routeWebSocket without connectToServer: on the first handler call the "server" does ws.close({ code: 1011 }), and the connection counter in the closure must reach 2 (expect.poll), after which the UI status is checked. No waitForTimeout at all.
Related lessons: “WebSocket: handshake, frames, ping/pong and closing”, “WebSocket, SSE or long polling: which to choose”, “DevTools Network, HAR, throttling and offline”.
In an interview.Junior: In Playwright I take the page websocket event and listen to framesent and framereceived to see the messages. For load I use k6 or Artillery. Middle/Senior: I subscribe before navigation and wait for an event with a predicate, not a timer. I replace the server with routeWebSocket, in proxy mode I peek at real traffic, I emulate failures with ws.close and a code, and I check reconnection and catching up. I measure load by delivery latency and the reconnection storm, not just the number of connections.