AlgoViz

WebSockets

medium 30 min

WebSocket starts as an HTTP request and then turns the same TCP connection into a two-way channel for small framed messages.

Video lesson · Chapter 1 of 5

Open a two-way room

0:00 / 3:20

WebSocket in 80 seconds: knock, then talk

1:20Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

WebSocket is a protocol, defined in RFC 6455, for two programs that both want to speak at any time over one long-lived connection. It begins with an ordinary HTTP request that asks to switch protocols. After the answer 101, the HTTP part is over.

From then on both sides send frames: small units with a header of a few bytes. A message is text (UTF-8) or binary. Three more kinds of frame look after the connection itself: ping, pong and close.

Why it exists

In HTTP only the client can begin. A server with news has to wait to be asked, and every question carries headers again. For chat, games, shared editing and trading screens, where both sides speak often, that is slow and wasteful.

Raw TCP would do, but a web page may not open raw TCP connections, and firewalls expect web traffic. WebSocket starts as HTTP on the usual ports, so it fits in with browsers, TLS and most of the existing network.

A short history

  1. June 2008

    Discussions led by Michael Carter produce the first version of the protocol, which gets the name WebSocket.

  2. December 2009

    Google Chrome 4 is the first browser to ship it, switched on by default.

  3. December 2011

    RFC 6455 standardises the protocol.

  4. December 2015

    RFC 7692 adds compression as an extension, permessage-deflate.

  5. September 2018

    RFC 8441 lets a WebSocket run on one stream of an HTTP/2 connection. RFC 9220 does the same for HTTP/3 in June 2022.

Words to know

Full duplex
Both sides can send at the same time.
Upgrade
The HTTP exchange that turns the connection into a WebSocket.
Frame
A header and a payload. One message is one or more frames.
Opcode
Four bits in the header that say what kind of frame it is.
Masking
Mixing every client payload with a random 4-byte key. It is not encryption.
Subprotocol
The agreed format of the messages, chosen in the handshake.
Backpressure
Slowing the sender, or dropping, when the receiver cannot keep up.
Half-open
One side is gone, and the other has not noticed yet.

How it works

Step through the idea, or press Play.

Step 1 of 3

Knock. GET with Upgrade: websocket and a random key

Understand it

Start here

The tube between two trees

Asha and Lee each have a platform in a tree. A wide glass tube joins the platforms. They send balls through it, but first they must agree to open the lids.

One tube, both directions
Open the lids?Knock first

The tube does not remember balls. If a ball may not be lost, somebody must number the balls and keep a copy.

This page is about the protocol and how to run it. Which of polling, server-sent events and WebSocket to pick is the topic of real-time APIs.

What you get

Why use it

  • Push

    The server sends when something happens. No polling delay. It is as fast as the network, not instant.

  • Both ways

    Either side starts. Typing, moving and ordering travel up while updates travel down.

  • Small overhead

    2 to 14 bytes of frame header per message instead of hundreds of bytes of HTTP headers.

  • One connection

    No connection setup for each message, so nothing waits for TCP and TLS again.

  • Many updates

    10 to 100 and more small updates a second suit it well, as in games, editors and trading screens.

  • In the browser

    Every modern browser has the WebSocket object. No plugin and no library is needed.

Step 1

The handshake

HTTP
GET /ws HTTP/1.1Host: feed.example.comConnection: UpgradeUpgrade: websocketOrigin: https://app.example.comSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==Sec-WebSocket-Version: 13Sec-WebSocket-Protocol: prices.v2, prices.v1HTTP/1.1 101 Switching ProtocolsConnection: UpgradeUpgrade: websocketSec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=Sec-WebSocket-Protocol: prices.v2
The key and the accept value are the example of RFC 6455.
HeaderWhoMeaning
Connection: UpgradeBothThis hop wants to change protocol
Upgrade: websocketBothTo this one. Upper and lower case do not matter
Sec-WebSocket-KeyClient16 random bytes in base64, new each time
Sec-WebSocket-AcceptServerBase64 of SHA-1 of the key and a fixed text
Sec-WebSocket-VersionClient13
OriginBrowserThe site that opened it. The server must check it
Sec-WebSocket-ProtocolBothClient offers subprotocols, server picks at most one
Sec-WebSocket-ExtensionsBothFor example permessage-deflate (compression)
Subprotocol names include graphql-transport-ws (GraphQL), wamp (calls and pub/sub) and v12.stomp (messaging). If none is agreed, you define your own message format.

