Lesson 6 of 59How backends work
ASGI and Uvicorn
Understand the layers under FastAPI, from Uvicorn's sockets to the ASGI callable, and call one by hand.
When you run a FastAPI app you type uvicorn app.main:app, not python main.py. That one command hides a whole stack of software, and knowing the layers is what lets you read a production error, pick the right number of workers, or answer "what is ASGI?" in an interview without guessing.
Two jobs, two programs
A Python web backend is split into two programs that agree on a contract:
- The server handles the network: it listens on a port, accepts connections, reads raw bytes, parses HTTP, and writes bytes back. It knows nothing about your todos.
- The application is your code (plus a framework). It receives an already parsed request and returns a response. It never touches a socket.
The contract between them is a Python calling convention. The old one is WSGI (Web Server Gateway Interface, 2003), used by Flask and classic Django. The new one is ASGI (Asynchronous Server Gateway Interface, 2016+), used by FastAPI, Starlette and modern Django.
Because of the contract, any server works with any framework. You can swap Uvicorn for Hypercorn or Granian without changing a line of your app.
WSGI vs ASGI
A WSGI app is a plain function. The server calls it once per request and waits for it to return.
def app(environ, start_response):
# environ: a dict with the method, path, headers...
start_response("200 OK", [("Content-Type", "text/plain")])
return [b"Hello"]That is simple, but it has a cost. While the function waits on a slow database query, its whole worker (a thread or process) sits idle. To serve 100 slow requests at once you need about 100 threads. And a function that returns once cannot hold a WebSocket open for minutes.
An ASGI app is an async function with three arguments.
async def app(scope, receive, send):
# scope: info about the connection (type, method, path, headers)
# receive: await it to get the next incoming message
# send: await it to send an outgoing message
...Because it is async, the app can await a database call, and while it waits, the same thread runs other requests. One process can juggle thousands of open connections. And because it talks in messages instead of returning once, the same interface handles HTTP, WebSockets and server-sent events.
| WSGI | ASGI | |
|---|---|---|
| Shape | app(environ, start_response) returns body | async app(scope, receive, send) |
| Concurrency | One request per thread or process | Many requests per process via async/await |
| WebSockets | No | Yes |
| Servers | Gunicorn, uWSGI | Uvicorn, Hypercorn, Granian |
| Frameworks | Flask, Django (classic) | FastAPI, Starlette, Django (async) |
Calling an ASGI app by hand
Here is a real ASGI app. No framework, no server. We play the server ourselves: build a scope, write fake receive and send functions, and call it.
Press Run (⌘ Enter) to see what happens.Change the body to b"" and run again. That is the whole interface. Uvicorn does exactly this, except receive reads real bytes from a socket and send writes real bytes back.
After running the code above, what does this print?
print(len(sent), sent[0]["status"], sent[1]["type"])
The messages always go in the same order, and the server checks it.
Uvicorn reads bytes from the socket and parses the HTTP request line and headers.
Order the steps of serving one HTTP request over ASGI.
- Tap the steps below in the right order.
Uvicorn, Starlette, FastAPI
Writing raw ASGI apps is tedious: you would parse query strings, match paths and build headers by hand. So we stack libraries.
Uvicorn is the ASGI server. It owns the port and the event loop and speaks HTTP on the wire.
This is why FastAPI's docs often send you to Starlette's docs for things like Request, StreamingResponse or middleware: those parts are Starlette's, re-exported by FastAPI.
Running Uvicorn
The command names a module and a variable inside it: module.path:variable.
# app/main.py contains `app = FastAPI()`uvicorn app.main:app --reload# Listen on every network interface (needed inside Docker), port 8000uvicorn app.main:app --host 0.0.0.0 --port 8000# Production: 4 worker processes, no reloaduvicorn app.main:app --host 0.0.0.0 --port 8000 --workers 4--reloadwatches your files and restarts the server on save. Development only: it is slow and uses extra memory.--host 0.0.0.0accepts connections from other machines. The default127.0.0.1only accepts connections from the same machine, which is a common "it works locally but not in Docker" bug.--workers 4starts 4 separate processes, each with its own event loop. One Python process runs your Python code on one CPU core at a time, so workers are how you use all the cores. A common starting point is one worker per core.
pip install "uvicorn[standard]" (included with fastapi[standard]) adds uvloop, a faster event loop, and httptools, a faster HTTP parser.
What about Gunicorn?
Gunicorn is a mature process manager from the WSGI world. For years the standard production setup was Gunicorn supervising Uvicorn workers: Gunicorn restarts crashed workers and handles signals, Uvicorn handles the requests.
gunicorn app.main:app -k uvicorn_worker.UvicornWorker -w 4 --bind 0.0.0.0:8000The worker class now lives in the small uvicorn-worker package. Recent Uvicorn versions can supervise their own workers too (--workers restarts dead ones), so many teams just use uvicorn --workers or fastapi run --workers 4. In containers on Kubernetes or ECS, people often run one Uvicorn process per container and let the platform run more containers instead.
Match each piece to its job.
uvicorn app.main:app inside a Docker container and publish port 8000, but your browser cannot connect. What is the likely fix?Practice
A raw ASGI app
Write a raw ASGI application, no framework: async def app(scope, receive, send).
Behaviour:
GET /responds200with bodyb"Hello, ASGI".POST /echoreads the request body withawait receive()and responds200with that same body.- Any other method or path responds
404with bodyb"Not Found".
Every response sends exactly two messages, in this order:
{"type": "http.response.start", "status": 200, "headers": [(b"content-type", b"text/plain")]}
{"type": "http.response.body", "body": b"Hello, ASGI"}The tests play the server: they call your app with a fake receive (returns one http.request message) and a fake send that records messages.
- ASGI
- The async contract between Python web servers and apps:
async app(scope, receive, send). - WSGI
- The older synchronous contract:
app(environ, start_response)returns a body once. No WebSockets. - Uvicorn
- An ASGI server. It listens on a port, parses HTTP, runs the event loop, and calls your app.
- Starlette
- The ASGI toolkit FastAPI is built on. It provides routing, requests, responses and middleware.
- worker
- One server process with its own event loop. Run several to use several CPU cores.
- scope
- The dict an ASGI app receives with connection details: type, method, path, headers, query string.