Skip to content

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.

14 min read0/5 questions

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.

wsgi_app.py
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.

asgi_app.py
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.

WSGIASGI
Shapeapp(environ, start_response) returns bodyasync app(scope, receive, send)
ConcurrencyOne request per thread or processMany requests per process via async/await
WebSocketsNoYes
ServersGunicorn, uWSGIUvicorn, Hypercorn, Granian
FrameworksFlask, Django (classic)FastAPI, Starlette, Django (async)
Quick check
Your app has a chat feature that keeps a WebSocket open for each user. Which statement is true?
Need a nudge? A hint rules out a wrong answer.

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.

Pythonasgi_by_hand.py
async def app(scope, receive, send): message = await receive() # the request body arrives as a message name = message["body"].decode() or "stranger" await send({ "type": "http.response.start", "status": 200, "headers": [(b"content-type", b"text/plain")], }) await send({ "type": "http.response.body", "body": f"Hello, {name}! You asked for {scope['path']}".encode(), }) # --- we play the server ---scope = {"type": "http", "method": "POST", "path": "/greet", "headers": []} async def receive(): return {"type": "http.request", "body": b"Ada", "more_body": False} sent = []async def send(message): sent.append(message) # Uvicorn would `await app(...)` inside its event loop. Our fake receive and# send never pause, so we can step the coroutine to the end by hand.coro = app(scope, receive, send)try: coro.send(None)except StopIteration: pass for message in sent: print(message)
Output
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.

Predict the outputPython

After running the code above, what does this print?

print(len(sent), sent[0]["status"], sent[1]["type"])
Need a nudge? Hints walk you through it.

The messages always go in the same order, and the server checks it.

One HTTP request over ASGI
ClientUvicornAppPOST /greet (raw bytes)app(scope, receive, send)await receive()http.response.starthttp.response.bodyHTTP/1.1 200 OK

Uvicorn reads bytes from the socket and parses the HTTP request line and headers.

1/6
Put it in order5 steps

Order the steps of serving one HTTP request over ASGI.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

What runs when a request hits a FastAPI app
  1. Your path functionsdef read_todo(todo_id: int): ...
  2. FastAPIType hints to validation, dependency injection, OpenAPI docs
  3. StarletteRouting, Request/Response objects, middleware, WebSockets
  4. ASGI interfaceasync app(scope, receive, send)
  5. UvicornSockets, HTTP parsing (httptools/h11), event loop (uvloop)
  6. Operating systemTCP connections on a port

Uvicorn is the ASGI server. It owns the port and the event loop and speaks HTTP on the wire.

1/5

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
  • --reload watches your files and restarts the server on save. Development only: it is slow and uses extra memory.
  • --host 0.0.0.0 accepts connections from other machines. The default 127.0.0.1 only accepts connections from the same machine, which is a common "it works locally but not in Docker" bug.
  • --workers 4 starts 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:8000

The 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 the pairs0/5 matched

Match each piece to its job.

Choose an item, then its match on the other side.
Quick check
You run uvicorn app.main:app inside a Docker container and publish port 8000, but your browser cannot connect. What is the likely fix?
Need a nudge? A hint rules out a wrong answer.

Practice

ChallengeMedium

A raw ASGI app

Write a raw ASGI application, no framework: async def app(scope, receive, send).

Behaviour:

  • GET / responds 200 with body b"Hello, ASGI".
  • POST /echo reads the request body with await receive() and responds 200 with that same body.
  • Any other method or path responds 404 with body b"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.

Python
async def app(scope, receive, send): # Decide status and body from scope["method"] and scope["path"], # then await send(...) twice: response start, then response body. pass
Key terms
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.