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.

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

TCP, TLSBrowserpageWebSocket serverwaiting

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

GET, 101BrowsertraderWebSocket server0 symbols

The screen opens a WebSocket.

Step 1: Connect

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Accepting every Origin

    critical

    Another site can open a WebSocket in the visitor's browser, with the visitor's cookies, and act as that person.

    Wrong
    def check_origin(origin):    return True
    Right
    ALLOWED = {"https://app.example.com"}def check_origin(origin):    return origin in ALLOWED
  • Reconnecting at once

    major

    After a server failure all clients return in the same second, and again after each failure.

    Wrong
    on_close = lambda: connect()
    Right
    on_close = lambda: after(    random(0, min(30, 2 ** tries)), connect)
  • Waiting for each client in the loop

    critical

    The slowest client sets the speed for everybody, and unbounded buffers fill the memory.

    Wrong
    for c in clients:    await c.send(m)
    Right
    for c in clients:    if not c.queue.try_put(m):   # bounded        c.close(1013)
  • Delivering locally and by pub/sub

    major

    The publishing server is subscribed too, so its own clients get the message twice.

    Wrong
    send_local(m)pubsub.publish(room, m)
    Right
    pubsub.publish(room, m)# on_pubsub() is the only sender
  • Calling send in any state

    minor

    In CONNECTING it throws. In CLOSING and CLOSED the message silently disappears.

    Wrong
    ws.send(m)
    Right
    if 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.