Introducing a new way to review your PRs.

Read the announcement

aio-libs / aiohttp

Asynchronous HTTP client/server framework for asyncio and Python

View on GitHub

19 documents · Updated Nov 23, 2026

docs / websocket-protocol-engine

WebSocket protocol engine

The WebSocket protocol engine turns an upgraded HTTP connection into a message channel. It validates the opening handshake, converts wire frames into typed messages, writes outbound frames, and coordinates buffering, compression, flow control, and close events for the higher-level WebSocket API. See WebSocket support for the wider feature and WebSocket endpoint lifecycles for connection setup and shutdown around this engine.

Handshake negotiation

The handshake negotiation accepts only a valid WebSocket upgrade and creates the protocol settings used by the reader and writer. It checks the upgrade request, supported protocol version, client key, optional sub-protocol, and permessage-deflate extension before returning the HTTP 101 response details. The server chooses the first client protocol that also appears in its configured protocol set. An unsupported extension is ignored on the server side rather than enabled. See aiohttp/web_ws.py.

The negotiated settings cross a clear boundary into the data path:

  • The selected sub-protocol becomes the connection's protocol value.
  • Compression settings select the deflate window and whether the compression context resets between messages.
  • The response's accept key proves that the server accepted this client handshake.
  • A successful upgrade disables HTTP keep-alive for the connection.

References: aiohttp/web_ws.py• L270-352 aiohttp/web_ws.py• L354-398 aiohttp/…/helpers.py• L67-148

Frame processing

Frame processing is a streaming pipeline that accepts arbitrary transport chunks and emits complete WebSocket messages. The reader keeps partial header, length, mask, and payload data until it has enough bytes to finish a frame. It then validates frame rules before it passes the frame to message assembly. The reader folds many small payload fragments into a bounded buffer so a large frame does not create an unbounded number of byte objects. aiohttp/…/reader_py.py provides the protocol behavior, while aiohttp/…/reader.py selects the available Python or optimized reader and aiohttp/_websocket/reader_c.pxd keeps the compiled reader's shared protocol state aligned with it.

The reader handles these wire-level concerns:

  • It reads short, extended-16-bit, and extended-64-bit payload lengths.
  • It accepts fragmented data messages only when continuation frames follow a non-final data frame; a new text or binary frame cannot start until the current message ends.
  • It permits control frames between message fragments without changing the data message state.
  • It rejects bad reserved bits, unknown opcodes, fragmented control frames, and oversized control payloads.
  • It enforces the configured message limit before it buffers a declared data payload.

This diagram shows how incoming bytes become queued messages or a protocol error.

flowchart LR
    A[Transport bytes] --> B[Frame header]
    B --> C[Payload length and mask]
    C --> D[Unmask payload]
    D --> E{Data or control}
    E -->|Data| F[Join fragments]
    F --> G[Decompress if negotiated]
    G --> H[Decode text or keep bytes]
    E -->|Ping, pong, or close| I[Validate control payload]
    H --> J[Message queue]
    I --> J
    B --> K[Protocol error]
    G --> K

References: aiohttp/…/reader_py.py• L190-249 aiohttp/…/reader_py.py• L251-404 aiohttp/…/reader_py.py• L405-634 aiohttp/…/reader_c.pxd• L71-132 aiohttp/…/reader.py• L1-31

Frame writing

Frame writing turns application payloads into valid WebSocket frames and sends them to the transport. The writer builds the frame header for the payload size, adds the reserved-bit marker when an extension is active, applies the client mask when required, and uses transport flow control to limit buffered output. aiohttp/…/writer.py keeps this work at the wire boundary so the public WebSocket response can expose text, bytes, JSON, ping, pong, and close operations without repeating frame rules.

The writer preserves message order when concurrent sends share a compression context. Small compressed sends run under a send lock. Large compressed sends keep the lock, compression, and transport write inside a cancellation shield so a cancelled task cannot advance the compressor without sending its result. Control frames bypass compression because WebSocket control frames are never compressed.

References: aiohttp/…/writer.py• L25-46 aiohttp/…/writer.py• L48-121 aiohttp/…/writer.py• L123-179 aiohttp/…/writer.py• L190-250 aiohttp/web_ws.py• L443-499

