Server Implementation
Relevant source files
The following files were used as context for generating this wiki page:
Uvicorn is a lightning-fast ASGI server implementation for Python, designed to handle asynchronous web applications. It serves as the bridge between low-level network sockets and high-level application code, supporting HTTP/1.1 and WebSocket protocols. The server implementation is built around a pluggable architecture that allows for different loop, HTTP, and WebSocket implementations depending on available dependencies.
The core of the server's lifecycle is managed by the Server class, which handles socket binding, the event loop execution, and graceful shutdown. It coordinates with protocol handlers to manage individual connections and uses a ServerState object to track shared data across the server instance.
Sources: README.md:1-20, uvicorn/main.py:445-480, uvicorn/server.py
Core Architecture and Lifecycle
The Uvicorn server operates by loading a configuration, binding to a network interface (host/port, UNIX socket, or file descriptor), and entering an asynchronous event loop. It supports multiple worker processes or an auto-reload mechanism for development.
Server Startup and Execution
When server.run() is called, the server initializes the environment and begins listening for connections. If multiple workers or reload mode are enabled, Uvicorn utilizes supervisors (Multiprocess or ChangeReload) to manage the underlying server instances.
Sources: uvicorn/main.py:455-475, uvicorn/server.py
Shared Server State
The ServerState class maintains global information shared across all connections in a single server process.
| Field | Description |
|---|---|
total_requests | Total number of HTTP requests processed by the server instance. |
connections | A set of active protocol instances currently connected. |
tasks | A set of active ASGI tasks being managed by the server. |
default_headers | Pre-calculated server headers (e.g., "Server", "Date"). |
Sources: uvicorn/protocols/http/httptools_impl.py:84-86, uvicorn/protocols/http/h11_impl.py:76-78
Protocol Implementations
Uvicorn abstracts protocol handling through classes that implement asyncio.Protocol. This allows the server to swap between high-performance C-based implementations (like httptools) and pure-Python fallbacks (like h11).
HTTP Protocols
Uvicorn provides two primary HTTP implementations:
- HttpToolsProtocol: Uses the
httptoolslibrary, a Python binding for the nodejs HTTP parser. It is preferred for performance. - H11Protocol: Uses the
h11library, a pure-Python, robust HTTP/1.1 implementation.
Both implementations manage a RequestResponseCycle which handles the ASGI send and receive interfaces for a single request.
WebSocket Protocols
Uvicorn supports WebSocket upgrades from HTTP connections. It manages the handshake and provides an ASGI-compatible interface for bi-directional communication.
- WebSocketProtocol: Built on the
websocketslibrary. - WebSocketsSansIOProtocol: A "sans-io" implementation for improved flexibility.
Sources: uvicorn/protocols/websockets/websockets_impl.py:45-120, uvicorn/protocols/websockets/websockets_sansio_impl.py:42-150
ASGI and WSGI Support
While Uvicorn is natively an ASGI server, it includes a middleware to support legacy WSGI applications.
WSGI Compatibility
The WSGIMiddleware converts ASGI scopes into WSGI environments and executes the WSGI application within a ThreadPoolExecutor to avoid blocking the asynchronous event loop.
| Component | Functionality |
|---|---|
build_environ | Maps ASGI scope keys to standard WSGI environ keys (e.g., PATH_INFO, REQUEST_METHOD). |
WSGIResponder | Handles the lifecycle of a WSGI request, managing the input stream and response queue. |
WSGIMiddleware | The entry point that wraps the WSGI application for the server. |
Sources: uvicorn/middleware/wsgi.py:27-140
# Mapping logic in build_environ
environ = {
"REQUEST_METHOD": scope["method"],
"SCRIPT_NAME": script_name,
"PATH_INFO": path_info,
"QUERY_STRING": scope["query_string"].decode("ascii"),
"SERVER_PROTOCOL": "HTTP/%s" % scope["http_version"],
"wsgi.input": body,
"wsgi.multithread": True,
}
Sources: uvicorn/middleware/wsgi.py:33-45
Configuration and CLI
The server is highly configurable via the Config class, which can be populated through the Command Line Interface (CLI) defined in uvicorn.main.
Key Configuration Options
| Option | Default | Description |
|---|---|---|
host | 127.0.0.1 | Bind socket to this host. |
port | 8000 | Bind socket to this port. |
loop | auto | Event loop implementation (uvloop, asyncio). |
http | auto | HTTP protocol (httptools, h11). |
ws | auto | WebSocket protocol (websockets, wsproto). |
limit_concurrency | None | Max concurrent connections before 503 responses. |
timeout_keep_alive | 5 | Seconds to wait for new data on Keep-Alive connections. |
Sources: uvicorn/main.py:65-275
Graceful Shutdown
The server implements a graceful shutdown procedure to ensure that active requests are completed before the process terminates.
- The server stops accepting new connections.
- It sends shutdown signals to all active protocol instances.
- HTTP protocols transition to
keep_alive = Falseto close after the current request. - WebSockets send a close frame (status code 1012).
- The server waits for the
timeout_graceful_shutdownperiod before forcing closure.
Sources: uvicorn/protocols/http/httptools_impl.py:255-263, uvicorn/protocols/websockets/websockets_sansio_impl.py:108-118, uvicorn/main.py:230-235
Conclusion
Uvicorn's server implementation is a modular system that prioritizes performance and standards compliance. By decoupling protocol parsing (via httptools/h11) from the application interface (ASGI), it provides a flexible foundation for modern Python web development while maintaining backward compatibility for WSGI through specialized middleware.