Every Python developer who has shipped a realtime feature has met the same three bugs. First, the connection that dies silently behind a load balancer because nobody configured keepalive pings, and the client sits waiting forever on a dead socket. Second, the cryptic ConnectionClosedError with close code 1006 — a code your server never sent, because 1006 does not travel on the wire; it means the TCP stream ended without a proper close frame. Third, the day a security reviewer asks why your client library has no proxy support, or why a single 100 MB JSON message just ballooned your server’s memory. These are not application bugs; they are protocol-machinery bugs living in the library beneath your handlers.

The websockets library — the WebSocket implementation for Python, built on top of CPython’s asyncio — takes these bugs personally. Its documentation famously explains why close codes are what they are, it ships keepalive defaults tuned from real deployment experience, and recent releases added HTTP proxy support with per-hop TLS. But the most interesting thing about it is invisible from the API: the entire protocol is implemented once, in pure Python, with no sockets, no event loop, and no I/O of any kind. That sans-I/O core is what lets the same project serve asyncio, threads, and trio from identical code.

This tour walks the real tree on the main branch (development toward 17.5). Everything lives under src/websockets/: the sans-I/O kernel in protocol.py and frames.py, the RFC 6455 handshake in client.py, server.py, and utils.py, the HTTP upgrade parser in http11.py, the asyncio implementation in asyncio/, a thread-based blocking implementation in sync/, a trio implementation in trio/, and one optional C extension in speedups.c. The diagram below shows how a single Protocol class fans out into three runtimes.

Architecture overview of the websockets library: sans-I/O core, frame codec, handshake, and three backends

From left to right: two async or threaded entry points, the handshake layer, and the shared sans-I/O kernel that all three runtimes drive byte-for-byte identically.

Reading the overview from left to right:

  • Protocol, L71 is the kernel: a state machine with Side (client or server) and a four-state State enum — CONNECTING, OPEN, CLOSING, CLOSED — plus a default incoming-message cap of 2**20 bytes.
  • parse, L564 is the receiving heart: a plain generator that never raises, instead mapping ProtocolError to close code 1002, EOFError to 1006, UnicodeDecodeError to 1007, and PayloadTooBig to 1009 before failing the connection per RFC 6455 §7.1.7.
  • Frame.parse, L261 decodes the wire format: a two-byte header, then a 7-bit, 16-bit, or 64-bit length, then the optionally masked payload.
  • connect, L97 builds the upgrade request with Sec-WebSocket-Key and Sec-WebSocket-Version: 13.
  • accept, L121 answers with a literal Response(101, "Switching Protocols") after validating the client’s key.
  • accept_key, L27 proves the handshake: base64 of SHA-1 over the key plus the fixed RFC 6455 GUID 258EAFA5-E914-47DA-95CA-C5AB0DC85B11.
  • Connection, L33 is the asyncio adapter — an asyncio.Protocol subclass whose constructor defaults to 20-second keepalive pings with a 20-second pong timeout.
  • PerMessageDeflate, L33 negotiates RFC 7692 compression, driving zlib with negative wbits and window sizes constrained to 8 through 15.

The detail view goes one level deeper — every parser state, every serializer helper, and the thread-based and trio backends:

Detailed module graph of websockets: parse generator, frame codec, handshake negotiation, asyncio internals, sync and trio backends

The same kernel, exploded: generator-driven parsing on the left, wire-format encoding center, runtime adapters on the right.

The sans-I/O core: a state machine with no sockets

Open protocol.py and there is no import asyncio, no socket, no event loop — not even a type hint mentioning one. The Protocol class receives bytes through receive_data(), hands them to a StreamReader, and advances a generator — not an async coroutine, just a plain generator stepped with next(). Outputs collect in two buffers: events (decoded Frame objects, or the Request/Response dataclasses during the handshake) and writes (serialized bytes, or the b"" sentinel SEND_EOF meaning “half-close the TCP connection”). The runtime adapter’s job is comically small: feed bytes in, call events_received() and data_to_send() out, and translate the sentinel into a transport call.

The close choreography is where the design earns its keep. When a Close frame arrives, recv_frame() at line 673 does not re-serialize anything — it echoes the received payload verbatim, because an empty close frame parses to the internal code 1005 (NO_STATUS_RCVD) which is not legal on the wire; re-sending it would be a protocol violation. Servers then immediately send_eof() and swap the parser for discard(), which drains and ignores everything until EOF, exactly as RFC 6455 §1.4 requires. Clients wait for the server to close first — asymmetric closing is one of those RFC rules most hand-rolled implementations get wrong, and it is a three-line branch here. And because every error path funnels through fail() with the correct close code, the 1006 mystery from the hook above dissolves: the library distinguishes abnormal closure (TCP died mid-stream) from normal closure (both sides exchanged close frames with codes in OK_CLOSE_CODES), and raises ConnectionClosedOK versus ConnectionClosedError accordingly.

The frame codec: RFC 6455 in 500 lines

frames.py is the whole wire format: opcode constants 0x00–0x0A, the IANA close-code table, and a Frame dataclass with opcode, data, fin, and three reserved bits rsv1–rsv3. The parser reads a two-byte header, interprets the four high bits of the first byte as FIN/RSV flags, validates the opcode, checks that the MASK bit matches the side (only clients mask, only servers require masks), and then decodes the length: 126 means “next two bytes are a 16-bit length”, 127 means “next eight bytes are a 64-bit length”. check() enforces two invariants people always forget: control frames (close, ping, pong) must be ≤125 bytes and never fragmented — a rule that exists so control frames cannot be blocked behind a giant fragmented message.