Masking

Masking protects client-to-server frame payloads as required by the WebSocket protocol. A four-byte key is XORed across the payload, and the same operation reverses the mask on the receiving side. The writer uses masking for client frames, while the reader accepts and removes a mask when one is present. The shared helper uses an optimized implementation when available and a pure-Python path otherwise. See aiohttp/…/helpers.py and aiohttp/…/reader_py.py.

Masking is separate from compression. The sender compresses the payload first, then frames and masks the resulting bytes. The receiver removes the mask before it joins fragments or decompresses the message.

References: aiohttp/…/helpers.py• L25-65 aiohttp/…/helpers.py• L12-20 aiohttp/…/reader_py.py• L562-628 aiohttp/…/writer.py• L131-179

Compression negotiation

Compression reduces message payload size when both peers negotiate permessage-deflate. The handshake parser accepts supported window sizes and context-takeover settings. The reader restores the deflate stream after it assembles a complete message, while the writer flushes each compressed message and removes the protocol's trailing deflate marker before it writes the frame. See aiohttp/…/helpers.py, aiohttp/…/reader_py.py, and aiohttp/…/writer.py.

The compression path protects two limits. It rejects a decompressed message that exceeds the configured size, and it rejects a compressed input with too many concatenated deflate members. Control frames do not touch the compression state, so a ping or pong can interrupt a fragmented compressed message without changing its result.

References: aiohttp/…/helpers.py• L67-148 aiohttp/…/reader_py.py• L295-334 aiohttp/…/reader_py.py• L484-505 aiohttp/…/writer.py• L181-257 aiohttp/compression_utils.py• L221-285 aiohttp/compression_utils.py• L288-360

Message models

Message models give the public API one typed result for each protocol event. Text messages contain decoded text by default or raw bytes when text decoding is disabled. Binary messages contain bytes. Ping, pong, close, closing, closed, and error messages carry the control or connection state needed by the receive layer. See aiohttp/…/models.py.

Each message records its type and payload size. Close messages also expose the close code and reason. Text and binary models provide a JSON helper, which lets callers parse message data without changing the wire-level reader.

Message kindMeaning to the receive layer
Text or binaryA complete application data message
Ping or pongA control event that may be handled automatically
CloseA peer close request with a code and reason
Closing or closedA local connection state marker
ErrorA protocol, transport, or heartbeat failure

References: aiohttp/…/models.py• L11-39 aiohttp/…/models.py• L42-127 aiohttp/…/models.py• L130-167

Message queue and flow control

The message queue separates transport parsing from application reads. The reader places complete messages in WebSocketDataQueue, and a caller waits on the queue through the WebSocket response. The queue tracks each message with a small size allowance and applies high- and low-water marks. When parsing reaches the high mark with unread input left, it keeps that input as a parser tail and stalls until the queue reaches the low mark. A read that ends exactly at a frame boundary does not create an empty stalled state. This keeps backpressure across both queued messages and input that has not yet become a message.

The stalled parser is held by a weak reference from the queue. The connection owner must keep the reader alive while it is registered, or the queue reports a runtime error after it drains the messages that it already holds. When the low-water mark is reached, the queue nudges the reader to process its saved tail before it resumes transport reads. The transport resumes only when no parser tail remains, which prevents new reads from moving the memory bound from the queue into the tail.

The queue also carries end-of-file and parser exceptions. This gives a waiting reader a defined result when the connection ends or frame validation fails instead of leaving the receive operation blocked.

References: aiohttp/…/reader_py.py• L81-187 aiohttp/…/reader_py.py• L405-422 aiohttp/base_protocol.py• L19-29 aiohttp/base_protocol.py• L66-105 aiohttp/base_protocol.py• L131-140 aiohttp/web_ws.py• L386-396

Close-state handling

Close-state handling coordinates the WebSocket close handshake with reads, writes, and transport shutdown. A peer close becomes a CLOSE message. The receive layer records its code, marks the connection as closing, and can send the matching close frame automatically. A local close sends its close frame, waits for the peer close when possible, and then closes the transport. See aiohttp/web_ws.py and aiohttp/…/writer.py.

