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.
See it run
Knock in HTTP, talk in frames, notice silence, come back without a gap, and reach clients on other servers.
Operations
Handshake
An HTTP request becomes a two-way channel on the same connection.
Step 1 of 5
TCP and TLS
The browser connects to port 443, as for any page.
Step 1: TCP and TLS
def handshake(request): if request["upgrade"].lower() != "websocket": return 400 if request["origin"] not in ALLOWED: return 403 if not user_of(request): return 401 accept = base64(sha1(request["key"] + GUID)) return 101, {"Sec-WebSocket-Accept": accept}- Cost
- 1 round trip after TCP and TLS
- Protects against
- Strangers, if you check
Do every check before the 101. After it there are no HTTP status codes any more.
In the real world
The same websockets doing real jobs. Pick one and step through it.
From connecting to closing, with one feed and many watchers.
Step 1 of 5
Connect
The screen opens a WebSocket.
Step 1: Connect
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Accepting every Origin
criticalAnother site can open a WebSocket in the visitor's browser, with the visitor's cookies, and act as that person.
Wrongdef check_origin(origin): return TrueRightALLOWED = {"https://app.example.com"}def check_origin(origin): return origin in ALLOWEDReconnecting at once
majorAfter a server failure all clients return in the same second, and again after each failure.
Wrongon_close = lambda: connect()Righton_close = lambda: after( random(0, min(30, 2 ** tries)), connect)Waiting for each client in the loop
criticalThe slowest client sets the speed for everybody, and unbounded buffers fill the memory.
Wrongfor c in clients: await c.send(m)Rightfor c in clients: if not c.queue.try_put(m): # bounded c.close(1013)Delivering locally and by pub/sub
majorThe publishing server is subscribed too, so its own clients get the message twice.
Wrongsend_local(m)pubsub.publish(room, m)Rightpubsub.publish(room, m)# on_pubsub() is the only senderCalling send in any state
minorIn CONNECTING it throws. In CLOSING and CLOSED the message silently disappears.
Wrongws.send(m)Rightif ws.ready_state == OPEN: ws.send(m)else: queue.append(m) # with a limit
Interview tips
How to explain it
- One HTTP request, 101, then frames both ways.
- Text, binary, ping, pong, close.
- The protocol remembers nothing: number, store, resume.
Memory trick
- 9 pings, A answers.
- Client masked, server plain.
- 1006: gone without a goodbye.
Reach for it when
- Both sides speak often.
- Data is binary, or tiny and frequent.
- People share one live thing.
Avoid it when
- Only the server speaks: SSE.
- Updates are rare: poll.
- Answers should be cached: HTTP.