skip to content

WebSockets

11 roadmaps45 questionsupdated

One TCP connection that either end may write to at any moment, obtained by upgrading an ordinary HTTP request and then held open. Interviewers reach for it whenever a brief says the word live.

on this pageshow

guide

overview

~1 min

A WebSocket is one long-lived TCP connection, opened by upgrading an HTTP request, over which either side may send a message whenever it likes. Interviewers bring it up whenever a design brief says live or push, to find out whether you know what the protocol leaves to you. A strong answer treats the socket as a thin pipe: it carries messages, while delivery confirmation, matching replies to requests, backpressure, reconnection and authorization after the open are the application's job. The hub splits the way a connection lives. The [HTTP upgrade handshake](/topics/proto-websockets-handshake) and the [extended CONNECT bootstrap](/topics/proto-websockets-http2-http3) are how a socket opens over HTTP/1.1 and over HTTP/2 or HTTP/3. [Frame format and masking](/topics/proto-websockets-framing) is the wire format; [bidirectional messaging](/topics/proto-websockets-messaging) is what the application sees on top of it, and [subprotocols and extensions](/topics/proto-websockets-subprotocols) is how both ends agree on what messages mean. [Ping/pong and close](/topics/proto-websockets-keepalive) covers liveness and shutdown. [Connection authentication](/topics/proto-websockets-auth) and [origin, TLS and proxies](/topics/proto-websockets-scaling) hold the security and deployment questions, and [short and long polling](/topics/proto-websockets-vs-polling) is the baseline a socket is measured against. Junior rounds ask for the handshake, the frame types and the difference from polling. Senior and principal rounds move to production: a proxy that swallows the upgrade, a token in the logs, a consumer that cannot keep up, a fleet where an open connection is the wrong call. Learn the handshake and framing first, then messaging and close; authentication and proxies make sense once the life of a connection is clear.

primer

### It starts as HTTP, then stops being HTTP The opening exchange is an ordinary HTTP request asking to switch protocols. Once the server agrees, the same TCP connection carries WebSocket frames and HTTP has no further say. That reuse is why sockets pass through existing ports and load balancers, and why every HTTP-era concern — cookies, `Origin`, proxies, access logs — applies to that single request and to nothing that follows it. ### Messages, not calls Either end may send at any time, and nothing pairs a message with a reply. The protocol gives you text and binary messages and stops there: no identifiers, no acknowledgements, nothing that confirms arrival. Anything shaped like a call — did the command land, which reply belongs to it — is a convention the two ends invent, which is why interviewers push toward a published subprotocol over a home-grown envelope. ### Frames are the unit on the wire A message travels as one or more frames, each with its own small header. Fragmentation lets a sender stream a message whose size it does not yet know, and lets control frames (ping, pong, close) slip in between pieces. Frames from client to server are masked, a defence aimed at intermediaries rather than eavesdroppers; confidentiality comes from TLS alone. ### Nothing tells the sender to slow down The protocol has no window or credit of its own. When a receiver falls behind, TCP pushes back and the pressure shows up as data piling up inside the sending process. Bounded queues, dropping or coalescing stale updates and caps on inbound message size are designs you choose, not settings you switch on. ### A quiet socket proves nothing A connection whose peer has vanished looks exactly like a healthy idle one until a write fails. Liveness needs a periodic probe with a deadline; a clean ending needs both sides to exchange close frames. ### Authorization happens once, at the door The browser API gives a page no way to add headers to the upgrade, so credentials ride in a cookie, the URL, a pre-minted ticket or the subprotocol list — each with its own leak or forgery risk. Whatever you pick is checked when the socket opens, and a socket that lives for hours outlives that check unless you design for it.

