Every FastAPI project ends its tutorial with the same incantation: uvicorn main:app --reload. You type it a thousand times without thinking, and then production bites you — a graceful shutdown hangs until the orchestrator force-kills the pod, a worker dies silently and traffic starts 502-ing, or your “scaled” service turns out to be one process all along. At that point the server stops being a black box and becomes code you need to read.
The good news is that uvicorn rewards reading. The tree of encode/uvicorn on branch main is compact and honest about its seams: one uvicorn/ package where config.py (about 615 lines) turns CLI flags into a loaded application, server.py (353 lines) owns the lifecycle, protocols/ holds swappable wire implementations, supervisors/ handles processes, and lifespan/ bridges startup hooks. The wiring lives in small dicts like HTTP_PROTOCOLS and LOOP_FACTORIES.
This tour follows the call path of uvicorn main:app --workers 2 from argument parsing to child processes, with every symbol and line number taken from the real tree. Two maps accompany it: an overview of how the major layers hand off, and a detail diagram down to individual methods. If you serve FastAPI apps for a living, this is the machinery underneath every request.
Uvicorn's control plane at a glance: run() builds a Config, Config resolves protocol and loop factories, Server executes the lifecycle, and Multiprocess duplicates that Server across workers sharing one pre-bound socket.
Reading the overview from left to right:
- Server.run, L85 — wraps
serve()inasyncio_run()with whatever loop factory the Config resolves. - Server.startup, L115 — runs lifespan startup first, then hands a
create_protocolfactory toloop.create_server. - Config.load, L438 — imports the app string, resolves protocol classes, builds SSL, wraps middleware — exactly once.
- HttpToolsProtocol, L44 — the default HTTP/1.1 implementation whenever the C-backed
httptoolspackage imports. - RequestResponseCycle.run_asgi, L418 — one asyncio task per request, translating ASGI
send()/receive()events to socket bytes. - FlowControl, L10 — backpressure at the transport edge: reading pauses above 64 KiB, writes gate behind
drain().- AutoZttpProtocol._switch, L78 — swaps HTTP/1.1 for HTTP/2 after sniffing ALPN or the cleartext h2c preface. - Multiprocess.keep_subprocess_alive, L214 — the parent’s 0.5-second tick that health-checks children and respawns the dead.
- LifespanOn.startup, L47 — queues a
lifespan.startupmessage and blocks until the app acknowledges it.
The detail view follows each hop: click options into Config.load, the tick loop and signal capture inside Server, per-connection protocol factories, lifespan assertions, and the two supervisor families.
The run() loop: signals, ticks, and a 0.1-second heartbeat
Server.run() is two lines that hide a philosophy: asyncio_run(self.serve(sockets=sockets), loop_factory=self.config.get_loop_factory()). The loop is a parameter, not an ambient fact. Config.get_loop_factory() (uvicorn/config.py, L554) resolves the --loop flag through the LOOP_FACTORIES map — none, auto, asyncio, uvloop, or the newer zuvloop — and uvicorn/loops/auto.py (L7) simply probes whether uvloop imports. The pure-asyncio factory has a platform twist: on Windows, without subprocesses, it returns asyncio.ProactorEventLoop, and everywhere else asyncio.SelectorEventLoop (uvicorn/loops/asyncio.py, L10-L11). That is a CPython stdlib subtlety leaking into server behavior: the Proactor loop supports the pipes that subprocess reloading needs, and it is traded away when you share sockets explicitly.
Signal handling is equally deliberate. serve() wraps _serve() in capture_signals() (L329), which registers signal.signal — not loop.add_signal_handler — so the original handlers can be restored, and re-raises captured signals LIFO when the context exits. handle_exit() (L348) sets should_exit on the first SIGINT and force_exit on the second, which is why pressing Ctrl+C twice during a stuck shutdown works.
Once serving, the server is not idle-blocked; it runs main_loop() (L242): sleep 0.1 seconds, call on_tick(), repeat, with the counter wrapping at 864000 ticks. on_tick() (L251) refreshes the Date header into ServerState.default_headers every 10 ticks — about once per second — and checks the request budget. That budget has a twist: limit_max_requests is a cached_property (L79) that adds random.randint(0, limit_max_requests_jitter) to the cap, so workers restarted by the same deploy do not all hit their ceiling in the same second. Shutdown (L281) closes listeners, calls shutdown() on every live connection, waits inside asyncio.timeout(timeout_graceful_shutdown) (L296), cancels leftover tasks, and only then fires the lifespan shutdown. Failures before serving exit with code 3 — STARTUP_FAILURE = 3 (config.py, L81), a constant the supervisor layer checks later.
Three HTTP parsers, one ASGI contract
The HTTP_PROTOCOLS dict in config.py (L52-L57) maps four names to import strings: auto, h11, httptools, zttp. The auto resolution happens at import time in uvicorn/protocols/http/auto.py: try import httptools, use HttpToolsProtocol on success, fall back to H11Protocol. Everything downstream only ever sees an asyncio.Protocol, so the parser swaps without touching the server.
The httptools implementation is the one worth studying. The class wires itself as the parser callback target: on_url (L238), on_header (L241), on_headers_complete (L249), on_body (L311) feed a per-connection scope incrementally. A cold-start optimization sits at L41: a STATUS_LINE dict precomputes the full HTTP/1.1 <code> <phrase>\r\n byte string for every status code from 100 to 599 — 500 entries — so response writing never does a http.HTTPStatus lookup per request. Completed-but-unanswered requests queue in a deque (L91), enabling HTTP/1.1 request queueing on one connection. WebSocket upgrades replay the raw request bytes into a newly constructed WebSocket protocol (L185-L203) and swap it in with transport.set_protocol().
Each request becomes a RequestResponseCycle (L377) whose run_asgi() (L418) builds the ASGI scope, spawns a task tracked in ServerState.tasks, and mediates the protocol. Backpressure lives in FlowControl (L10): HIGH_WATER_LIMIT is 65536 bytes (L8), and when the concurrency limit is exceeded the cycle short-circuits into service_unavailable() (L42), which hand-writes a 503 with connection: close. The h11 alternative (L40) constructs an h11.Connection (L57) and leans on that library’s state machine; its --h11-max-incomplete-event-size flag bounds header buffering.
From httptools and h11 to zttp: how HTTP/2 entered the tree
For years uvicorn shipped without HTTP/2, and the current tree shows it being introduced surgically. The new parser is zttp, pinned as an optional dependency at zttp>=0.0.34 in pyproject.toml (L72). Enabling --http2 without it is a hard error: Config.load() raises ValueError unless http == "zttp" (config.py, L441-L447), because HTTP/2 lives in ZttpH2Protocol (zttp_h2_impl.py, L35), not in the older backends.
The entry point is AutoZttpProtocol (auto_zttp_impl.py, L15), a dispatcher with one job. Over TLS it consults the negotiated ALPN result inside connection_made (L48-L52); in cleartext it buffers the first bytes and matches the 24-byte client preface HTTP2_PREFACE = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" (L12). The class advertises alpn_protocols = ["h2", "http/1.1"] (L23), and Config.load() threads that attribute into create_ssl_context()’s set_alpn_protocols() call (config.py, L137-L138) — protocol selection and TLS configuration meet in one place. _switch() (L78) replaces itself on the transport via transport.set_protocol(), replaying buffered bytes, so the client never sees the negotiation.
Other build facts appear only in the tree: the dev toolchain is pinned to ruff >=0.15.15 plus pytest>=9.1.1 (pyproject.toml, L53-L54); parser leniencies are enabled with set_dangerous_leniencies(lenient_data_after_close=True), guarded by an AttributeError fallback for httptools older than 0.6.3 (httptools_impl.py, L64-L68); and default limits are conservative — backlog=2048, timeout_keep_alive=5 seconds, ws_max_size=16777216 (config.py, L232-L233 and L206).
Workers, reloaders, and the socket handoff
The dispatch happens at the bottom of run() in uvicorn/main.py (L625-L643): reload maps to ChangeReload, more than one worker maps to Multiprocess, and everything else is a plain server.run(). Both multi-process modes require the app as an import string — a bound instance cannot be pickled into a fresh interpreter — and Config.bind_socket() (L567) binds once in the parent with SO_REUSEADDR, marks the socket set_inheritable(True) (L612), and hands the same listening socket to every child, which is why worker scaling does not multiply kernel accept queues.
Multiprocess (supervisors/multiprocess.py, L141) is a 140-line arbiter. It registers handlers for INT TERM BREAK HUP QUIT TTIN TTOU USR1 USR2 WINCH (L17-L21), parks them in a queue drained every 0.5 seconds (L203), and translates them into pool operations: SIGTTIN adds a worker, SIGTTOU removes one (L267-L281), SIGHUP restarts the pool. Child health is a multiprocessing Pipe: Process.ping() (L49) sends b"ping" and waits for a reply from a daemon always_pong thread (L62) in the child, which answers with the server’s started flag. A hung child is killed and replaced by keep_subprocess_alive() (L214), but a child exiting with code 3 — STARTUP_FAILURE — stops the parent too, because a broken app import would otherwise loop forever (L225-L231). Restarts are zero-downtime: restart_all() (L173) starts the replacement and waits for it to report ready before terminating the old worker.
Reload supervision shares the child-spawning plumbing through get_subprocess() (uvicorn/_subprocess.py, L21), which uses the spawn context and reconfigures logging in each child. BaseReload (basereload.py, L25) provides the startup/restart/shutdown skeleton, and the exported ChangeReload in supervisors/init.py resolves to WatchFilesReload when watchfiles is installed, else StatReload, which stats files every 0.25s.
The lifespan handshake and middleware wrapping
ASGI lifespan is its own mini-protocol, implemented as a queue conversation. LifespanOn (lifespan/on.py, L31) starts a task running main() (L78), which invokes the application with a scope of type: "lifespan" — the app pulls lifespan.startup from receive_queue and replies through send(). Every reply mutates asyncio Events with assertion-guarded transitions (L102-L134), so an app that sends startup.complete twice fails loudly. The shared state dict (L45) flows into every request scope as app_state, which is how lifespan-published objects reach handlers. If the application dies on the lifespan scope while --lifespan auto is active, the server logs “ASGI ‘lifespan’ protocol appears unsupported.” (L93) and continues — that tolerance is what makes auto the safe default.
Middleware wrapping is explicit, applied in Config.load() (L534-L543) in fixed order: WSGI apps get bridged (delegating to a2wsgi when installed, otherwise the internal _WSGIMiddleware at wsgi.py, L82), ASGI 2.0 dual-callable apps get adapted by ASGI2Middleware (asgi2.py, L9), trace-level logging inserts MessageLoggerMiddleware, and ProxyHeadersMiddleware (proxy_headers.py, L9) rewrites client and scheme from X-Forwarded-* headers — but only for hosts in _TrustedHosts (L105), defaulting to 127.0.0.1,::1. On the response side, Config.load() encodes custom headers to latin-1 and prepends server: uvicorn unless you supplied your own (config.py, L495-L500).
Honest Limits
Reading the source also tells you where uvicorn will not help you. Each process runs a single event loop; one CPU-bound request blocks every connection in that worker. The 0.1-second tick loop means signal-triggered shutdown can lag by a tick, and the Enjoyed this post? Never miss out on future posts by following us Date header refreshes at one-second granularity. Reload and multiple workers are mutually exclusive — enabling both logs "workers" flag is ignored when reloading is enabled (config.py, L366-L367). On Windows there is no SIGTERM, so the supervisor sends CTRL_BREAK_EVENT and children translate SIGBREAK to SIGTERM themselves (multiprocess.py, L67-L74). WebSocket support with --ws auto silently degrades to none if neither websockets nor wsproto is installed (websockets/auto.py), surfacing later as a confusing “Unsupported upgrade request” warning. HTTP/2 requires installing the separate zttp package, and cleartext h2c works only via prior-knowledge preface sniffing, not the Upgrade header. And behind Gunicorn, the in-tree uvicorn.workers module is deprecated in favor of the extracted uvicorn-worker package (workers.py, L21-L26). None of these are bugs; they are trade-offs with names, and now you know where each one lives.