The accept value

accept=base64⁡(SHA1⁡(key∥GUID))\text{accept} = \operatorname{base64}\big(\operatorname{SHA1}(\text{key} \mathbin{\Vert} \text{GUID})\big)
The GUID is 258EAFA5-E914-47DA-95CA-C5AB0DC85B11, the same for everybody. It proves that the server speaks WebSocket and did not just return a cached answer. It is not a password.

Before the first message

Any answer other than 101, such as 401 or 403, means there is no WebSocket. The page sees only a close, with code 1006 and no details.

Step 2

Frames

Opcodes

OpcodeKindUse
0x0ContinuationThe next piece of a message sent in pieces
0x1TextValid UTF-8, often JSON
0x2BinaryAny bytes: images, Protocol Buffers, your own format
0x8CloseEnds the connection, with a code and a reason
0x9PingAre you there?
0xAPongYes, with the same payload
Close, ping and pong are control frames: at most 125 bytes, never split. They may come between the pieces of a split message.

Header size

PayloadFrom serverFrom client
0 to 125 bytes26
126 to 65,535 bytes48
More1014
The client column adds the 4-byte masking key.

What small frames save

100,000 messagess×(500−2) B=49.8 MBs100{,}000\ \tfrac{\text{messages}}{\text{s}} \times (500 - 2)\ \text{B} = 49.8\ \tfrac{\text{MB}}{\text{s}}
Assumption: 500 bytes of HTTP headers on an uncompressed request and answer. TCP, IP and TLS bytes come on top in both cases.

One large message in pieces

FIN marks the last piece. Two messages cannot be mixed on one connection, so a huge message delays the rest. Send files another way.

Payload

Text or binary

Start with JSON text: it is easy to read and change. Move the busiest message to binary when measurements ask for it. A price update as one type byte, a 4-byte symbol number, an 8-byte price and an 8-byte time needs 21 bytes. The same in JSON is roughly 60 to 80.

An order book message

1+4+2+2⏟type, symbol, two counts+16 nn=20:;9+320=329 B\underbrace{1 + 4 + 2 + 2}_{\text{type, symbol, two counts}} + 16\,n \qquad n = 20:; 9 + 320 = 329\ \text{B}
Each of the n price levels is a price and a size of 8 bytes each. Both sides must agree on byte order. Floats are fine for display; for money that is counted, send whole numbers of the smallest unit.

Binary

  • Smaller, and quick to read
  • Needs a shared, versioned layout
  • Set ws.binaryType = "arraybuffer" in the browser
  • Protocol Buffers or MessagePack save you from hand-made layouts

Text

  • Larger, though compression helps
  • Must be valid UTF-8, or the connection is closed with 1007
  • Readable in the developer tools
  • Often good enough

Step 3

The life of a connection

States

A closed WebSocket is never opened again. Make a new one.
readyStateNameWhat to do with a message
0CONNECTINGKeep it in a short queue. send throws an error now
1OPENSend
2CLOSINGsend discards it silently. Keep it for the next connection, if it still matters
3CLOSEDThe same

Close codes

CodeMeaningTypical causeReconnect?
1000NormalThe work is doneNo
1001Going awayServer stops, or the person left the pageYes, after a wait
1002Protocol errorA broken frameFind the bug
1003Unsupported dataBinary, but only text is acceptedFind the bug
1006AbnormalNo close frame arrived: network or crash. Never sent on the wireYes, after a wait
1008Policy violationNo permission, limit brokenFix first
1009Message too bigAbove the limit of the receiverFind the bug
1011Internal errorThe server failedYes, after a wait
1012Service restartA deploymentYes, after a wait
1013Try again laterOverloadYes, after a longer wait
4000 to 4999Your ownFor example 4000 for no heartbeatYou decide
A page may only send 1000 or 3000 to 4999. 3000 to 3999 can be registered.