101 Switching Protocols
The HTTP/1.1 status a server returns to accept the upgrade; from the end of that response onward, the connection carries WebSocket frames.
Sec-WebSocket-Accept
The server's handshake field derived from the client's random key. It shows the responder understood the WebSocket handshake; it authenticates nobody.
Frame
The unit on the wire: a short header with FIN bit, opcode, mask flag and payload length, followed by the payload.
Masking
XOR-ing each client-to-server payload with a random per-frame key, so crafted bytes cannot pass for other protocols in proxy caches. Not encryption.
Control frame
A ping, pong or close frame: small, never fragmented, and allowed to arrive between the fragments of a data message.
Close status code
A numeric reason carried in a close frame, such as normal closure or message too big. Some codes exist only for local APIs.
Half-open connection
A connection one side still believes is open after the other side or a middlebox has discarded it; only a write or probe exposes it.
Subprotocol
An application protocol negotiated in the handshake, such as STOMP or MQTT, that defines what messages mean on this socket.
permessage-deflate
The standard extension that compresses message payloads, negotiated with parameters that trade compression ratio against per-connection memory.
wss
The WebSocket scheme run over TLS, on port 443 by default. Protection ends wherever TLS is terminated.
Origin header
The request field a browser sets to the page's origin on the upgrade. Servers check it to block cross-site sockets; non-browser clients can forge it.
Extended CONNECT
The HTTP/2 and HTTP/3 method for opening a WebSocket on one stream, enabled by a server setting, with a success status instead of 101.

Trace one connection from open to close. The client sends an HTTP request asking to upgrade, offering subprotocols and extensions and carrying whatever credential it can: usually a cookie, or a ticket in the URL. Every proxy on the path has to pass that upgrade through, and the server checks `Origin`, the credential and its own connection limits before agreeing. Over HTTP/2 or HTTP/3 the same negotiation rides an extended CONNECT on one stream of a connection that already exists, and a success status stands in for the 101. Once open, the layers stack like this: - **TCP, or one stream of an HTTP/2 or HTTP/3 connection,** carries the bytes and supplies the only backpressure. - **TLS**, for `wss`, encrypts up to the point where it is terminated. - **Frames** carry payload, fragmentation and the control traffic: ping, pong and close. - **Extensions** such as permessage-deflate transform payloads, as agreed at open. - **The subprotocol** gives messages meaning: commands, subscriptions, acknowledgements, errors. - **The application** owns the rest: correlating replies, reconnecting, catching up on missed events, re-checking authorization. In a browser, the page holds only the thin end of all this — a URL, the names it offers and a few events: ```javascript // an ordinary authenticated request mints a short-lived, single-use ticket const { ticket } = await (await fetch("/ws-ticket", { method: "POST" })).json(); // the upgrade takes only a URL and subprotocol names: no header slot const ws = new WebSocket(`wss://example.com/live?ticket=${ticket}`, ["v12.stomp"]); ws.onopen = () => console.log(ws.protocol); // the one name the server echoed ws.onclose = (e) => console.log(e.code); // 1006 when no close frame arrived function send(frame) { if (ws.bufferedAmount > 1_000_000) return; // the page's only backpressure signal ws.send(frame); } ``` Three sections meet in those lines: the credential cannot travel as a header, the server picks at most one subprotocol, and the page learns the receiver is slow only by watching its own send buffer grow.

  1. HTTP Upgrade Handshake →

    Where every connection begins: how an HTTP request becomes a socket, and why HTTP has no say once it succeeds.

  2. Frame Format and Masking →

    The wire format every later section assumes: frame header, message fragmentation and why client frames are masked.

  3. Bidirectional Messaging →

    What the application actually gets: text and binary messages, reassembly, and no built-in flow control or reply matching.

  4. Ping/Pong and Close →

    How to tell a live socket from a dead one and how to end a connection cleanly.

  5. Connection Authentication →

    Credentials on a socket, where tokens leak, and what to do when authorization expires mid-connection.

  6. Origin, TLS, and Proxies →

    Origin checks, TLS and reverse proxies: the reasons a socket that works locally fails once deployed.

  • Calling masking a security feature for the data: the key travels in the frame, anyone on the path can undo it, and only wss keeps payloads private.

  • Assuming a sent message was received and processed: the protocol confirms nothing, so command traffic needs acknowledgements and a correlation id defined by the application or its subprotocol.

  • Treating an allowlisted Origin as authentication: it stops other sites' pages in a victim's browser, while any scripted client sends whatever value it likes.

  • Putting a long-lived access token in the wss: query string, where it lands in logs and history — see Token in the Query String.

  • Reading a quiet connection as a healthy one: without pings on a timer and a pong deadline, a half-open socket stays connected until a write finally fails.

  • Debugging the application when clients get 200 instead of 101 behind a new reverse proxy; the proxy usually dropped the hop-by-hop upgrade fields.

  • Reaching for a socket whenever a brief says real time: for rare updates, one-way push or devices that sleep, polling can be cheaper and simpler.

