Skip to content

    Frontend System Design

    WebSockets in Depth

    Learn how a WebSocket works on the wire: the upgrade handshake, masked frames, fragments, ping and pong, close codes and bufferedAmount, with a model lab.

    By Published 13 min read

    • frontend-system-design
    • websockets
    • real-time
    • protocols
    Share

    Standard lessonintermediateTypeScript labFrontend System Design

    Before this: Polling, Server-Sent Events and WebSockets

    What you'll learn: By the end of this lesson you will be able to describe how a WebSocket opens, read the bytes of a frame (opcode, length, mask), explain why client frames are masked, say how a message is fragmented and where ping and pong fit, close a connection with a code and read it on the other side, and use readyState and bufferedAmount to see what your page is doing.

    Think of a private lane at a loading dock. You knock on the office window with a polite request to use it (an HTTP request). The clerk checks your papers and says "go ahead" (a 101 response). After that you hand over parcels in labelled boxes (frames), the clerk can hand parcels back at any time, and you finish with a spoken goodbye and a reason (the closing handshake).

    The running example is the support-chat panel on the ShopStream grocery marketplace. Polling, Server-Sent Events and WebSockets explains when to choose one; this lesson is about what it is.

    The core idea

    1. A WebSocket is an HTTP upgrade followed by framed messages on the same connection. After the handshake the bytes are frames, not HTTP.
    2. The page sees a thin view of a richer protocol. readyState, send(), bufferedAmount and the close event summarise opcodes, masking, fragments and a closing handshake.
    3. The protocol gives you messages, not delivery guarantees. What happens to a message when the connection dies is the application's job (later lessons).

    Three illustrations run through the lesson: a minimal example (the handshake and the "Hello" frames of RFC 6455), a realistic example (the chat panel) and a failure example (frames that break the rules).

    The opening handshake

    A WebSocket begins as an ordinary HTTP/1.1 request. RFC 6455 requires a GET of at least HTTP/1.1 with Upgrade: websocket, a Connection header that includes Upgrade, a Sec-WebSocket-Key that is a random 16-byte value (base64 text) and Sec-WebSocket-Version: 13; a browser also sends Origin. The page can offer sub-protocols (names such as chat.v2 for the messages that will travel), and the connection opens only if the server picks one of them.

    The server answers 101 with a Sec-WebSocket-Accept header: the key plus the fixed string 258EAFA5-E914-47DA-95CA-C5AB0DC85B11, hashed with SHA-1 and base64-encoded. The RFC's example turns dGhlIHNhbXBsZSBub25jZQ== into s3pPLMBiTxaQ9kYGzzhZRbK+xOo=, and the lab computes the same. Any other status means the handshake has not completed; the lab's client opens only on a 101 whose accept value matches its key.

    Figure 1. The opening handshake

    sequenceDiagram accTitle: The WebSocket opening handshake accDescr: The browser sends an HTTP GET with Upgrade, Connection, a random key, version 13, an Origin and optional sub-protocol names. The server checks the origin and the request, then answers 101 Switching Protocols with the accept value computed from the key and the chosen sub-protocol. If the origin is not expected it answers 403 instead. After 101 both sides exchange frames. participant B as Browser participant S as Server B->>S: GET /live, Upgrade websocket, key, version 13, Origin alt origin expected and request valid S-->>B: 101 Switching Protocols, accept value, chosen sub-protocol Note over B,S: from here on, frames instead of HTTP else origin not expected S-->>B: 403 Forbidden end

    How to read this: everything above the 101 is HTTP; everything after it is frames on the same connection.

    Two security points live here. RFC 6455 says a server should verify that Origin is one it expects and answer 403 Forbidden if not, because a page on any site can try to open a socket to your server. It also "doesn't prescribe any particular way" to authenticate a client during the handshake (cookies, HTTP authentication and TLS authentication are its examples). The browser constructor has no option for custom headers, so a common design is a cookie or a short-lived ticket from your API. The wss scheme (default port 443) is tunnelled over TLS. Over HTTP/2, RFC 8441 replaces the key and accept headers with an extended CONNECT.

    What a frame looks like

    After 101, each message travels in one or more frames. The first two bytes carry the control fields:

    Field Size Meaning
    FIN 1 bit This is the last fragment of a message
    RSV1 to RSV3 3 bits Must be 0 unless an extension was negotiated
    Opcode 4 bits 0x0 continuation, 0x1 text, 0x2 binary, 0x8 close, 0x9 ping, 0xA pong
    MASK 1 bit Whether the payload is masked
    Payload length 7 bits, or 7 plus 16 or 64 0 to 125 is the length itself; 126 means the next 2 bytes hold it; 127 means the next 8 bytes
    Masking key 4 bytes, if MASK is set The XOR key
    Payload the rest The data

    The lab prints the RFC's own examples. An unmasked text frame for "Hello" is 81 05 48 65 6c 6c 6f: 0x81 is FIN plus opcode 1, 0x05 is "no mask, length 5". From a client the same message is 81 85 37 fa 21 3d 7f 9f 4d 51 58: the length byte carries the mask bit (0x85), then the 4-byte key, then the payload XORed with the key, repeating it. A 256-byte payload needs the 16-bit length form and 65536 bytes the 64-bit form.

    Figure 2. What sits between send() and the wire

    A message passes through the page's socket object, a frame encoder that masks it, and the networkPage code to Socket object (send(data)); Socket object to Frame encoder (queued bytes); Frame encoder to Server (masked frames)Page code: send, onmessagePage codesend, onmessageSocket object: readyStateSocket objectreadyStateFrame encoder: mask, lengthFrame encodermask, lengthServer: unmasks, parsesServerunmasks, parsessend(data)queued bytesmasked frames

    How to read this: send() returns before anything leaves the machine. The bytes wait in the queue (that is bufferedAmount) until the network takes them.

    Why masking exists. The 32-bit key is chosen at random by the client and must come from a strong source of entropy. The RFC's reason (section 10.3) is to protect infrastructure: masking stops a remote script from controlling how its data looks on the wire, so it cannot build bytes that a confused intermediary reads as an HTTP request. A client must mask every frame, a server must not, and a server must close the connection on an unmasked frame (it may send 1002, a protocol error). Masking is not encryption: the key travels in the frame.

    Messages, fragments, ping and pong

    A message is unfragmented when it is one frame with FIN set. A sender may split it: the first frame carries the real opcode (text or binary) with FIN clear, the next frames use opcode 0x0 (continuation), and the last has FIN set. Fragments must be delivered in the order sent, the fragments of two messages must not be interleaved, and every endpoint must accept both forms. A text message must be valid UTF-8 as a whole (a character may be cut between fragments), and an endpoint that finds invalid UTF-8 must fail the connection.

    Control frames (close, ping, pong) carry at most 125 bytes, are never fragmented, and may be injected in the middle of a fragmented message. An endpoint that receives a ping must answer with a pong with the same data, unless it already received a Close frame; a pong may also be sent unsolicited, as a one-way heartbeat.

    Figure 3. A message in three fragments with a ping in the middle

    sequenceDiagram accTitle: Fragments with a ping in between accDescr: The client sends a text frame with FIN clear carrying the first part, then a ping with data p1, then a continuation frame with FIN clear, then a final continuation frame with FIN set. The server answers the ping with a pong carrying the same data and delivers one text message once the last fragment arrives. participant C as Client participant S as Server C->>S: text frame, FIN clear, "Hello" C->>S: ping "p1" (control frame, not fragmented) S-->>C: pong "p1" C->>S: continuation, FIN clear, ", wor" C->>S: continuation, FIN set, "ld" Note over S: delivers one message: Hello, world

    How to read this: the application sees one message; the ping and pong stay at the protocol layer.

    MDN lists only close() and send() as methods of the WebSocket interface, so page code cannot send a protocol ping: a heartbeat from the page is an ordinary message that the server must answer itself. Heartbeats get their own lesson later.

    Closing, and the codes

    Either side starts closing by sending a Close frame: a 2-byte status code, optionally followed by a UTF-8 reason. An endpoint that receives one it did not provoke must send one back, and after sending one an application must not send more data frames. When both have been sent and received, the endpoint should close the connection; the server closes TCP first.

    Figure 4. The states of a clean close, and the way out when there is none

    stateDiagram-v2 accTitle: Closing a WebSocket accDescr: The connection is open. When the page calls close it sends a Close frame and moves to closing. When the peer's Close frame arrives, the connection is closed with the peer's code. If the peer's Close frame arrives first, the endpoint answers with its own and the connection is closed. If the transport breaks with no Close frame, the connection is closed abnormally and the page sees code 1006. [*] --> OPEN OPEN --> CLOSING: close() sends a Close frame CLOSING --> CLOSED: peer's Close frame arrives OPEN --> CLOSED: peer's Close arrives, ours sent in reply OPEN --> CLOSED: transport lost, no Close frame (1006) CLOSED --> [*]

    How to read this: clean paths end after a Close frame each way. The last path has no goodbye, which the page reports as 1006.

    Code Meaning (RFC 6455)
    1000 Normal closure
    1001 An endpoint is "going away"
    1002 Protocol error (the lab's choice for malformed or unmasked frames)
    1007 Data not consistent with the message type (text that is not UTF-8)
    1008, 1009 Policy violation; message too big to process
    1011 Unexpected condition at the server
    1005, 1006, 1015 Reserved: an endpoint must not set them in a Close frame (1006 is used for an abnormal close, 1015 for a TLS failure)
    3000 to 3999 For libraries, frameworks and applications
    4000 to 4999 Private use

    In the browser, close(code, reason) accepts only 1000 or a code from 3000 to 4999 (otherwise InvalidAccessError) and a reason of at most 123 bytes (otherwise SyntaxError). The close event reports wasClean, code and reason, and a connection closed abnormally reports 1006: it means "the connection ended and nobody said goodbye", not "an error 1006 was sent".

    What the page sees: readyState, send() and bufferedAmount

    The browser object has four states: CONNECTING (0), OPEN (1), CLOSING (2) and CLOSED (3). send() throws while CONNECTING. bufferedAmount is "the number of bytes of application data (UTF-8 text and binary data) that have been queued using send()", and once the connection is closed it only increases: send() after a close does not fail loudly, it counts bytes that will never leave.

    // Sketch with the browser API, not run by the lab: do not queue when the socket is not open or is backed up.
    function trySend(socket: WebSocket, text: string, maxBuffered = 64 * 1024): "sent" | "closed" | "busy" {
      if (socket.readyState !== WebSocket.OPEN) return "closed";
      if (socket.bufferedAmount > maxBuffered) return "busy";
      socket.send(text);
      return "sent";
    }

    MDN says the WebSocket interface has no backpressure: when messages arrive faster than the page can process them it fills memory, hits 100% CPU, or both, and it points to the WebTransport API for a version that supports it. A cap on bufferedAmount protects only the sending side.

    Trade-offs

    Choice Gain Cost
    Authenticate in the handshake (cookie or ticket) No per-message cost A ticket must be short-lived; a cookie ties you to cookie rules
    Fragment a large message A ping or close can go between the pieces More frames; the receiver must cap the reassembled size
    Limit message size at the server A bad client cannot exhaust memory A client over the limit is closed with 1009 and must handle it
    Heartbeat from the page Detects dead connections Traffic, and server code to answer it

    Build it: the protocol as data

    Goal. Run a model of the WebSocket protocol: compute the accept value, encode and parse frames, reassemble fragments, answer a ping, close cleanly, and watch a receiver reject broken frames.

    Setup. The lab is in the course's example workspace (Node 26.13.1, pnpm). It is a model, not a socket: there is no TCP, TLS, browser, timing or extension, and two Endpoint objects hand bytes to each other. Where the RFC leaves a choice (the code sent on a failure, the size limit, mask keys that count up from the RFC's sample key instead of being random) the code says so.

    cd examples/frontend
    pnpm install
    cd labs/websocket-protocol-model
    pnpm test           # 53 tests
    node src/demo.ts

    Steps.

    1. Run the tests, then the demo. Section 1's accept value must be s3pPLMBiTxaQ9kYGzzhZRbK+xOo=.
    2. In section 2, compare the bytes with the RFC's section 5.7 examples and the table above.
    3. In section 4, find the ping inside three fragments and the single message that comes out.
    4. In section 6, read the first line: a client frame that is not masked.

    Expected output, captured from a real run (Node 26.13.1, 2026-12-01), the handshake and the frame bytes:

    WebSocket protocol as a model: handshake, frames, closing (no sockets)
    
    === 1. The opening handshake (RFC 6455 section 4)
    client request:
      GET /live HTTP/1.1
      Host: shop.example
      Upgrade: websocket
      Connection: Upgrade
      Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
      Sec-WebSocket-Version: 13
      Origin: https://shop.example
      Sec-WebSocket-Protocol: chat.v1, chat.v2
    server answer:
      HTTP/1.1 101 Switching Protocols
      Upgrade: websocket
      Connection: Upgrade
      Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
      Sec-WebSocket-Protocol: chat.v2
    accept value for the RFC sample key: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
    client check: {"ok":true,"protocol":"chat.v2"}
    unexpected origin: 403 (origin https://evil.example is not expected)
    plain GET: 400 (Upgrade must name websocket)
    client check of a wrong accept value: {"ok":false,"reason":"Sec-WebSocket-Accept does not match the key"}
    
    === 2. Frame bytes (compare RFC 6455 section 5.7)
    text "Hello", server to client:  81 05 48 65 6c 6c 6f
    text "Hello", client to server:  81 85 37 fa 21 3d 7f 9f 4d 51 58
    fragment 1 of 2, "Hel":          01 03 48 65 6c
    fragment 2 of 2, "lo":           80 02 6c 6f
    ping "Hello":                    89 05 48 65 6c 6c 6f
    pong "Hello", masked:            8a 85 37 fa 21 3d 7f 9f 4d 51 58
    payload length   header bytes (unmasked)
                 5    2: 82 05
               125    2: 82 7d
               126    4: 82 7e 00 7e
               256    4: 82 7e 01 00
             65535    4: 82 7e ff ff
             65536   10: 82 7f 00 00 00 00 00 01 00 00

    Expected output, captured from a real run (same run), messages, fragments and the closing handshake:

    === 3. Two endpoints, one message each way
    client bufferedAmount after send: 5
    bytes on the wire (masked):       81 85 37 fa 21 3d 5f 9f 4d 51 58
    client bufferedAmount after the frame left: 0
    server received: ["hello"]
    bytes on the wire (unmasked):     81 07 77 65 6c 63 6f 6d 65
    send() while CONNECTING throws: InvalidStateError: the connection is still CONNECTING
    
    === 4. A message in three frames, a ping in the middle, bytes arriving in 4-byte pieces
    stream: 38 bytes in 4 frames
    server messages: ["Hello, world"]
    server log: received ping (2 bytes)
    client log: received pong (2 bytes)
    
    === 5. The closing handshake, and a connection that just vanishes
    before: client OPEN, server OPEN
    after client.close(): client CLOSING, server OPEN
    after both Close frames: client CLOSED, server CLOSED
    client close event: {"code":1000,"reason":"done","wasClean":true}
    server close event: {"code":1000,"reason":"done","wasClean":true}
    client log: sent close 1000 "done"; received close 1000 "done"
    server log: received close 1000 "done"; sent close 1000 "done"
    send() after close: nothing queued, bufferedAmount 4, frames queued 0
    close(1005, 0 chars) throws: InvalidAccessError: code must be 1000 or 3000 to 4999
    close(1000, 124 chars) throws: SyntaxError: reason is longer than 123 bytes
    connection lost: CLOSED {"code":1006,"reason":"","wasClean":false}
    CLOSED is 3, CLOSING is 2

    Expected output, captured from a real run (same run), protocol failures and bufferedAmount:

    === 6. Protocol failures: the receiver sends a Close frame with a code and stops
    client frame that is not masked          -> close 1002, CLOSED, wasClean false, messages 0
    ping split into fragments                -> close 1002, CLOSED, wasClean false, messages 0
    ping with 126 bytes                      -> close 1002, CLOSED, wasClean false, messages 0
    continuation with nothing to continue    -> close 1002, CLOSED, wasClean false, messages 0
    new message before the last one ended    -> close 1002, CLOSED, wasClean false, messages 0
    text that is not UTF-8                   -> close 1007, CLOSED, wasClean false, messages 0
    message over the 16-byte limit           -> close 1009, CLOSED, wasClean false, messages 0
    
    === 7. bufferedAmount: six 1000-byte messages, a link that carries 2500 bytes per tick
    tick 0: queued 6 frames, bufferedAmount 6000
    tick 1: queued 4 frames, bufferedAmount 4000, server has 2
    tick 2: queued 2 frames, bufferedAmount 2000, server has 4
    tick 3: queued 0 frames, bufferedAmount 0, server has 6

    What the lab does not show. No network, TCP, TLS, latency, proxy or browser scheduling. The 2500-byte "link" and the 16-byte limit are made up. The RFC allows 1002 for an unmasked frame; the other failure codes are the lab's choices. Counting send() during CLOSING in bufferedAmount is a simplification: the standard read here states it only for a closed connection. Extensions such as compression are out of scope.

    Break it. In src/endpoint.ts, in the constructor, change expectMasked: this.role === "server" to expectMasked: false. A server now rejects the masked frames every client sends, and tests such as "delivers text and binary messages in order" fail. Restore it.

    In practice: a support chat that reconnects in a loop

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    The support chat panel opens a WebSocket when the shopper opens it. Messages go up as text, replies come down, and the server refuses a message over 64 KB (illustrative). The panel reconnects automatically on any close.

    Starting architecture

    Figure 5. Starting point: any close triggers a reconnect

    Starting architecture: the panel reconnects on every close, whatever the reasonChat panel to Chat gateway (frames); Chat gateway to Support service; Chat gateway to Chat panel (close, any code)Chat panel: reconnects on closeChat panelreconnects oncloseChat gateway: 64 KB limitChat gateway64 KB limitSupport service: repliesSupportservicerepliesframesclose, any code

    How to read this: the red edge is the problem. The panel treats every close alike, whether it came from a deploy or from a refused message.

    Options considered

    Option What it fixes What it costs Risk
    Reconnect on every close Survives deploys and drops Nothing new A permanent refusal becomes a reconnect storm
    Reconnect by close code, with backoff; check size before send() Retries only what is transient; the common case never hits the limit A table of codes and a copy of the limit The two limits can drift

    The decision

    Field Decision record
    Context A user pasted a huge text; the server closed with 1009; the panel reconnected and resent it from its queue, again and again.
    Decision Read code and wasClean in the close handler. Retry with backoff on 1001, 1006 and clean closes the user did not ask for. Do not retry on 1008 or 1009: show an error on the message. Check the size before send().
    Consequences, good A refused message ends in a clear error, and transient drops still recover.
    Consequences, bad The client carries a copy of the size limit and a table of codes.
    Revisit when The server adds its own codes in the 4000 to 4999 range, or messages become large binary data.

    Rollout and verification

    1. Log every close with code, wasClean and the time since open, before changing behaviour.
    2. Test each row of the code table with a fake socket, and send an over-limit message on staging.

    The 2 a.m. failure

    At the evening peak the gateway's connection count triples and users are "typing into nothing". Logs show clients opening a connection, sending one message and receiving close code 1009, repeatedly (illustrative): the queue holds a message that can never be sent, and every reconnect resends it.

    First three checks: (1) read the close codes in gateway logs and client metrics; (2) check whether the size limit changed in a recent deploy; (3) check whether the client drops a message after it is refused. Mitigation: deploy the client check, stop reconnecting on 1009, or raise the limit. Follow-up: alert on repeated opens from one client, cap reconnect attempts, and put close codes on the dashboard.

    Architect's notes

    • Read the close code, always. It is the only reason the protocol gives; log it with wasClean and the connection's age.
    • Limit message size on both ends, after reassembly.
    • Authenticate before you upgrade, with a short-lived ticket.

    Common mistakes

    • Reconnecting in a tight loop on a code that will never succeed.
    • Reading 1006 as a server error code. It means no Close frame arrived.
    • Assuming masking protects privacy. The key is in the frame; TLS (wss) protects the bytes.

    Key takeaways

    • A WebSocket is an HTTP upgrade (101 plus an accept value computed from the client's key) followed by frames.
    • A frame has FIN, an opcode, a length (7, 16 or 64 bits) and, from a client, a mask; clients must mask and servers must not.
    • Messages can be fragmented; ping, pong and close are at most 125 bytes, never fragmented, and may sit between fragments.
    • Closing is a handshake with a code; 1006 means no Close frame arrived.
    • readyState and bufferedAmount show your side of the queue; the browser API has no backpressure.
    • Treat close codes as data: retry transient ones, stop on policy and size ones.

    Practice exercises

    Exercise 1 — Starter (45 min): Encode by hand the client frame for "OK" with the key 37 fa 21 3d, check it against the lab's encodeFrame, and say which byte holds the mask bit.

    Exercise 2 — Intermediate (2 hours): Add lab tests for a Close frame with a one-byte body and one whose reason is not valid UTF-8. Decide which code each should produce and whether the RFC fixes it.

    Exercise 3 — Advanced (half day): Write a reconnect policy table (close code to action) for the chat panel, with a fake-socket test per row.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments