Mental model
Unlike Python's legacy WSGI standard—which processes one blocking HTTP request per OS thread from start to finish—ASGI (Asynchronous Server Gateway Interface) models every HTTP request, WebSocket frame stream, and server lifespan hook as an asynchronous coroutine driven by a fast non-blocking asyncio / uvloop event loop inside Uvicorn or Hypercorn. Because one worker process multiplexes thousands of open sockets over OS epoll/kqueue notifications while awaiting database queries, Redis lookups, and upstream LLM streams, ASGI unlocks orders-of-magnitude higher connection concurrency—provided application routes never accidentally stall that shared event loop with blocking synchronous I/O or heavy CPU loops.
Theory
An ASGI application is formally a single async callable accepting three objects: scope (a connection metadata dictionary decoded once per HTTP request or WebSocket lifecycle), receive (an awaitable coroutine yielding incoming request body or disconnect events), and send (an awaitable coroutine flushing response status headers and streamed body chunks back to the client socket).
| Server / Protocol Layer | Concurrency Model | Streaming & WebSocket Support | Ideal Production Deployment |
|---|---|---|---|
Uvicorn (--loop uvloop --http httptools) | Single-process Cython/libuv epoll loop per worker | Native HTTP/1.1 + WebSockets; crisp lowest-overhead latency | Default FastAPI runtime behind Nginx/Traefik HTTP/2 proxy |
| Hypercorn | asyncio / Trio event loops with pure-Python or HTTP/2 framing | Native HTTP/1.1, HTTP/2 multiplexing, HTTP/3 QUIC, WebSockets | Direct HTTP/2 gRPC/ASGI termination when no reverse proxy sits in front |
Gunicorn + uvicorn.workers.UvicornWorker | Prefork multi-process supervisor spawning N async worker processes | Manages graceful SIGUSR2 reloads & crashed-worker respawns | Bare-metal / VM multi-core boxes needing OS process supervision |
| WSGI (Gunicorn Sync / gthread) | 1 OS thread per in-flight HTTP socket | Breaks on WebSockets and stalls under 1,000 open SSE LLM streams | Legacy synchronous Django/Flask CRUD apps only |
Event Loop Protection, Sync Threadpools, and Container Worker Sizing
FastAPI treats async def and plain def path operations fundamentally differently at ASGI dispatch time:
async defendpoints execute directly on the worker'suvloopthread. Any blocking call inside them (requests.get(),time.sleep(), synchronouspsycopg2queries, heavy JSON compression) freezes all concurrent users assigned to that worker process until it finishes.defendpoints are automatically dispatched via Starlette (run_in_threadpool) to AnyIO's per-worker threadpool (40threads by default), isolating blocking synchronous SDKs cleanly from the main loop—though saturating all40threads stalls new synchronous requests behind thread exhaustion.
pythonimport asynciofrom collections.abc import Awaitable, Callablefrom fastapi import FastAPI# Minimal raw ASGI server-protocol signature understood by Uvicorn and Hypercornasync def raw_asgi_healthcheck(scope: dict[str, object],receive: Callable[[], Awaitable[dict[str, object]]],send: Callable[[dict[str, object]], Awaitable[None]],) -> None:if scope["type"] == "lifespan":while True:event = await receive()if event["type"] == "lifespan.startup":await send({"type": "lifespan.startup.complete"})elif event["type"] == "lifespan.shutdown":await send({"type": "lifespan.shutdown.complete"})returnreturnassert scope["type"] == "http"await send({"type": "http.response.start","status": 200,"headers": [(b"content-type", b"application/json")],})await send({"type": "http.response.body", "body": b'{"status":"ok"}'})# Production container entrypoint:# Prefer single-process `uvicorn app:main --workers 1` per K8s pod sized to 1-2 vCPU,# or multi-worker `fastapi run` / `uvicorn --workers N --timeout-graceful-shutdown 30` on VMs.
Also watch Kubernetes container CPU limits carefully: spawning --workers 16 inside a 2-vCPU container causes severe CFS throttling and multiplies memory (16x model/code RSS) without extra throughput. Size workers to physical CPU quota (1 per container on orchestrators scaling pods horizontally, or cores to 2 * cores + 1 on dedicated hosts with mixed def threadpools) and always configure --timeout-graceful-shutdown paired with --limit-concurrency for overload backpressure.
Alternatives and trade-offs
- Single-Worker Uvicorn per Kubernetes Container: Simplest signal handling (
SIGTERMtriggers lifespan shutdown cleanly), predictable memory per replica, linear pod-level autoscaling, zero duplicate scheduled crons across workers; relies on Kubernetes HorizontalPodAutoscaler for multi-core scaling. - Multi-Worker Process Supervisor (
uvicorn --workers Nor Gunicorn): Maximizes multi-core CPU utilization on single VMs/VPS nodes where horizontal orchestrators are absent; replicates per-worker memory caches (Ncopies of connection pools and in-memory structures) unless coordinated via Redis. - Hypercorn with HTTP/2 Direct Termination: Removes the Nginx/Envoy hop when internal cluster services demand multiplexed HTTP/2 directly into FastAPI without an external ingress proxy.
Failure modes and misconceptions
- Calling Blocking I/O (
requests,time.sleep, syncboto3) Insideasync def: Even a 100 ms blocking call inside anasync defhandler freezes every WebSocket ping, healthcheck, and concurrent API call sharing that Uvicorn worker process—turning10concurrent requests into1.0 sp99 tail latency. Either switch to async drivers (httpx.AsyncClient,asyncpg) or mark the endpoint plaindef/ offload viaasyncio.to_thread(). - Ignoring Reverse-Proxy
proxy_headersBehind TLS Terminators: Running Uvicorn without--proxy-headers --forwarded-allow-ips="*"(or scoped proxy CIDR) makesrequest.client.hostresolve to the load balancer IP (127.0.0.1/172.18.0.x) and breaks HTTPS redirect URL generation (request.url_for()). - Leaving Default
--timeout-keep-alive 5Shorter Than Upstream ALB Idle Timeout: When AWS ALB / Nginx uses a60 skeep-alive pool against Uvicorn's5 sserver keep-alive timeout, Uvicorn closes TCP sockets mid-reuse right as the load balancer sends a new request, generating spurious HTTP502 Bad Gatewayerrors. Set Uvicorn--timeout-keep-aliveslightly higher (65–75 s) than upstream proxy keep-alive timeouts. - Assuming Python's GIL Disables ASGI Concurrency: While CPython serializes bytecode execution per process, network sockets (
uvloop/httptools) spend95%+of I/O-bound AI API latency suspended waiting on PostgreSQL, Redis, and upstream LLM streams—yielding high single-worker concurrency until actual Python CPU work saturates a core.
Decision scenario
Your FastAPI AI gateway serves 1,500 concurrent streaming SSE chat sessions behind a Traefik reverse proxy (60 s idle keep-alive) on 4-vCPU Kubernetes nodes with 1 vCPU pod requests. Run one Uvicorn process per container with --loop uvloop --http httptools --proxy-headers --timeout-keep-alive 70 --timeout-graceful-shutdown 30 so pod memory stays lean and Kubernetes manages replica scaling across nodes, migrate all downstream LLM/DB clients to httpx.AsyncClient and asyncpg so the uvloop thread stays 100% unblocked, and wrap any legacy synchronous PDF parsers with await asyncio.to_thread(...) bounded by a max_concurrency semaphore.
Learning outcomes
- Trace the three-part ASGI contract (
scope,receive,send) across HTTP requests and worker lifespan hooks. - Distinguish FastAPI's direct
uvloopexecution forasync defroutes vs. AnyIO threadpool offloading for plaindefroutes. - Prevent
502 Bad Gatewaykeep-alive races by keeping Uvicorn's--timeout-keep-aliveabove reverse-proxy idle timeouts. - Right-size Uvicorn workers across single-process Kubernetes pods vs. multi-core VM deployments with graceful shutdown bounds.
Trade-offs
ASGI with uvloop yields massive streaming concurrency and sub-millisecond dispatch overhead in Python, at the operational cost of strict non-blocking discipline across all libraries imported inside async def code paths and careful keep-alive synchronization with reverse proxies.