This guide assumes the protocol as RFC 6455 defined it in 2011, version 13 — the value clients send in `Sec-WebSocket-Version` today. The framing and the HTTP/1.1 handshake have not changed since; what changed is around them, and interviewers ask about each piece: - **RFC 7692** (2015) standardised permessage-deflate and its context-takeover and window parameters. - **RFC 8441** (2018) defined how to open a socket over HTTP/2 with extended CONNECT, gated by a server setting. - **RFC 9220** (2022) carried the same bootstrap to HTTP/3. Pre-standard drafts used a different handshake and sent unmasked frames; they matter now only as the reason masking and the accept digest exist. When a question concerns opening a socket, say which HTTP version you mean: the key and accept exchange and the 101 status belong to HTTP/1.1 alone, and an answer that assumes them on HTTP/2 is wrong.

Interviewers expect you to place WebSockets among the other ways to get data to a client without being asked. **Short and long polling** use plain HTTP and fit rare or bursty updates, especially where clients sleep or connections are metered. **Server-sent events** stream from server to client over an ordinary HTTP response, with reconnection built into the browser API; they fit one-way feeds, and a socket earns its place when the client also sends often. **WebTransport**, built on HTTP/3, offers multiple streams and unreliable datagrams, and is the newer option where head-of-line blocking matters. gRPC streaming serves service-to-service streams more often than browsers. On top of the socket sit the protocols that give messages meaning: STOMP, usually in front of a message broker; MQTT for devices; and graphql-ws for GraphQL subscriptions. Libraries such as Socket.IO add their own protocol with rooms, acknowledgements and fallbacks, so their clients do not talk to a plain WebSocket server. Fanning messages out across a fleet of socket servers is a system-design question; this hub stops at one server's sockets.

report an issue with this guide →

questions

page 1 of 2

In the WebSocket protocol, why can a browser page not set an HTTP Authorization request header on the upgrade?

level: juniorimportance: must knowfreq 62%

answer

  1. the page never builds the request
  2. URL and subprotocol list only
  3. ordinary GET, then the 101
  4. cookies ride automatically, tokens do not
  5. a non-browser client has no such limit

basics

~20 s

The upgrade is an ordinary HTTP GET issued by the browser itself, and the page's socket API accepts only a URL and a list of subprotocol names. There is no place to add a request field, so no Authorization.

solid answer

~40 s

A WebSocket connection starts as an HTTP/1.1 `GET` carrying `Upgrade: websocket`, `Connection: Upgrade`, `Sec-WebSocket-Key` and `Sec-WebSocket-Version: 13`, answered by `101 Switching Protocols`. Nothing in RFC 6455 forbids an `Authorization` field on that request — the restriction is in the browser: the client API a page gets accepts a URL and an optional subprotocol list and nothing else, so the page never builds the request and cannot add fields to it. What still travels automatically is a cookie scoped to the target origin. That leaves four practical routes for a credential: the cookie, a token in the URL query string, a token smuggled as a second subprotocol value, or a short-lived ticket redeemed on the upgrade. A non-browser client writes the request itself and is under none of this.

code

http · 13 lines
http
GET /cabinet/socket HTTP/1.1
Host: console.example.org
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: https://console.example.org
Cookie: cabinet_session=8f2c1d...

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

go deeper

for a junior

Recall that a WebSocket starts life as an HTTP GET with Upgrade and Connection fields, and that a page can only influence the URL and the subprotocol list. That is enough to explain why the header is missing.

