Introduction to Uvicorn
Relevant source files
The following files were used as context for generating this wiki page:
Uvicorn is a lightning-fast ASGI (Asynchronous Server Gateway Interface) web server implementation for Python. It is designed to provide a minimal, low-level interface between asynchronous web frameworks and the server, supporting HTTP/1.1 and WebSockets. By leveraging an asynchronous concurrency model, Uvicorn allows for long-lived connections, lightweight background tasks, and efficient handling of network I/O bound endpoints.
Sources: README.md:1-26, README.md:58-66
Core Architecture and Components
Uvicorn's architecture is built around a centralized Server class that manages the lifecycle of the application, and a Config class that handles environment and execution settings. It utilizes pluggable protocol implementations for both HTTP and WebSockets.
High-Level Component Relationship
The following diagram illustrates how the CLI or programmatic entry point initializes the configuration and starts the server instance.
Key Classes
| Class | Description | Source |
|---|---|---|
Config | Manages server settings, including host, port, SSL context, and protocol choices. | uvicorn/config.py:155 |
Server | Handles the socket binding, event loop management, and graceful shutdown logic. | uvicorn/server.py:47 |
ServerState | Stores shared state across protocol instances, such as connection counts and tasks. | uvicorn/server.py:36 |
HttpToolsProtocol | High-performance HTTP/1.1 implementation using the httptools C-parser. | uvicorn/protocols/http/httptools_impl.py:34 |
H11Protocol | Pure-Python HTTP/1.1 implementation using the h11 library. | uvicorn/protocols/http/h11_impl.py:36 |
Execution Flow
When Uvicorn starts, it follows a structured sequence: loading the application, binding sockets, and initiating the lifespan protocol before entering the main event loop.
Server Startup Sequence
Request Handling Logic
For every incoming connection, the server instantiates a protocol handler (e.g., HttpToolsProtocol). This handler parses the raw data into an ASGI scope and manages the RequestResponseCycle.
- Data Reception: Raw bytes are fed into the parser.
- Scope Creation: A dictionary containing request metadata (method, path, headers) is generated.
- Task Dispatch: An asynchronous task is created to run the ASGI application.
- Response Cycle: The application sends events back to the server (e.g.,
http.response.start), which the protocol translates into raw HTTP bytes.
Sources: uvicorn/protocols/http/httptools_impl.py:118-170, uvicorn/protocols/http/httptools_impl.py:284-350
Protocol Implementations
Uvicorn supports multiple protocol implementations which can be selected via the --http and --ws flags or determined automatically.
HTTP Protocols
- httptools: Faster implementation using a C-based parser. Requires
uvicorn[standard]. - h11: A robust, pure-Python implementation used as a fallback.
WebSocket Protocols
- websockets: High-performance implementation using the
websocketslibrary. - websockets-sansio: A "Sans-IO" implementation for modern async usage.
- wsproto: An alternative implementation using
wsproto.
Sources: uvicorn/config.py:36-50, README.md:28-40
Middleware and Extensions
Uvicorn includes built-in middleware to handle legacy interfaces and proxy environments:
- WSGIMiddleware: Allows running synchronous WSGI applications within the asynchronous Uvicorn environment. It uses a
ThreadPoolExecutorto handle the blocking WSGI callable. - ProxyHeadersMiddleware: Populates the ASGI scope's client and scheme information using
X-Forwarded-ForandX-Forwarded-Protoheaders from trusted proxies.
Sources: uvicorn/middleware/wsgi.py:75-103, uvicorn/config.py:339-342
WSGI to ASGI Translation Flow
Sources: uvicorn/middleware/wsgi.py:106-150
Configuration Options
Uvicorn is highly configurable via CLI arguments or environmental variables (prefixed with UVICORN_).
| Option | Type | Default | Description |
|---|---|---|---|
--host | str | 127.0.0.1 | Bind socket to this host. |
--port | int | 8000 | Bind socket to this port. |
--workers | int | None | Number of worker processes ($WEB_CONCURRENCY). |
--reload | bool | False | Enable auto-reload on code changes. |
--loop | str | auto | Event loop implementation (asyncio, uvloop). |
--http | str | auto | HTTP protocol (httptools, h11). |
--limit-concurrency | int | None | Max concurrent connections before 503 responses. |
Sources: uvicorn/main.py:61-150, uvicorn/config.py:255-265
Conclusion
Uvicorn serves as a critical bridge in the Python ecosystem, enabling high-performance asynchronous web serving. Its flexible architecture allows it to scale from a single-process development server with auto-reload capabilities to a multi-worker production deployment using uvloop and httptools for maximum throughput.
Sources: README.md:58-85, uvicorn/main.py:512-525