WebSockets
medium 30 minWebSocket 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
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
June 2008
Discussions led by Michael Carter produce the first version of the protocol, which gets the name WebSocket.
December 2009
Google Chrome 4 is the first browser to ship it, switched on by default.
December 2011
RFC 6455 standardises the protocol.
December 2015
RFC 7692 adds compression as an extension, permessage-deflate.
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.
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.
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
WebSocketobject. No plugin and no library is needed.
Step 1
The handshake
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| Header | Who | Meaning |
|---|---|---|
Connection: Upgrade | Both | This hop wants to change protocol |
Upgrade: websocket | Both | To this one. Upper and lower case do not matter |
Sec-WebSocket-Key | Client | 16 random bytes in base64, new each time |
Sec-WebSocket-Accept | Server | Base64 of SHA-1 of the key and a fixed text |
Sec-WebSocket-Version | Client | 13 |
Origin | Browser | The site that opened it. The server must check it |
Sec-WebSocket-Protocol | Both | Client offers subprotocols, server picks at most one |
Sec-WebSocket-Extensions | Both | For example permessage-deflate (compression) |
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
Before the first message
Step 2
Frames
Opcodes
| Opcode | Kind | Use |
|---|---|---|
0x0 | Continuation | The next piece of a message sent in pieces |
0x1 | Text | Valid UTF-8, often JSON |
0x2 | Binary | Any bytes: images, Protocol Buffers, your own format |
0x8 | Close | Ends the connection, with a code and a reason |
0x9 | Ping | Are you there? |
0xA | Pong | Yes, with the same payload |
Header size
| Payload | From server | From client |
|---|---|---|
| 0 to 125 bytes | 2 | 6 |
| 126 to 65,535 bytes | 4 | 8 |
| More | 10 | 14 |
What small frames save
One large message in pieces
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
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
| readyState | Name | What to do with a message |
|---|---|---|
| 0 | CONNECTING | Keep it in a short queue. send throws an error now |
| 1 | OPEN | Send |
| 2 | CLOSING | send discards it silently. Keep it for the next connection, if it still matters |
| 3 | CLOSED | The same |
Close codes
| Code | Meaning | Typical cause | Reconnect? |
|---|---|---|---|
| 1000 | Normal | The work is done | No |
| 1001 | Going away | Server stops, or the person left the page | Yes, after a wait |
| 1002 | Protocol error | A broken frame | Find the bug |
| 1003 | Unsupported data | Binary, but only text is accepted | Find the bug |
| 1006 | Abnormal | No close frame arrived: network or crash. Never sent on the wire | Yes, after a wait |
| 1008 | Policy violation | No permission, limit broken | Fix first |
| 1009 | Message too big | Above the limit of the receiver | Find the bug |
| 1011 | Internal error | The server failed | Yes, after a wait |
| 1012 | Service restart | A deployment | Yes, after a wait |
| 1013 | Try again later | Overload | Yes, after a longer wait |
| 4000 to 4999 | Your own | For example 4000 for no heartbeat | You decide |
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
| Where | Default | Change |
|---|---|---|
| nginx as proxy | Closes after 60 s without data from your server | proxy_read_timeout, or send pings |
| AWS Application Load Balancer | Idle timeout 60 s | Attribute idle_timeout.timeout_seconds |
| Amazon API Gateway | 10 minutes idle, 2 hours in all | Not adjustable: plan to reconnect |
Python websockets | Ping every 20 s, waits 20 s for the pong | ping_interval, ping_timeout |
Reliability
Reconnect without losing anything
- 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
Subscribe again
The new connection knows nothing about the old one. Keep the list of subscriptions in the client.
- 3
Send the last number
The server sends everything after it from a store, then goes live.
- 4
Give up rarely
After many tries show an offline notice, and try again when the network or the page comes back.
- 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
| Step | Parts | What happens |
|---|---|---|
| 1 | Browser, balancer | GET with Upgrade |
| 2 | Server | 101 after the checks |
| 3 | Browser, server | Text frame: subscribe NQ. The server notes it in memory and confirms |
| 4 | Feed, pub/sub, server | A price arrives once, and goes to every subscriber as a small frame |
| 5 | Server, browser | Ping every 30 s. No pong in time: close and clean up |
| 6 | Both | Close 1000, the other side answers with close, TCP ends, subscriptions are removed |
Where the load is
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
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 }}One connection, two hops
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
| Measure | Why |
|---|---|
| Open connections, per server | Capacity and balance |
| Handshakes per second, and failures by status | Storms, broken sign-in |
| Closes by code | 1006 rising means network or timers; 1009 means a limit |
| Queue length per client, slow closes | Slow readers before memory is full |
| Time from event to send | What people feel |
| Frames and bytes out | Cost, 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 with | Same | Different | Choose the other when |
|---|---|---|---|
| Server-sent events | Server push, open connection, in the browser | One way, text only, plain HTTP, reconnects itself, shares HTTP/2 | The client rarely sends |
| Long polling | Server push, works in browsers | A request per answer, full headers, needs a cursor | Streaming is blocked, or as a fallback |
| gRPC streaming | Both directions, busy streams | HTTP/2, fixed schema, generated code. Browsers need gRPC-Web, which has no client streaming | Services talk to services |
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.