TCP Flow Control
Relevant source files
The following files were used as context for generating this wiki page:
TCP Flow Control in Uvicorn is a mechanism designed to manage the rate of data transmission between the server and the client to prevent buffer overflows and ensure system stability. It operates by monitoring the state of the underlying asyncio.Transport and coordinating with ASGI application events to pause and resume reading/writing as necessary.
The system primarily handles two scenarios: backpressure from the application when it cannot consume request bodies fast enough (read flow control), and backpressure from the network when the client cannot receive response data fast enough (write flow control).
Architecture and Components
The flow control logic is encapsulated within specific protocol implementations and a dedicated FlowControl class.
FlowControl Class
The FlowControl class manages the writability state of the transport. It uses an asyncio.Event to block or release the execution of ASGI send() calls based on the transport's buffer levels.
Sources: uvicorn/protocols/http/httptools_impl.py:83, uvicorn/protocols/http/h11_impl.py:75
High Water Mark Logic
Uvicorn uses a "High Water Mark" threshold to trigger flow control. When an incoming request body exceeds the HIGH_WATER_LIMIT (defined in flow_control.py), the protocol instructs the transport to stop reading from the socket.
Sources: uvicorn/protocols/http/httptools_impl.py:270-272, uvicorn/protocols/http/h11_impl.py:176-178
| Component | Description |
|---|---|
HIGH_WATER_LIMIT | The threshold (typically 65536 bytes) at which the server pauses reading to prevent memory exhaustion. |
FlowControl.pause_writing() | Callback triggered by asyncio when the transport's write buffer exceeds its high water mark. |
FlowControl.resume_writing() | Callback triggered by asyncio when the transport's write buffer drops below its low water mark. |
FlowControl.drain() | An awaitable method that blocks until the transport is writable again. |
Sources: uvicorn/protocols/http/httptools_impl.py:34-40, uvicorn/protocols/http/h11_impl.py:36-40
Data Flow and Logic
The following diagram illustrates the interaction between the network transport, the Uvicorn protocol implementation, and the ASGI application during a read-heavy operation.
The diagram shows how the buffer size triggers the pausing and resuming of the socket reading via the Transport interface.
Write Flow Control
When an ASGI application calls send(), the RequestResponseCycle checks the status of the FlowControl object. If the transport has signaled that its buffer is full (write_paused is True), the send() call will await flow.drain().
# From RequestResponseCycle.send in httptools_impl.py
async def send(self, message: ASGISendEvent) -> None:
if self.flow.write_paused and not self.disconnected:
await self.flow.drain()
Sources: uvicorn/protocols/http/httptools_impl.py:465-467, uvicorn/protocols/http/h11_impl.py:291-293
Read Flow Control (Backpressure)
Read flow control is managed during on_body (in httptools) or handle_events (in h11). If the accumulated body in the current cycle exceeds the limit, the transport is paused. It is only resumed when the ASGI application calls receive(), which consumes the data and clears the internal buffer.
Protocol Specific Implementation
WebSocket Flow Control
WebSocket implementations (wsproto and websockets_sansio) use a similar pattern but rely on an asyncio.Event named writable.
- Pause:
pause_writingclears the event. - Resume:
resume_writingsets the event. - Application Send: The
sendmethod awaitsself.writable.wait().
Sources: uvicorn/protocols/websockets/wsproto_impl.py:165-175, uvicorn/protocols/websockets/websockets_sansio_impl.py:117-124
Concurrency Limits
TCP Flow Control is also impacted by global concurrency settings. If limit_concurrency is reached, Uvicorn protocols will immediately return a "503 Service Unavailable" response and close the connection rather than allowing more data to flow.
Sources: uvicorn/protocols/http/httptools_impl.py:214-220, tests/protocols/test_http.py:734-754
Summary
TCP Flow Control in Uvicorn ensures that neither the server's memory nor the client's network buffer is overwhelmed. By utilizing the HIGH_WATER_LIMIT for reads and the FlowControl.drain() mechanism for writes, Uvicorn provides a robust implementation of backpressure that complies with the ASGI specification while maintaining high performance.