for a middle

Explain that the restriction is a client API limitation rather than a protocol rule, and walk the four routes a credential can take instead, naming what each costs on the wire.

for a senior

Demonstrate that the answer depends on the client kind, and that the check happens once at the handshake — so the identity a connection carries all shift is whatever the upgrade established.

for a principal

Frame it as a fleet decision: whether one endpoint serves both page and service clients with two credential routes, or two endpoints each accept one, and what that costs in review surface.

## The upgrade is an ordinary HTTP request A WebSocket connection does not begin as a socket. It begins as an HTTP/1.1 `GET` that asks the server to change protocols. That request carries `Upgrade: websocket`, `Connection: Upgrade`, a client-generated `Sec-WebSocket-Key` and `Sec-WebSocket-Version: 13`; the server answers `101 Switching Protocols` with a `Sec-WebSocket-Accept` digest, and from that moment the same TCP connection carries frames instead of HTTP messages. Because it is an ordinary HTTP request, it can carry ordinary HTTP request fields. **RFC 6455 places no restriction on an `Authorization` field on the upgrade.** The limitation that every team runs into is on the client side, and it applies to exactly one kind of client. ## What a page's client API actually accepts The socket API a browser gives a page takes two things: - the **URL** — scheme, authority, path and query string, all under your control; - an optional **list of subprotocol names**, which the browser puts in `Sec-WebSocket-Protocol`. That is the entire input surface. The page does not construct the request, so it cannot add, remove or edit a single field on it. Cookies are attached by the browser according to the cookie's own attributes, not by your code. So the practical question is never "which header do I use" — it is "which of the two inputs I control can carry a credential, and what does that cost." ## The routes a credential can actually take | Route | Who can use it | What it costs | |---|---|---| | Session **cookie** | a browser page | sent automatically, including on an upgrade started by a page you do not control, so cross-site protection becomes load-bearing; the cookie's own attributes decide whether it travels at all | | **Token in the query string** | any client | lands in the server's access log, every intermediary's access log, browser history, and any copy of that URL — the most common credential leak on this protocol | | **Token as a second `Sec-WebSocket-Protocol` value** | any client | abuses a negotiation field; the server must select exactly one value to echo and it must not be the token | | **Short-lived single-use ticket** in the query string | any client | one extra authenticated request before the upgrade; the shape that survives review | | **Credential in the first frame** after the socket opens | any client | the server has already accepted an unauthenticated connection and must time it out if no credential arrives | None of these is free, and a candidate who names the trade-off rather than a favourite is the one answering the question. ## A non-browser client is under no such limitation A server-to-server client, a command-line client or a native application writes the upgrade request itself. It sets `Authorization` exactly as it would on any other HTTP request, and the whole problem disappears. This is why the honest answer to "how do you authenticate a WebSocket" begins with a question back: **which client?** A console running in a browser and a background service opening the same endpoint have different answers, and an interviewer listening for that distinction hears it immediately. It also means a server that accepts only `Authorization` is not wrong — it is simply unusable from a page, which may be exactly the intent for an internal endpoint. ## What the check is worth Whatever route you choose, the authentication happens **once**, on the request that opens the connection. If it succeeds the server completes the handshake; if it fails the server refuses the upgrade with an ordinary HTTP error response instead of the `101`, and no socket ever exists. There is no second credential exchange defined by the protocol, and no per-frame credential: once the connection is up, everything the server knows about who is on the other end is whatever it recorded at the handshake and attached to the connection. On a console that dispenses controlled substances, that single check is the entire identity story for a connection that may stay open all shift — which is why the same leaf goes on to ask what happens when the credential behind it expires. ## What an interviewer is listening for 1. That the upgrade **is** HTTP, so HTTP mechanisms are in play at all. 2. That the missing header is a **client API** limitation, not a protocol rule. 3. That the answer **differs by client kind**. 4. That the cookie is not a neutral default — it is a choice with a cross-site consequence.

  • If the protocol allows an Authorization field on the upgrade, when is it actually the right choice?
    Whenever the client is not a browser page. A service, a native application or a command-line client builds the upgrade request itself and can set any request field on it, so it authenticates the handshake exactly as it would any other HTTP request — no ticket endpoint, no token in the URL, no cookie. Restricting an endpoint to that route is a reasonable way to say "not callable from a page".
  • What does the server know about the caller once the socket is open?
    Only what it recorded during the handshake and bound to the connection. The protocol defines no second credential exchange and no per-frame identity, so every frame that arrives is attributed to the principal established at open. Anything finer — per-message authorization, a principal that can change — is the application's own invention layered on top.
  • Can the page authenticate after the socket opens instead?
    Yes, by sending the credential in the first application frame, and some designs do. The cost is that the server has already accepted a connection from an unauthenticated peer: it must hold that socket in an unauthenticated state, refuse every other message until a valid credential arrives, and close it on a short timer if one never does.