Health

Heartbeats

TCP may take many minutes to notice that the other side is gone, for example when a phone loses its signal. Until then the server holds memory for nobody. A ping every 20 to 60 seconds finds such half-open connections and keeps proxies from closing a quiet path.

Timers that will meet your connection

WhereDefaultChange
nginx as proxyCloses after 60 s without data from your serverproxy_read_timeout, or send pings
AWS Application Load BalancerIdle timeout 60 sAttribute idle_timeout.timeout_seconds
Amazon API Gateway10 minutes idle, 2 hours in allNot adjustable: plan to reconnect
Python websocketsPing every 20 s, waits 20 s for the pongping_interval, ping_timeout
The shortest timer on the path decides. Ping well below it.

Reliability

Reconnect without losing anything

  1. 1

    Wait a random time

    Between 0 and min(30 s, 1 s times 2 to the power of the try). Without the random part, all clients of a failed server come back together. See retries.

  2. 2

    Subscribe again

    The new connection knows nothing about the old one. Keep the list of subscriptions in the client.

  3. 3

    Send the last number

    The server sends everything after it from a store, then goes live.

  4. 4

    Give up rarely

    After many tries show an offline notice, and try again when the network or the page comes back.

  5. 5

    Limit the queue

    Messages written while offline wait in a bounded queue. Old cursor positions can be dropped; chat messages need an id, so that the server keeps each once. See idempotency.

What to do after a close

Slow receivers

Backpressure

TCP slows the sender when the receiver stops reading, and then the bytes pile up in your server. The browser API has no backpressure either: ws.bufferedAmount shows how many bytes still wait to be sent, and WebSocketStream is a newer API that does slow the sender, where a browser offers it.

Bounded

  • A queue with a limit for every client
  • Prices and positions: keep only the newest per key
  • Chat and orders: close the slow client, who then catches up from the store
  • One slow client never delays the others

Unbounded

  • One phone in a tunnel fills the memory
  • Waiting for each client in a loop: all are as slow as the slowest
  • Dropping chat messages without a gap number
  • Nobody measures the queue length

Security

Before you accept

  • wss only

    TLS protects the data, and old proxies that do not understand WebSocket see only an encrypted tunnel.

  • Check Origin

    Browsers let any site open a WebSocket to you and send your cookies. Accept only your own sites. Never return true for all.

  • Sign in

    A cookie at the handshake, or a short-lived ticket in the first message. Page code cannot set an Authorization header, and long-lived tokens in a URL land in logs.

  • Check every message

    Permission per room or symbol, size limit, rate limit, valid format. End the connection when the session ends.

More on identity: API authentication and API authorization.

Scale

From one server to many

A connection lives on one server and stays there. That is what makes these servers stateful. It does not need sticky sessions for the WebSocket itself: after the handshake, there is nothing left to balance. Stickiness only matters for libraries that begin with several HTTP requests. The real question is how a message reaches a client on another server.

A market data service

Traders connect with wss through a load balancer to two WebSocket servers, each its own machine. A feed reader, which receives market prices, publishes them to Redis pub/sub by symbol. Both WebSocket servers subscribe to Redis and push to their own clients.
Each server subscribes only to the symbols its clients want. Redis pub/sub delivers at most once, so a store must fill the gaps.
StepPartsWhat happens
1Browser, balancerGET with Upgrade
2Server101 after the checks
3Browser, serverText frame: subscribe NQ. The server notes it in memory and confirms
4Feed, pub/sub, serverA price arrives once, and goes to every subscriber as a small frame
5Server, browserPing every 30 s. No pong in time: close and clean up
6BothClose 1000, the other side answers with close, TCP ends, subscriptions are removed
NQ stands for Nasdaq futures, a name often seen in trading examples.

Where the load is

