WebSockets Implementations
Relevant source files
The following files were used as context for generating this wiki page:
Uvicorn provides multiple WebSocket protocol implementations to handle full-duplex communication over a single TCP connection within the ASGI ecosystem. These implementations manage the initial HTTP upgrade handshake, state transitions, keepalive mechanisms (pings/pongs), and data frame fragmentation/reassembly for both text and binary payloads.
The project supports different backends for WebSocket processing, primarily relying on the websockets library (standard and sans-io versions) and wsproto. These protocols are integrated into Uvicorn's asynchronous loop, allowing them to bridge low-level network events to high-level ASGI application events like websocket.connect, websocket.receive, and websocket.disconnect.
Sources: uvicorn/protocols/websockets/websockets_impl.py, uvicorn/protocols/websockets/wsproto_impl.py, README.md:50-60
Architecture and Protocol Selection
Uvicorn transitions from HTTP to WebSocket when an Upgrade: websocket header is detected in an incoming HTTP/1.1 request. The specific WebSocket protocol class is determined by the server configuration, typically defaulting to a "standard" implementation if the necessary dependencies are installed.
Handshake and Upgrade Flow
The transition starts in the HTTP protocol layer (HttpToolsProtocol or H11Protocol). When a valid upgrade request is parsed, the HTTP protocol discards itself from the connection pool and hands over the underlying transport to the selected WebSocket protocol implementation.
The flow ensures that the network transport is preserved while the protocol state machine switches from request-response to a persistent WebSocket connection.
Sources: uvicorn/protocols/http/httptools_impl.py:126-146, uvicorn/protocols/http/h11_impl.py:175-190
Core WebSocket Implementations
Uvicorn features three primary implementation strategies for WebSockets.
| Implementation | Base Class / Library | Characteristics |
|---|---|---|
WebSocketProtocol | websockets.server.WebSocketServerProtocol | Legacy implementation using the websockets library's built-in protocol handling. |
WebSocketsSansIOProtocol | websockets.server.ServerProtocol | Modern implementation using the Sans-IO (synchronous parser) version of websockets. |
WSProtocol | wsproto.WSConnection | Implementation using the wsproto library, focusing on a pure state-machine approach. |
Sources: uvicorn/protocols/websockets/websockets_impl.py:46, uvicorn/protocols/websockets/websockets_sansio_impl.py:40, uvicorn/protocols/websockets/wsproto_impl.py:61
WebSockets Sans-IO Implementation
The WebSocketsSansIOProtocol manages state by feeding raw bytes into the ServerProtocol parser and handling generated events. It accumulates fragmented frames into a bytearray and only dispatches to the ASGI application when the fin bit is detected.
Keepalive and Connection Health
To prevent connection timeouts by intermediaries and detect dead peers, Uvicorn implements a keepalive mechanism using WebSocket Ping and Pong frames.
Ping/Pong Logic
The server schedules pings based on the ws_ping_interval. If a ws_ping_timeout is configured, the server sets a timer after sending a ping. If a matching pong is not received within that window, the connection is failed with code 1011 (internal error).
Key components in WSProtocol and WebSocketsSansIOProtocol:
pending_ping_payload: A random 4-byte identifier to match pongs to pings.last_ping_rtt: Used to adjust the next ping schedule.keepalive_timeout(): Triggered when a pong is overdue.
Sources: uvicorn/protocols/websockets/wsproto_impl.py:217-251, uvicorn/protocols/websockets/websockets_sansio_impl.py:215-255
Data Buffering and Limits
WebSockets handle large messages through fragmentation. Uvicorn manages this by buffering incoming fragments until a message is complete.
Message Reassembly
In the wsproto implementation, a WebsocketBuffer class wraps BytesIO or StringIO. It enforces the ws_max_size limit during accumulation to prevent memory exhaustion attacks.
# uvicorn/protocols/websockets/wsproto_impl.py:34-45
def extend(self, event: events.TextMessage | events.BytesMessage) -> None:
if self.value is None:
self.value = StringIO() if isinstance(event, events.TextMessage) else BytesIO()
self.value.write(event.data)
# Count UTF-8 bytes for text or raw bytes for binary
self.length += len(event.data.encode()) if isinstance(event, events.TextMessage) else len(event.data)
if self.length > self.max_length:
raise FrameTooLargeError
If the accumulated size exceeds ws_max_size, the server sends a close frame with code 1009 (Message Too Big) and terminates the transport.
Sources: uvicorn/protocols/websockets/wsproto_impl.py:30-58, tests/protocols/test_websocket.py:532-550
ASGI Event Mapping
The protocols map internal library events to the ASGI 2.4 specification.
| ASGI Message Type | Direction | Implementation Action |
|---|---|---|
websocket.connect | Server -> App | Sent when the handshake request is received. |
websocket.accept | App -> Server | Triggers the handshake response (HTTP 101). |
websocket.receive | Server -> App | Dispatched when a full Text/Binary message is reassembled. |
websocket.send | App -> Server | Encodes and sends a data frame to the client. |
websocket.close | App -> Server | Sends a Close frame and shuts down the transport. |
websocket.disconnect | Server -> App | Sent when the transport is lost or a Close frame is received. |
Sources: uvicorn/protocols/websockets/websockets_sansio_impl.py:276-350, uvicorn/protocols/websockets/websockets_impl.py:230-280
Conclusion
Uvicorn's WebSocket implementations provide a robust bridge between low-level asynchronous socket handling and the ASGI application interface. By supporting multiple backends like websockets and wsproto, Uvicorn ensures compatibility and performance across different environment configurations while strictly adhering to the ASGI specification for message flow, keepalives, and error handling.