saying these in an interview costs you the question

  • Says RFC 6455 forbids an Authorization field on the upgrade request
  • Thinks the WebSocket upgrade is not an HTTP request at all
  • Believes every client is limited the way a browser page is
  • Assumes wss encryption removes the need to authenticate the handshake
  • Treats an in-band first-message credential as costing nothing
open as a page

In a WebSocket data frame, what do the FIN bit and the 4-bit opcode in the first byte tell the receiver?

level: juniorimportance: must knowfreq 70%

basics

~20 s

FIN says whether this frame is the last of its message; the 4-bit opcode says what the frame is: %x0 continuation, %x1 text, %x2 binary, %x8 close, %x9 ping, %xA pong. Three RSV bits sit between them.

open as a page

What does a WebSocket client send in its HTTP/1.1 upgrade request, and which response means the socket is open?

level: juniorimportance: must knowfreq 84%

basics

~20 s

A WebSocket client opens with an ordinary HTTP/1.1 GET carrying Host, Upgrade: websocket, Connection: Upgrade, a random Sec-WebSocket-Key and Sec-WebSocket-Version: 13. A 101 Switching Protocols response with a matching Sec-WebSocket-Accept means the socket is open.

open as a page

In the WebSocket protocol, what must an endpoint do when it receives a Ping control frame, and what does that exchange prove?

level: juniorimportance: must knowfreq 68%

basics

~20 s

A WebSocket endpoint that receives a Ping frame (opcode %x9) must answer with a Pong frame (opcode %xA) carrying identical application data. A completed round trip proves the peer's process read a frame and wrote one back.

open as a page

In a WebSocket connection, what does the protocol guarantee about a text message that it does not guarantee about a binary one?

level: juniorimportance: must knowfreq 62%

basics

~20 s

A WebSocket text message must carry valid UTF-8, and an endpoint receiving invalid UTF-8 in one fails the connection with close status 1007. A binary message is an opaque sequence of octets the protocol never inspects.

open as a page

In a WebSocket opening handshake, what does the client's `Sec-WebSocket-Protocol` field offer, and how must the server answer?

level: juniorimportance: must knowfreq 62%

basics

~20 s

Sec-WebSocket-Protocol carries an ordered list of application protocol names the client can speak. The server selects at most one and echoes exactly that name in its 101 response; returning two names, or one never offered, fails the connection.

open as a page

How do short polling and long polling differ in what the HTTP server does with each request for updates?

level: juniorimportance: must knowfreq 84%

basics

~20 s

Short polling answers every request immediately, empty or not, so the client re-asks on a fixed timer. Long polling holds each request open until an update exists or the server's hold period expires, then answers once.

open as a page

Why must a WebSocket client mask every frame it sends, when the masking key travels in that same frame?

level: middleimportance: must knowfreq 62%

basics

~20 s

Masking defeats intermediary cache poisoning, not eavesdropping. A fresh random 32-bit key per frame stops an attacker-controlled page from making a client emit bytes a proxy would read as a second HTTP request and cache. It is trivially reversible and is no substitute for TLS.

open as a page

In a WebSocket opening handshake, how does the server compute Sec-WebSocket-Accept, and what does that value prove?