The states have distinct meanings:

  • Open: application messages and control frames can use the writer.
  • Closing: the close exchange is in progress. New non-close writes are rejected, and receive can return a closing marker.
  • Closed: the transport is no longer usable. Repeated receive calls return a closed marker for a limited number of accesses before raising an error.
  • Error: a protocol or transport failure records an exception and closes or marks the connection as abnormal.

This diagram shows the main close paths and the point where the transport becomes unusable.

stateDiagram-v2
    [*] --> Open
    Open --> Closing: peer CLOSE or local close
    Open --> Closed: EOF or fatal transport failure
    Closing --> Closed: close exchange or timeout
    Closing --> Closed: transport close
    Open --> Error: frame or heartbeat error
    Error --> Closed: abnormal transport close

The receive loop handles protocol errors by storing the WebSocket close code, attempting a close with that code, and returning an error message. Heartbeat failure marks an abnormal closure and wakes a waiting receive operation with the error. A close while another task is waiting to receive uses a closing marker to break that wait before the close task completes.

References: aiohttp/web_ws.py• L240-256 aiohttp/web_ws.py• L510-579 aiohttp/web_ws.py• L596-669 aiohttp/web_ws.py• L768-774 aiohttp/…/writer.py• L74-79 aiohttp/…/writer.py• L260-269

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the handshake extension result aligned with the reader's reserved-bit checks and the writer's compression mode.
  • Keep message-size checks aligned across declared frame lengths, assembled fragments, and decompressed output.
  • Preserve the queue's high- and low-water contract when changing message sizes, parser tails, or payload-fragment folding.
  • Preserve the close marker and exception paths when changing receive() or local close behavior.
  • Keep client masking and server non-masking behavior aligned with the role that creates each writer.
  • Keep compressed send serialization cancellation-safe when changing compressor or executor behavior.
  • Keep the compiled reader declarations aligned with the Python reader state and message contract.

Important failure modes

TriggerConsequenceGuard
Missing or invalid upgrade, version, or client keyThe handshake returns an HTTP bad-request responseValidate all opening handshake fields before creating the writer
Reserved bit or opcode is not allowed by the negotiated extensionsThe reader raises a protocol error and the receive layer starts an error closeKeep frame validation tied to negotiated compression
Fragment sequence starts with continuation or uses a new data opcode mid-messageThe message is rejected with a protocol errorTrack the active data opcode until its final continuation
Declared or decompressed data exceeds the message limitThe connection reports MESSAGE_TOO_BIG instead of buffering the full messageCheck size before payload buffering and after decompression
Concurrent compressed sends are cancelled during compressionCompressor state and later frames can become corruptedKeep the lock, compression, and write inside the shielded operation
A queued message batch exceeds the read limit while input remains unparsedResuming transport reads too early can move the memory bound from the queue into the parser tailStall parsing at the high-water mark and resume transport only after the tail is gone and the queue has headroom
A stalled reader is garbage collected before the queue drainsQueued messages can remain readable, but later reads surface a runtime error instead of resuming parsingKeep a strong reference to the reader while it is registered with the parser
Peer close, EOF, timeout, or heartbeat failure occurs during closeThe connection can end with an abnormal close codeRecord the close state and close the transport on timeout or failure

Key files

FileWhy to read it
aiohttp/web_ws.pyConnects handshake negotiation, reader and writer setup, message receive behavior, flow control, and close state
aiohttp/…/reader_py.pyDefines the streaming frame parser, fragmentation rules, message conversion, and queue behavior
aiohttp/_websocket/reader_c.pxdDefines the shared state contract for the compiled reader and its queue
aiohttp/…/writer.pyDefines frame construction, masking, compression serialization, output flow control, and close-frame writes
aiohttp/…/models.pyDefines the message types and close codes exposed across the WebSocket boundary
aiohttp/…/helpers.pyDefines masking and permessage-deflate negotiation rules
aiohttp/…/reader.pySelects the Python or optimized reader and queue implementation
aiohttp/compression_utils.pyDefines the shared deflate compression and decompression behavior used by WebSockets
aiohttp/base_protocol.pyProvides the transport read-pause and write-drain controls used by the queue and writer