Understanding ASGI: scopes and event flow for HTTP and WebSocket apps
ASGI (Asynchronous Server Gateway Interface) is the standard interface between asynchronous Python apps and protocol servers. The server provides a per-connection scope; the app receives events through receive and sends response events with send. An HTTP request has one scope per request, while a WebSocket scope lasts until the connection closes. This event model supports protocols that exchange multiple messages. This guide explains the ASGI 3 callable, HTTP/WebSocket events, and lifespan; it does not cover a framework API or server deployment.
ASGI (Asynchronous Server Gateway Interface) is the standard interface between asynchronous Python apps and protocol servers. The server provides a per-connection scope; the app receives events through receive and sends response events with send. An HTTP request has one scope per request, while a WebSocket scope lasts until the connection closes. This event model supports protocols that exchange multiple messages. This guide explains the ASGI 3 callable, HTTP/WebSocket events, and lifespan; it does not cover a framework API or server deployment.
ASGI apps use a connection scope and an async callable
An ASGI 3 app is one callable: async def application(scope, receive, send). scope is a dictionary with connection type and request metadata. receive and send are awaitable callables. Use scope["type"] to distinguish http, websocket, and lifespan; each protocol has its own scope lifetime.
async def application(scope, receive, send):
if scope["type"] != "http":
return
while True:
event = await receive()
if event["type"] == "http.disconnect":
return
if event["type"] == "http.request" and not event.get("more_body", False):
break
body = b"Hello ASGI\n"
await send(
{
"type": "http.response.start",
"status": 200,
"headers": [
[b"content-type", b"text/plain; charset=utf-8"],
[b"content-length", str(len(body)).encode("ascii")],
],
}
)
await send({"type": "http.response.body", "body": body})This illustrative example consumes the HTTP request body events, then sends a fixed response. It was not run or verified and has no application logic or production error handling. Large request bodies should be consumed in chunks rather than accumulated in memory.
HTTP exchanges request and response events
An HTTP scope lasts for one request, even when the underlying socket remains open for other requests. Metadata such as method, path, query, headers, and scheme is in the scope. The body can arrive in http.request chunks: when more_body is true, wait for another chunk; false means the body is complete. The protocol server handles transfer encoding and presents decoded body bytes.
An app usually starts a response with http.response.start, containing an integer status and byte header pairs, then sends one or more http.response.body events. The final body event ends the response. Headers are represented as byte pairs and can preserve duplicates. Cookie headers have special repetition rules under HTTP/2 and HTTP/3; do not combine Set-Cookie values with commas. The HTTP sub-specification's spec_version is different from both the ASGI version and HTTP version. Check support before sending optional features.
WebSocket exchanges events for the connection lifetime
A WebSocket is not a single HTTP response. Its scope lasts while the socket is connected. The handshake begins with websocket.connect; the app chooses to accept or reject, then exchanges messages using websocket.receive and websocket.send. Closing and disconnect details depend on the ASGI HTTP/WebSocket sub-specification version supported by the server.
HTTP request/response logic cannot simply be reused for a long-lived socket. Design authentication expiry, disconnect handling, background task cancellation, and resource cleanup for that lifetime.
Lifespan initializes and cleans up event-loop resources
The lifespan scope lasts for an event loop, not one HTTP request or WebSocket. At startup, the server sends lifespan.startup; after successful initialization, the app sends lifespan.startup.complete and the server may begin accepting connections. At shutdown, the app receives lifespan.shutdown, cleans up, and replies with lifespan.shutdown.complete. Create and close event-loop-bound resources such as database pools inside the relevant lifespan.
Multi-process or multi-thread servers can run lifespan once per process or thread event loop. Do not assume module globals are a single shared resource across workers. Servers may not support the lifespan state feature, so check the chosen server's behavior.
WSGI conversion and common misconceptions
WSGI is a synchronous callable that returns one response iterable. ASGI uses per-connection async calls and event exchange. A compatibility wrapper can run some WSGI requests inside an ASGI server, often by running synchronous code in a thread pool. This translates the interface; it does not automatically make the app asynchronous or add WebSocket support.
**Only part of a request body is processed:** keep receiving while `http.request` has `more_body=True`.
**The body is truncated or processed twice:** check the receive loop's completion and `http.disconnect` handling.
**An optional header or WebSocket feature fails on some servers:** compare `scope["asgi"]["spec_version"]` with the feature requirement; if absent, follow the sub-spec's default version.
**A pool initialized by one worker is shared elsewhere:** check the event loop and lifespan scope that created it.
**Assuming ASGI is automatically faster:** do not claim a speedup without profiling sync libraries, CPU load, connection patterns, server, and app.
Sources and scope
[ASGI 3.0 base specification](https://asgi.readthedocs.io/en/stable/specs/main.html) — callable, scope, events, and connection lifetime
[HTTP and WebSocket ASGI message format](https://asgi.readthedocs.io/en/stable/specs/www.html) — HTTP scope/body/response, header representation, WebSocket, and sub-spec versions
[ASGI Lifespan protocol](https://asgi.readthedocs.io/en/stable/specs/lifespan.html) — startup/shutdown events and per-event-loop state
[ASGI introduction](https://asgi.readthedocs.io/en/stable/introduction.html) — structural difference from WSGI and compatibility wrappers
Official docs were read on 2026-11-20. The sample is illustrative and was not run. No framework/server support, throughput, failure behavior, or deployment outcome was tested.