HTTP Protocol Implementations
Relevant source files
The following files were used as context for generating this wiki page:
Uvicorn provides high-performance HTTP/1.1 protocol implementations designed to interface between low-level network transports and ASGI-compliant applications. The system supports two primary backends: a Cython-based implementation using httptools for maximum performance and a pure-Python implementation using h11 for robustness and portability.
These implementations manage the full lifecycle of an HTTP request, including parsing byte streams, managing connection state (such as Keep-Alive), handling flow control, and executing the ASGI application via a RequestResponseCycle.
Sources: uvicorn/protocols/http/httptools_impl.py:44-48, uvicorn/protocols/http/h11_impl.py:43-47, README.md
Protocol Architecture
Uvicorn utilizes a class-based protocol architecture where each implementation inherits from asyncio.Protocol. The core responsibility of these classes is to translate network events (data received, connection lost) into ASGI scope and events.
Implementation Variants
| Implementation | Backend Library | Description |
|---|---|---|
HttpToolsProtocol | httptools | Cython-based parser. Fastest performance, used in uvicorn[standard]. |
H11Protocol | h11 | Pure-Python Sans-IO implementation. Highly compliant and robust. |
Sources: uvicorn/protocols/http/httptools_impl.py:44, uvicorn/protocols/http/h11_impl.py:43, pyproject.toml:47-50
Request Lifecycle Flow
The following diagram illustrates the typical data flow from a transport receiving bytes to the ASGI application returning a response.
This diagram shows the internal transition from byte parsing to ASGI task execution.
Sources: uvicorn/protocols/http/httptools_impl.py:143-200, uvicorn/protocols/http/h11_impl.py:133-170
RequestResponseCycle
The RequestResponseCycle is a per-request state machine that manages the interaction between the protocol and the ASGI application. It implements the ASGI send and receive callables.
Core Logic
- ASGI Receive: The cycle provides
http.requestevents to the app. If the body is large, it utilizesFlowControlto pause/resume the transport reading based onHIGH_WATER_LIMIT(65,536 bytes). - ASGI Send: The app sends
http.response.start(to set status and headers) followed byhttp.response.body. - Validation: It enforces protocol constraints, such as ensuring headers aren't sent twice and that
Content-Lengthmatches the actual body size.
Sources: uvicorn/protocols/http/httptools_impl.py:284-315, uvicorn/protocols/http/httptools_impl.py:400-480
Connection Management
| Feature | Description |
|---|---|
| Keep-Alive | Controlled via timeout_keep_alive. If idle, the protocol schedules a timeout_keep_alive_handler to close the connection. |
| Pipelining | HttpToolsProtocol maintains a pipeline deque to queue requests received before the previous response has finished. |
| Upgrades | Detects Upgrade: websocket headers. If a WebSocket protocol is configured, it handovers the transport to a WSProtocol instance. |
Sources: uvicorn/protocols/http/httptools_impl.py:126-135, uvicorn/protocols/http/httptools_impl.py:235-245, uvicorn/protocols/http/h11_impl.py:113-125
ASGI Scope Generation
When headers are parsed, the protocol generates an HTTPScope dictionary.
# Based on uvicorn/protocols/http/httptools_impl.py:207-224
self.scope = {
"type": "http",
"asgi": {"version": self.config.asgi_version, "spec_version": "2.3"},
"http_version": "1.1",
"server": self.server,
"client": self.client,
"scheme": self.scheme,
"method": method.decode("ascii"),
"root_path": self.root_path,
"path": full_path,
"raw_path": full_raw_path,
"query_string": parsed_url.query or b"",
"headers": self.headers,
"state": self.app_state.copy(),
}
Sources: uvicorn/protocols/http/httptools_impl.py:207-224, uvicorn/_types.py:73-88
Flow Control
Uvicorn implements backpressure using a FlowControl helper. This ensures that the server does not overwhelm the application with body data if the app is slow to process, and similarly handles slow network clients during response sending.
Sequence of flow control during a POST request with a large body.
Sources: uvicorn/protocols/http/httptools_impl.py:266-270, uvicorn/protocols/http/h11_impl.py:180-184
WSGI Compatibility
Uvicorn includes a WSGIMiddleware and WSGIResponder to allow legacy synchronous applications to run on the async HTTP protocols.
- Execution: The responder uses a
ThreadPoolExecutorto run the WSGI callable without blocking the event loop. - Environ Building: It translates the ASGI
HTTPScopeinto a standard WSGIenvirondictionary, including headers,PATH_INFO, andSCRIPT_NAME. - Streaming: WSGI response iterables are consumed in the thread pool and pushed into an async queue for the protocol to send.
Sources: uvicorn/middleware/wsgi.py:30-100, uvicorn/middleware/wsgi.py:115-130
Protocol Error Handling
Both implementations handle malformed requests by returning immediate 400 responses.
- Validation: Uvicorn checks for invalid characters in header names (using
HEADER_RE) and values (usingHEADER_VALUE_RE) to prevent header injection or smuggling. - App Exceptions: If the ASGI application raises an unhandled exception before the response has started, the cycle sends a
500 Internal Server Error. If it fails mid-response, the connection is simply closed.
Sources: uvicorn/protocols/http/httptools_impl.py:44-45, uvicorn/protocols/http/httptools_impl.py:370-385, tests/protocols/test_http.py:430-450
Summary
Uvicorn's HTTP protocol implementations provide a high-performance bridge to ASGI applications. By supporting multiple backends (httptools and h11), it balances raw speed with broad compatibility. The use of a decoupled RequestResponseCycle and robust FlowControl ensures that Uvicorn can handle complex scenarios like request pipelining, body streaming, and protocol upgrades while maintaining stability under high load.