Architecture Overview
Relevant source files
The following files were used as context for generating this wiki page:
Uvicorn is a high-performance ASGI (Asynchronous Server Gateway Interface) web server implementation for Python. It acts as a bridge between low-level network sockets and high-level Python web applications or frameworks, supporting HTTP/1.1 and WebSocket protocols.
The architecture is designed to be modular, allowing for different loop implementations (asyncio, uvloop) and protocol parsers (httptools, h11). It manages the lifecycle of connections, request-response cycles, and application lifespans while providing robustness through concurrency limits and graceful shutdown mechanisms.
Sources: README.md:1-25, uvicorn/config.py:32-60
Core Components
The system is composed of several layers that handle configuration, process management, protocol parsing, and application execution.
Configuration and Entry Point
The Config class is the central authority for server settings, handling everything from socket binding to protocol selection. The main.py file provides the CLI interface and the run() function, which initializes the server based on the provided configuration.
Sources: uvicorn/config.py:165-430, uvicorn/main.py:440-540
Protocol Implementations
Uvicorn provides multiple implementations for HTTP and WebSocket protocols. These implementations are responsible for translating raw bytes from the network into ASGI events.
- HTTP Protocols: Supports
httptools(fast C-based parser) andh11(pure Python parser). - WebSocket Protocols: Supports
websockets,websockets-sansio, andwsproto. - WSGI Middleware: A legacy wrapper allowing WSGI applications to run within the ASGI environment.
Sources: uvicorn/config.py:44-55, uvicorn/protocols/http/httptools_impl.py:41-80, uvicorn/middleware/wsgi.py:76-90
Request-Response Cycle
For every HTTP request, a RequestResponseCycle object is created. This object manages the state of a single request, handles the ASGI send and receive calls, and ensures the response is correctly formatted and sent back to the transport layer.
Sources: uvicorn/protocols/http/httptools_impl.py:276-320, uvicorn/protocols/http/h11_impl.py:257-296
Data Flow Architecture
The following diagram illustrates the flow of a request from the network through Uvicorn's layers to the ASGI application.
The flow starts with raw bytes at the Transport layer, which are passed to a specific Protocol implementation for parsing. A RequestResponseCycle is then spawned to manage the interaction with the ASGI application.
Sources: uvicorn/protocols/http/httptools_impl.py:145-250, uvicorn/protocols/http/h11_impl.py:126-230
Protocol Interaction and ASGI Mapping
Uvicorn maps low-level protocol events to standard ASGI scopes and messages.
HTTP Mapping
| Protocol Element | ASGI Scope/Message Mapping | File Reference |
|---|---|---|
| Request Line | method, path, query_string, http_version | httptools_impl.py:207-220 |
| Headers | headers (list of byte tuples) | _types.py:75-88 |
| Request Body | http.request event | _types.py:120-124 |
| Response Start | http.response.start event | _types.py:133-138 |
| Response Body | http.response.body event | _types.py:141-145 |
Sources: uvicorn/protocols/http/httptools_impl.py:205-240, uvicorn/_types.py:75-145
WebSocket Lifecycle
The WebSocket implementation involves an initial HTTP upgrade followed by persistent frame-based communication.
The sequence shows the transition from a standard HTTP request to a persistent WebSocket connection, managed by the WebSocketsSansIOProtocol.
Sources: uvicorn/protocols/websockets/websockets_sansio_impl.py:133-210, uvicorn/protocols/websockets/websockets_sansio_impl.py:345-400
Server State and Concurrency Management
The ServerState object (often referenced as server_state in protocols) maintains global counters and sets to manage resources.
- Connections: A set of active protocol instances. This is used for graceful shutdowns.
- Tasks: A set of running ASGI tasks.
- Total Requests: A counter for all processed requests.
- Concurrency Limits: Managed via
limit_concurrencyin theConfig. When the sum of connections or tasks exceeds this limit, the server issues 503 "Service Unavailable" responses.
Sources: uvicorn/protocols/http/httptools_impl.py:73-80, uvicorn/protocols/http/httptools_impl.py:223-230, uvicorn/config.py:236-245
WSGI Support Architecture
While Uvicorn is primarily an ASGI server, it includes a WSGIMiddleware to support legacy WSGI applications. This middleware executes the WSGI application in a ThreadPoolExecutor to avoid blocking the asynchronous event loop.
This diagram shows how the WSGIResponder bridges the async ASGI interface with the synchronous WSGI application running in a separate thread.
Sources: uvicorn/middleware/wsgi.py:18-70, uvicorn/middleware/wsgi.py:110-160
Configuration Options Summary
The Config class handles a wide range of parameters. Below are key categories:
| Category | Key Parameters | Default | Description |
|---|---|---|---|
| Network | host, port, uds, fd | 127.0.0.1:8000 | Binding options for the server socket. |
| Protocols | http, ws, interface | auto | Selection of parser implementations. |
| Timeouts | timeout_keep_alive, timeout_notify | 5, 30 | Management of idle connections and worker health. |
| Security | ssl_keyfile, ssl_certfile, proxy_headers | None, True | SSL configuration and proxy trust settings. |
| Limits | limit_concurrency, ws_max_size | None, 16MB | Resource usage constraints. |
Sources: uvicorn/config.py:165-280, uvicorn/main.py:40-200
Conclusion
The architecture of Uvicorn provides a flexible and high-performance foundation for running asynchronous web services in Python. By decoupling the parser implementation from the ASGI logic and providing a robust lifecycle management system, it ensures that applications can scale and handle various network conditions efficiently. The inclusion of WSGI support and multiple protocol parsers makes it a versatile tool in the Python web ecosystem.
Sources: README.md:1-25, uvicorn/config.py:440-500