{"canonical_url":"https://engineer.company/glossary/websocket/","content_markdown":"# WebSocket\n\n## What it is\n\nWebSocket is a protocol for a connection both sides can write to at any\nmoment. An HTTP handshake establishes it, and it stays open until a peer\ncloses it or the connection fails. The IETF published it as RFC 6455 in\nDecember 2011, and the part a browser exposes to scripts, the\n`WebSocket` object, is defined by the WHATWG WebSockets\nStandard. Plenty of code and documentation spells it “websocket” or “web\nsocket”, and the plural WebSockets usually means the technology as a whole.\n\nIn the classic HTTP/1.1 handshake, the connection starts with an ordinary\n`GET`. The client adds `Upgrade:\nwebsocket` and\n`Connection: Upgrade`, a `Sec-WebSocket-Version` of 13 and a\n`Sec-WebSocket-Key`, which is a random 16-byte value encoded in\nbase64. A server that agrees answers with status 101 Switching Protocols and a\n`Sec-WebSocket-Accept` header. That value proves the server read this\nvery handshake rather than replaying an old answer: it is the client's key\nwith a fixed GUID appended, hashed with SHA-1 and encoded in base64. From that\nmoment HTTP is finished on that connection, and both sides exchange frames\ninstead. HTTP/2 and HTTP/3 instead carry WebSocket over one stream using\nextended CONNECT, as RFC 8441 and RFC 9220 specify.\n\nA frame is small. Its header starts at two bytes, grows by two or eight more\nwhen the payload is longer than 125 bytes, and by another four on frames from\nthe client, which carry a masking key. Each frame carries an opcode: text,\nbinary, or continuation for a message split across several frames, plus three\ncontrol frames for close, ping and pong. A complete text message must be valid\nUTF-8; an individual fragment can split a UTF-8 sequence. Every frame a client\nsends is masked with a fresh random 32-bit key, and a server never masks.\nMasking is not encryption. It exists so that a hostile script cannot choose\nthe exact bytes that cross the network and use them to poison a caching proxy\nsomewhere along the path.\n\nAddresses use the `ws://` and `wss://` schemes, with port 80 and port 443 as the\ndefaults, and `wss` runs the whole exchange inside TLS. Those are the ports HTTP\nalready uses, on purpose: the handshake looks like any other web request to the\nfirewalls and proxies it passes through.\n\n## Why it matters\n\nWith short HTTP responses, the server speaks only when spoken to. Plenty of\nproducts need the opposite: a chat message, a price that just moved, a cursor\nin a shared document, a background job that has finished. Without a channel\nthe server can write to, the client has to poll. It asks every few seconds,\nmost answers only say that nothing has changed, each one carries a full set of\nheaders, and news waits up to one interval before anyone sees it. An open\nWebSocket connection removes both costs. The server can send when something\nhappens, without waiting for the next poll. Each message needs only a few\nbytes of framing instead of a full set of HTTP headers.\n\nThe price is state. An HTTP request can land on any server behind a load\nbalancer, while a WebSocket connection belongs to one process for as long as it\nlives. That process holds memory for every open connection, a deploy or restart\ncuts all of them at once, and every proxy and load balancer on the path has to\nsupport the handshake and put up with a connection that may stay quiet for\nminutes. Running more than one server raises a question that plain HTTP never\nasks: when something happens on server A, how does it reach a client whose\nconnection lives on server B? The usual answer is a shared publish-and-subscribe\nchannel that every server listens to, and that is one more system to operate.\n\nSo it is a choice, not a default. When only the server has news to send,\nserver-sent events, defined in the HTML Standard, push events over an ordinary\nHTTP response of type `text/event-stream`, and the browser reconnects by itself\nwhen the response breaks off. WebSocket earns its extra moving parts when the\nclient has as much to say as the server, as in chat, games and collaborative\nediting.\n\n## What it looks like in practice\n\nThe exchange below opens a chat connection. The key is the sample value from\nRFC 6455 itself, and the accept value is the one the standard prints, which\nevery correct server must send back for that key.\n\n```http\nGET /chat HTTP/1.1\nHost: example.com\nUpgrade: websocket\nConnection: Upgrade\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\nSec-WebSocket-Version: 13\nOrigin: https://example.com\n\nHTTP/1.1 101 Switching Protocols\nUpgrade: websocket\nConnection: Upgrade\nSec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\n```\n\nAfter the blank line that ends the server's answer, nothing on the connection is\nHTTP any more. A browser does the whole handshake behind one constructor call\nand hands the rest to event listeners:\n\n```js\nconst socket = new WebSocket(\"wss://example.com/chat\");\nsocket.addEventListener(\"open\", () =\u003e socket.send(\"hello\"));\nsocket.addEventListener(\"message\", (event) =\u003e console.log(event.data));\nsocket.addEventListener(\"close\", (event) =\u003e {\n  console.log(event.code, event.reason, event.wasClean);\n});\n```\n\nThe close event says how the connection ended. Code 1000 is a normal closure and\n1001 means a peer is going away, such as a server shutting down or a browser\nleaving the page. Code 1006 means the connection dropped without any close frame\nat all. No endpoint may send it; it exists only so the program on top can tell\nan abnormal end from a clean one.\n\nThe line between request-and-answer and a socket shows up clearly in one project\nin this site's portfolio. When an API moved onto Huma v2,\n[every route went onto Huma's request and response model except exactly two](/portfolio/migrated-the-api-to-huma-v2-at-100-parity/):\nthe WebSocket endpoints stayed on raw Fiber, because there the code genuinely\nwants the socket itself and Huma's model does not fit. A framework built around\nHTTP's own shape describes and validates requests and answers well, and a\nlong-lived two-way connection is simply a different thing.\n\n## Where it goes wrong\n\n**A page on another site opens a connection with your visitors' cookies.** The\nbrowser makes the handshake request to the server's host and can include its\ncookies, subject to the browser's cookie policies. Where those policies allow\nauthenticated cross-site requests, a cookie-authenticated server that ignores\nthe `Origin` header can accept a connection opened by\nanother site's page as the visitor. RFC 6455 says a server meant only for\ncertain sites should check `Origin` against the ones it\nexpects and refuse the rest with 403 Forbidden. Do it in the handshake, before\naccepting the connection.\n\n**The access token ends up in the logs.** The browser's `WebSocket` constructor\ntakes a URL and an optional list of subprotocols, and nothing else, so a script\ncannot add an `Authorization` header. The quick way round is a token in the URL,\nwhere reverse proxies and access logs write it down. The RFC leaves\nauthentication open and names cookies, HTTP authentication and TLS\nauthentication as options. A cookie with the `Origin` check above works, and so\ndoes a short-lived, single-use ticket that the page fetches over an\nauthenticated HTTP call and spends on the handshake.\n\n**A restart turns every client into a flood.** An abrupt deploy or restart can\nclose all connections at once. Clients that receive no close frame report code\n1006; if they all reconnect immediately and keep trying, the server comes back\nup to what the RFC likens to a denial-of-service attack. RFC 6455 asks clients\nto wait a random time before the first attempt, suggesting anything between 0\nand 5 seconds, and to wait longer after each failure, for example with\ntruncated binary exponential backoff. A server that closes its connections\nwith 1001 before it stops at least tells clients the break was planned.\n\n```js\nfunction reconnectDelay(attempt) {\n  if (attempt === 0) return Math.random() * 5000;\n  const ceiling = Math.min(60_000, 1000 * 2 ** attempt);\n  return Math.random() * ceiling;\n}\n```\n\n**Connections die and nobody notices.** A connection that carries no traffic\ngives neither side any sign that the path still exists, and a peer that\nvanished without a close frame looks exactly like a quiet one until the next\nwrite fails. Ping and pong exist for this: an endpoint must answer a ping with\na pong unless it has already received a close frame. When several pings are\nunanswered, it may answer only the latest. The RFC notes that a ping can serve\nas a keepalive or as a check that the other side still responds. The browser\nAPI offers no way to send a ping, so the timer belongs on the server: ping\neach connection at a fixed interval and close the ones that miss their pong.\n\n**One message eats the server's memory.** The length field in a frame header\nleaves room for payloads far larger than any server has memory for, and the RFC\nwarns that a hostile peer may send one enormous frame or an endless run of small\nfragments. Implementations must protect themselves, so set a maximum message\nsize in the server library and close with code 1009, message too big, when a\npeer exceeds it. The same backlog builds in the other direction. In the browser,\n`bufferedAmount` reports the bytes `send()` has queued that are still waiting to\ngo out on the network, and the WHATWG example sends its next update only when\nthat number is zero. On the server, a client that reads slowly fills the\noutgoing buffer in the same way, so each connection needs a cap on it and a rule\nfor what happens when the cap is reached.\n\n## Further reading\n\n- [RFC 6455: The WebSocket Protocol](https://www.rfc-editor.org/rfc/rfc6455) —\n  the handshake, framing, masking and close codes, and the security reasoning\n  behind each of them.\n- [WebSockets Standard](https://websockets.spec.whatwg.org/) — the browser API:\n  the constructor, `send()`, `close()`, `bufferedAmount` and the close event.\n- [RFC 9110: HTTP Semantics](https://www.rfc-editor.org/rfc/rfc9110) — the\n  `Upgrade` header field and the 101 Switching Protocols status the handshake\n  relies on.\n- [Server-sent events](https://html.spec.whatwg.org/multipage/server-sent-events.html)\n  — the HTML Standard's one-way alternative, with reconnection built in.\n- [RFC 8441: Bootstrapping WebSockets with HTTP/2](https://www.rfc-editor.org/rfc/rfc8441)\n  — extended CONNECT carries WebSocket on one multiplexed HTTP/2 stream.\n- [RFC 9220: Bootstrapping WebSockets with HTTP/3](https://www.rfc-editor.org/rfc/rfc9220)\n  — the corresponding extended-CONNECT mechanism for HTTP/3.\n\n\u003chttps://engineer.company/glossary/websocket/\u003e\n","date_modified":"2026-11-09T21:50:25Z","description":"How one HTTP request turns into a two-way connection that stays open, when it beats polling, and five ways a long-lived socket goes wrong.","formats":{"gemtext":"https://engineer.company/glossary/websocket/index.gmi","gopher":"https://engineer.company/glossary/websocket/gophermap","html":"https://engineer.company/glossary/websocket/","json":"https://engineer.company/glossary/websocket/index.json","markdown":"https://engineer.company/glossary/websocket/index.md","pdf":"https://engineer.company/glossary/websocket/index.pdf"},"kind":"page","language":"en","title":"What is WebSocket?","url":"https://engineer.company/glossary/websocket/","version":1}