level: middleimportance: must knowfreq 66%

basics

~10 s

The server appends the fixed GUID 258EAFA5-E914-47DA-95CA-C5AB0DC85B11 to the client's Sec-WebSocket-Key text, SHA-1 hashes the result and base64-encodes the digest. It proves the peer implements the WebSocket handshake - not authentication, privacy or integrity.

open as a page

Before a WebSocket can open over HTTP/2, what must the server have sent, and what request replaces the GET with `Upgrade: websocket`?

level: middleimportance: must knowfreq 58%

basics

~10 s

An HTTP/2 server must first advertise SETTINGS_ENABLE_CONNECT_PROTOCOL with the value 1; only then may a client send an extended CONNECT request carrying the :protocol pseudo-header set to websocket, alongside :scheme, :path and :authority.

open as a page

In a WebSocket connection, what happens on the wire between one endpoint deciding to close and the TCP connection actually ending?

level: middleimportance: must knowfreq 60%

basics

~20 s

The closing endpoint sends a Close frame and stops sending data; the peer sends a Close frame back. Only once both directions have exchanged one does the transport go: the server closes the TCP connection and the client waits for that close.

open as a page

Why can a page on an attacker's domain open a WebSocket to your server with the victim's cookies attached, and what stops it?

level: middleimportance: must knowfreq 70%

basics

~20 s

Nothing in the browser blocks a cross-site WebSocket upgrade, and cookies for your host may ride along, so the socket is authenticated but unintended. The server must check the Origin request field against an allowlist and refuse the handshake.

open as a page

Why adopt a published WebSocket subprotocol such as STOMP or MQTT instead of inventing your own JSON message envelope?

level: middleimportance: must knowfreq 48%

basics

~20 s

A published subprotocol hands you a specified message grammar with acknowledgement and error semantics somebody else designed, documented and implemented twice. An ad-hoc envelope means you own all of that, usually without writing it down.

open as a page

When a WebSocket client puts its access token in the wss: URL query string, where does that token land and what replaces the practice?

level: seniorimportance: must knowfreq 60%

basics

~20 s

It lands in the server's access log, in every intermediary's access log, in browser history, and in every copy of that URL. Replace it with a short-lived single-use ticket minted on an ordinary authenticated request and redeemed on the upgrade.

open as a page

A yard system pushes position updates over a WebSocket faster than the cabin console consumes them - what in the protocol tells the sender to slow down?

level: seniorimportance: must knowfreq 58%

basics

~20 s

Nothing at the WebSocket layer. The protocol defines no credit, window or acknowledgement a receiver can use to say stop. The only backpressure is TCP's underneath, and it reaches the sending application as a growing outbound queue rather than an error.

open as a page

A reverse proxy now sits in front of your WebSocket service and clients get 200 OK with an HTML body instead of 101. What happened?

level: seniorimportance: must knowfreq 64%

basics

~20 s

The proxy did not forward the Upgrade and Connection fields. They are connection-scoped, meaningful only on the hop that carries them, so the origin saw a plain GET for that path and answered it normally with the page it serves there.

open as a page

An irrigation controller's long-poll feed drops some events and repeats others under load; what happens between each response and the next request?

level: seniorimportance: must knowfreq 55%

basics

~20 s

Nothing of that client is open in the gap. Unless the server keeps each client's position and the events published since it, anything emitted between a response and the next request is lost — and re-asking by timestamp repeats events instead.

open as a page

In the WebSocket protocol, what does a wss: URL give you that a ws: URL does not, and where does that protection stop?

level: juniorimportance: should knowfreq 61%

basics

~20 s

Both schemes run the same WebSocket protocol; wss: runs it over TLS, on port 443 by default rather than 80. The protection stops wherever TLS is terminated, so any hop beyond that point carries frames in whatever the operator configured.

open as a page

On a WebSocket that multiplexes many channels, why must the server authorize each subscribe message when the upgrade was already authenticated?

level: middleimportance: should knowfreq 44%

basics

~20 s