Two touches show the engineering maturity. First, serialization picks the smallest length encoding — !BB, !BBH, or !BBQ struct formats — and client-side masking draws a fresh 4-byte key from secrets.token_bytes(4) for every frame. Second, __str__ is a full logging subsystem: it tries to render payloads as UTF-8 even in binary frames, handles UTF-8 sequences split across fragment boundaries via is_utf8_fragment() (which decodes only the clean interior of a fragment), and elides long payloads to a configurable 75 characters (env-var WEBSOCKETS_MAX_LOG_SIZE). Debug logs that show TEXT 'hello' [3 bytes] instead of hex soup are the difference between diagnosing a protocol bug in minutes versus hours.

The handshake: entropy, a GUID, and one SHA-1

The opening handshake is two classes extending the kernel. ClientProtocol.connect() assembles the upgrade request: Host, Upgrade: websocket, Connection: Upgrade, Sec-WebSocket-Key, Sec-WebSocket-Version: 13, plus optional Origin, basic auth from the URI, and negotiated Sec-WebSocket-Extensions and Sec-WebSocket-Protocol headers built by headers.py. The key is 16 random bytes from secrets.token_bytes(16), base64-encoded — not a hash, not a UUID, just entropy to defeat caching proxies. The server side validates that header (exactly one value, 24 base64 chars), computes accept_key() — SHA-1 over the client key concatenated with the fixed GUID 258EAFA5-E914-47DA-95CA-C5AB0DC85B11, then base64 — and replies 101 Switching Protocols. If the negotiation fails, reject() produces a proper HTTP error response instead of leaving a dead socket. Header parsing itself is defensively scoped in http11.py: at most 128 headers (roughly 1 MiB), lines capped at 8192 bytes, response bodies limited to 1 MiB since they exist only to carry error messages — all tunable through environment variables.

From a big-int XOR to NEON and SSE2

WebSocket’s signature performance tax is masking: every client-to-server frame is XORed with a 4-byte repeating key, mandated by RFC 6455 to make malicious browser payloads un-mimicable by cache-poisoning attacks. The pure-Python fallback in utils.py is genuinely clever: it converts the whole payload into one big integer, builds a mask-sized integer from the repeated 4-byte key, and XORs the two — turning a byte-by-byte loop into one C-level arithmetic operation over the entire message. When the optional C extension is available, frames.py imports apply_mask from speedups instead (with a plain try/except ImportError), and that is where the hardware shows up. The C function dispatches on architecture: on ARM it uses NEON intrinsics to XOR 16-byte blocks, on x86 it uses SSE2 _mm_loadu_si128/_mm_xor_si128 over unaligned 16-byte chunks, and only without SIMD does it fall back to 8-byte 64-bit XORs. setup.py builds this as the websockets.speedups extension, deliberately optional so a pure-Python wheel always works. The same evolution pattern appears in the API itself: src/websockets/legacy/ still carries the old callback-based WebSocketServerProtocol design, frozen in place, while everything new lands on the sans-I/O core — a clean marker of where the project’s history split.

One core, three runtimes: asyncio, sync, trio

The adapters are thin by construction. The asyncio Connection implements asyncio.Protocol, forwards data_received() into receive_data(), and — critically for production — starts a keepalive() task that sends a ping every ping_interval seconds (default 20) and closes the connection if no pong returns within ping_timeout (default 20). connect() handles the dial-up: TCP or TLS, HTTP proxy tunneling (opt-out with proxy=None, separate TLS options for the proxy hop), an open_timeout of 10 seconds around the whole handshake, and a reconnect-style pattern for resilient clients. On the server, serve() runs the opening handshake before invoking your handler, supports process_request hooks for health checks (returning non-None short-circuits the WebSocket upgrade — the FAQ’s health-check example relies on this), and routes multiple URL patterns through Router. The sync/ package mirrors the whole API for scripts and tests that don’t want an event loop — same recv/send/close methods, thread-per-connection servers — and trio/connection.py implements the same surface as a trio.abc.AsyncResource. Message framing into recv() versus recv_streaming() semantics happens in messages.py’s Assembler, and broadcast() fans a message out to many connections at once, deliberately without backpressure, skipping connections that are mid-close.

Honest Limits

The design buys generality at a price. The generator-based parser is the least obvious code in the project — parse() is stepped by next(), swaps itself for discard() mid-iteration on close, and hands errors to the caller through parser_exc rather than raising; you need three mental models (state machine, generator protocol, RFC choreography) to trace one frame. The legacy/ package is a second, older implementation kept alive for backwards compatibility, so many files exist twice with subtly different behavior — a real tax on contributors. Text vs. binary decoding of received messages happens at recv() time, not parse time, so a malformed UTF-8 frame can sit accepted until you try to read it. broadcast() has no backpressure by design, so a slow consumer’s write buffer grows until its keepalive timeout kills it — a footgun for million-connection fan-outs. And permessage-deflate negotiation, with its parameter factories and window-bit edge cases (window size 8 is unsupported because zlib cannot use fewer than 9 bits), is combinatorial logic that invites subtle interop bugs. None of these are bugs; all of them are trade-offs you can now see the seams of. For the matching HTTP-side machinery, see the source tours of FastAPI and Django, which ride on top of these same sockets.

Watch PyShine on YouTube

Contents