ASGI

Also known as: Asynchronous Server Gateway Interface

On this page 7

ASGI, the Asynchronous Server Gateway Interface, is the Python specification that defines how an asynchronous server passes network events to a web application and receives responses back. In the landscape of web servers and application servers, ASGI is the async successor to WSGI: it keeps the idea of a neutral contract between server and framework, but adds support for long-lived connections such as WebSocket, HTTP/2 streams and server-sent events.

An ASGI deployment typically has three layers: a front-facing reverse proxy such as Nginx or Traefik, an ASGI server such as Uvicorn, Hypercorn or Daphne, and an ASGI application written with a framework such as Starlette, FastAPI, Django or Quart. Because the interface is standardized, any compliant server can run any compliant application.

How the ASGI interface works

An ASGI application is a single asynchronous callable with the signature async def app(scope, receive, send). The server calls it once per connection, not once per request, which is the central design difference from WSGI, where one synchronous call handles one request and returns one response.

The three arguments carry the whole conversation. The scope is a dictionary describing the connection: its type (http, websocket or lifespan), path, headers, client address and ASGI version. The receive awaitable delivers incoming events, and the send awaitable emits outgoing events. Each event is a plain dictionary with a type key, such as http.request or websocket.receive.

The following table lists the main message types an application sees during a typical connection.

Event typeDirectionPurpose
http.requestServer to appDelivers request body chunks
http.response.startApp to serverSends status code and headers
http.response.bodyApp to serverSends body chunks, with a more-body flag
http.disconnectServer to appSignals that the client went away
websocket.connectServer to appOpens a WebSocket handshake
websocket.sendApp to serverPushes a text or binary frame
lifespan.startupServer to appRuns once before serving traffic
Core ASGI event types and their direction

Because body data arrives and leaves in chunks with a more_body flag, ASGI supports streaming uploads and downloads natively. The lifespan protocol lets an application open database pools or load models at startup and release them cleanly at shutdown, a task that WSGI never standardized.

ASGI compared with WSGI and other gateway interfaces

ASGI belongs to a family of gateway interfaces that separate the network-facing process from application code. The Common Gateway Interface started one process per request, FastCGI and PHP-FPM kept persistent worker processes, and WSGI standardized the Python synchronous model. ASGI extends this lineage to event-loop concurrency.

The table below compares the interfaces a server administrator is most likely to meet in Python and PHP hosting.

InterfaceExecution modelLong-lived connectionsTypical servers
CGINew process per requestNoApache, lighttpd
FastCGIPersistent worker processesNoPHP-FPM, Nginx upstream
WSGISynchronous call per requestNoGunicorn, uWSGI, mod_wsgi
ASGIAsync callable per connectionYesUvicorn, Hypercorn, Daphne
Gateway interfaces compared

ASGI is backward compatible in practice: adapters such as WsgiToAsgi wrap a WSGI application so it can run under an ASGI server in a thread pool. The reverse is not true, because a WSGI server has no way to hold a connection open while the application awaits further events.

Servers, frameworks and deployment topology

A production ASGI stack separates connection handling, process management and application logic. The ASGI server parses HTTP or WebSocket frames and runs the event loop, a process manager supervises several worker processes, and the reverse proxy terminates TLS, serves static files and buffers slow clients.

The following table summarizes the components most often combined in ASGI deployments.

ComponentRoleNotes
UvicornASGI serverFast, uses uvloop and httptools when available
HypercornASGI serverSupports HTTP/2 and HTTP/3 over QUIC
DaphneASGI serverReference server from the Django Channels project
GunicornProcess managerRuns Uvicorn workers via a worker class
Nginx or TraefikReverse proxyTLS, compression, WebSocket upgrade forwarding
FastAPI, Starlette, DjangoFrameworksExpose an ASGI app object to the server
Common components of an ASGI deployment

Concurrency in ASGI is multiplied across two axes: each worker process runs one event loop that can hold thousands of idle connections, and the number of workers is usually set near the number of CPU cores. A single loop uses one core, so CPU-bound work still requires more processes, not more coroutines.

Configuring and tuning an ASGI server

Correct ASGI configuration depends mostly on workload shape: how long requests wait on I/O, how many connections stay open, and how much CPU each request needs. The decision table below maps common situations to settings.

SituationRecommended settingReason
Many idle WebSocket clientsFew workers, high connection limitsIdle sockets cost memory, not CPU
CPU-heavy request handlingWorkers near core count, task queueOne event loop cannot use several cores
Blocking database driverAsync driver or thread pool offloadBlocking calls stall the whole loop
Behind a reverse proxyTrust proxy headers explicitlyPreserves real client IP and scheme
Zero-downtime deploysGraceful shutdown timeoutLets open requests finish before exit
Deployment decisions for typical ASGI workloads

Two settings deserve special attention. Keep-alive timeouts must be shorter on the ASGI server than on the proxy, or the proxy may reuse a socket the server has already closed, producing intermittent 502 errors. Forwarded headers such as X-Forwarded-For should be trusted only from known proxy addresses, otherwise clients can spoof their IP.

Limitations and common mistakes with ASGI

The most frequent failure is blocking the event loop. A synchronous call such as a classic database query, a time.sleep or a large JSON encode inside an async def handler pauses every connection served by that worker, so latency rises for all clients at once.

  • Mixing sync and async code carelessly: frameworks run sync views in a thread pool, which adds overhead and can exhaust threads under load.
  • Assuming async means faster: ASGI improves concurrency for I/O-bound work, not raw speed for CPU-bound code.
  • Ignoring disconnect events: long streaming responses that never check http.disconnect keep working for clients that are gone.
  • Forgetting WebSocket proxy settings: the reverse proxy must forward Upgrade and Connection headers and allow long read timeouts.
  • Holding per-connection state in memory: horizontal scaling then requires sticky sessions or a shared broker such as Redis.

ASGI also remains a community specification rather than a formal PEP standard, so extensions such as HTTP trailers or server push are optional and unevenly supported across servers. Teams relying on a specific extension should verify it in the chosen server before committing.

Explained without jargon

ASGI is an agreed set of rules that lets the program receiving internet traffic talk to the program that builds web pages, written in the Python language. Older rules handled one visitor at a time per worker, like a clerk who must finish with one customer before greeting the next.

ASGI lets one worker juggle many conversations at once, switching to whoever needs attention while others wait for data. That makes it a good fit for chat, live dashboards and notifications, where connections stay open for minutes. The key point is simple: ASGI is the plug that connects fast async servers to modern Python web frameworks.

A typical use case

A logistics company builds a live tracking dashboard with FastAPI. Dispatchers keep a WebSocket open all shift, and each truck reports its position every five seconds. The team runs Gunicorn with four Uvicorn workers on a four-core virtual machine, behind Nginx that terminates TLS and forwards WebSocket upgrades with a one-hour read timeout.

Under load testing, the stack holds about 8,000 concurrent WebSocket connections while CPU stays below 40 percent. One early problem appeared: a synchronous geocoding library froze updates for every dispatcher for several hundred milliseconds. Moving that call to a thread pool restored smooth sub-second updates, and a lifespan startup handler now opens the async database pool once per worker instead of per request.