Authenticating the upgrade establishes who is connected, not what they may read. Each subscribe or publish names a channel, so the server must check that principal against that channel when the message arrives, and end subscriptions whose access is withdrawn.

open as a page

How does a WebSocket sender split one message across several frames, and what does each frame carry?

level: middleimportance: should knowfreq 42%

basics

~20 s

The first frame carries the real opcode with FIN clear; every later frame carries opcode %x0 with FIN clear; the last carries opcode %x0 with FIN set. Each frame declares its own length, so the sender never needs the total in advance.

open as a page

In a WebSocket frame, how is payload length encoded when the 7-bit length field holds 126 or 127?

level: middleimportance: should knowfreq 45%

basics

~20 s

Values 0-125 are the length itself. 126 means the next 2 bytes hold a 16-bit unsigned length; 127 means the next 8 bytes hold a 64-bit unsigned length. Both are network byte order, so a small frame costs 2 header bytes and a huge one costs 10.

open as a page

A WebSocket bootstrapped over HTTP/2 sends no `Sec-WebSocket-Key` and gets no `101`, so which handshake fields survive and what signals success?

level: middleimportance: should knowfreq 46%

basics

~10 s

Origin, Sec-WebSocket-Version, Sec-WebSocket-Protocol and Sec-WebSocket-Extensions survive, lowercased as HTTP/2 requires. The Key/Accept digest is gone because the :protocol pseudo-header does its job, and success is a 2xx status - in practice 200.

open as a page

In the WebSocket protocol, which close status codes must never appear in a Close frame on the wire, and why do they exist?

level: middleimportance: should knowfreq 50%

basics

~20 s

Codes 1005, 1006 and 1015 are reserved and must never be sent in a Close frame. They exist only so a local client API can report a Close frame with no status, a connection that ended with no Close frame at all, or a failed TLS handshake.

open as a page

While a WebSocket receiver is reassembling a fragmented message, a control frame arrives between two of its fragments - what must the receiver do?

level: middleimportance: should knowfreq 42%

basics

~20 s

Handle it immediately and separately. A WebSocket control frame may be injected between the fragments of a message; it never joins the reassembly buffer and never ends the message being reassembled, which resumes with the next fragment.

open as a page

A crane console sends a command over a WebSocket and needs to know which reply answers it - what does the protocol give it?

level: middleimportance: should knowfreq 52%

basics

~10 s

Nothing. A WebSocket carries whole messages, not calls: there is no request identifier, no reply field and no delivery report. Request-and-response over a socket is an application convention both ends must invent and agree.

open as a page

Your server refuses any WebSocket upgrade whose Origin field is not allowlisted, yet a scripted non-browser client connects freely. Why?

level: middleimportance: should knowfreq 46%

basics

~20 s

Only a browser is obliged to fill in the Origin request field honestly. Any other client writes whatever string it likes, so the check is a defence against pages the victim's browser loads, not authentication of the caller.

open as a page

In a WebSocket handshake, how is `permessage-deflate` negotiated, and what marks a message on the wire as compressed?

level: middleimportance: should knowfreq 40%

basics

~20 s

The client offers permessage-deflate in Sec-WebSocket-Extensions on the opening request; the server returns the one offer it accepts, with agreed parameters. Afterwards the RSV1 bit on a message's first frame marks that message's payload as compressed.

open as a page

Why does a long-poll server answer empty-handed when its own hold period expires instead of waiting indefinitely?

level: middleimportance: should knowfreq 48%

basics

~20 s

Because a request nobody has answered is indistinguishable from a broken path. A bounded hold lets the server return an empty result, release the request and prove the cycle still works; the client re-issues at once.

open as a page

In short polling, how does the client's fixed interval trade worst-case staleness against the cost of empty polls?

level: middleimportance: should knowfreq 62%

basics

~20 s

The interval is the staleness budget: an update can wait almost a full interval plus a round trip. Halving it halves that wait and doubles request volume, and on a rarely-changing feed nearly every extra request returns nothing.

open as a page

showing 1–30 of 45

WebSockets interview questions & primer · KataJob