50 updatess×20,000 watchers=1,000,000 framess;→;5 updatess: 100,00050\ \tfrac{\text{updates}}{\text{s}} \times 20{,}000\ \text{watchers} = 1{,}000{,}000\ \tfrac{\text{frames}}{\text{s}} ;\to; 5\ \tfrac{\text{updates}}{\text{s}}:\ 100{,}000
People cannot read 50 changes a second. Merging to 5 a second saves 90% of the work.
  • Encode once

    Build the frame for a symbol one time and send the same bytes to all. Server frames are not masked, so they are equal.

  • Balance by connections

    New servers start empty, and old ones stay full. Choose the server with the fewest open connections.

  • Deploy slowly

    Stop taking new clients, close old ones with 1001 or 1012 spread over minutes, keep spare capacity for handshakes.

  • Raise limits

    Open file descriptors, memory per connection, connection tracking in firewalls. Load test with idle and with busy clients.

Pub/sub itself: pub-sub. A whole chat on top of this: group chat app.

Operate

Through proxies

nginx
map $http_upgrade $connection_upgrade {    default upgrade;    ''      close;}server {    location /ws {        proxy_pass http://backend;        proxy_http_version 1.1;   # already the default since nginx 1.29.7        proxy_set_header Upgrade $http_upgrade;        proxy_set_header Connection $connection_upgrade;        proxy_set_header Host $host;        proxy_read_timeout 300s;  # default 60s without data    }}
Upgrade and Connection are hop-by-hop headers: a proxy does not pass them on unless told to.

One connection, two hops

A browser sends wss to our system, where an nginx proxy ends TLS and passes the Upgrade header to a WebSocket server. The server pings every 30 seconds, so that the 60 second timer of the proxy never ends.
The proxy holds one connection on each side, and a timer. A ping every 30 seconds restarts it.

Over HTTP/2 there is no Upgrade and no 101. The client opens a stream with the extended CONNECT method (RFC 8441) when the server announces support. The WebSocket then shares a connection with other requests. HTTP/3 works the same way (RFC 9220). The frames do not change. See HTTP/2 and HTTP/3.

What to watch

MeasureWhy
Open connections, per serverCapacity and balance
Handshakes per second, and failures by statusStorms, broken sign-in
Closes by code1006 rising means network or timers; 1009 means a limit
Queue length per client, slow closesSlow readers before memory is full
Time from event to sendWhat people feel
Frames and bytes outCost, and fan-out that grew

Decide

When to choose it

Choose it for

  • Chat and messaging
  • Multiplayer games in the browser
  • Editing together
  • Trading screens with order books and orders
  • Live sensors and dashboards with control messages
  • Notifications, if a connection is open anyway

Choose something else for

  • Request and answer: plain HTTP
  • Updates from the server only: server-sent events
  • Rare updates: polling
  • Data that should be cached: messages have no URL and no cache
  • Networks whose proxies block it, without a fallback
  • Servers that must hold nothing between requests
Compared withSameDifferentChoose the other when
Server-sent eventsServer push, open connection, in the browserOne way, text only, plain HTTP, reconnects itself, shares HTTP/2The client rarely sends
Long pollingServer push, works in browsersA request per answer, full headers, needs a cursorStreaming is blocked, or as a fallback
gRPC streamingBoth directions, busy streamsHTTP/2, fixed schema, generated code. Browsers need gRPC-Web, which has no client streamingServices talk to services
MQTT can run inside a WebSocket, when a page needs topics and delivery levels. WebTransport offers many streams and unreliable datagrams over HTTP/3.

Summary

The whole topic in one minute.

One HTTP request with Upgrade: websocket, one answer 101, and the TCP connection now carries frames in both directions. A short frame costs 2 bytes of header from the server and 6 from the client.

The connection is the easy part. Real services add heartbeats, reconnecting with a random wait, resuming after the last number seen, bounded buffers for slow clients, an Origin check, and pub/sub between servers. If only the server speaks, server-sent events are simpler.

  • An HTTP GET with Upgrade, an answer 101, and then frames in both directions on the same connection.
  • Text and binary carry data; ping, pong and close carry care. Client frames are masked, server frames are not.
  • 1006 means no close frame was seen. Reconnect after a random, growing wait, subscribe again, and resume by number.
  • Bound the queue of every client, and check Origin, user, size and rate.
  • Across servers, publish by topic and let each server push to its own connections.
  • One way only: server-sent events are simpler.

Sources