FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

ASGI Spec & High-Concurrency Servers

Low-level ASGI 3.0 protocol teardown, receive/send channels, and Uvicorn/Granian servers.

Freshness: current•15 min read•Computer Science and Programming

Key Learning Outcomes

  • ✓Understand ASGI scope and channel events
  • ✓Deploy high-concurrency async servers
Full Technical Reference Document

Mental model

Legacy synchronous WSGI binds one OS thread or worker process strictly to one HTTP request from open to EOF cleanly—collapsing immediately under long-lived SSE LLM streams and WebSockets. ASGI (Asynchronous Server Gateway Interface) replaces blocking call/return with a non-blocking single async callable app(scope, receive, send): servers like Uvicorn (libuv + httptools) or Rust-native Granian (hyper + tokio) multiplex thousands of idle streams cleanly over non-blocking event queues until CPU worker pools take over.

TCP / HTTP socket accept
Server builds scope metadata dict
Invoke async app(scope, receive, send)
Await http.request body chunks
Stream http.response.start + body events
Conceptual teaching model synthesized from:Uvicorn ASGI Server Architecture and Lifespan ReferenceFastAPI Framework Architecture & Dependency Injection SpecificationPython 3.12 AsyncIO Event Loop & Asynchronous I/O Specification

Learning outcomes

  • Trace exact ASGI 3.0 protocol event frames across scope metadata, receive() request streams, and send() streaming HTTP responses cleanly.
  • Contrast Gunicorn + Uvicorn workers (uvloop) cleanly against Rust Granian (tokio/hyper) and legacy WSGI under mixed SSE streaming and CPU serialization workloads cleanly.
  • Configure proper --workers, thread-pool offloading (sync def vs async def), HTTP keepalives, and graceful connection-draining flags (--timeout-graceful-shutdown) cleanly.

Theory

Underneath Starlette and FastAPI, every single HTTP request or WebSocket upgrade simplifies neatly into three parameters managed cleanly by the ASGI server event loop:

  1. scope (dict): Immutable per-connection metadata (scope["type"] == "http" | "websocket" | "lifespan", path, headers as byte pairs, HTTP version, client address).
  2. receive() (async callable): Yields structured inbound events incrementally ({"type": "http.request", "body": b"...", "more_body": True/False}, or "http.disconnect").
  3. send() (async callable): Emits incremental outbound response frames ("http.response.start" once cleanly with status + headers, followed strictly by one or more "http.response.body" chunks ending with "more_body": False).
Server StackCore Networking EngineSSE / Streaming & HTTP/2Worker Process ArchitectureIdeal AI Service Fit
WSGI (Gunicorn Sync)Thread/worker blocking socketsPoor (locks 1 worker per 30s stream)Process-per-request-capLegacy blocking CRUD apps only
Uvicorn (--loop uvloop)Cython libuv + httptools HTTP/1.1Excellent non-blocking SSE; relies on Nginx/Envoy for HTTP/2Single event loop per worker PID (run N = vCPUs)FastAPI backends behind Traefik/Nginx proxy
Granian (Rust Core)Multi-threaded Rust tokio + hyperNative fast HTTP/1.1 & HTTP/2 & TLS cleanlyAsync runtime + dedicated Python thread orchestrationHigh-QPS APIs cutting Cython overhead cleanly

Notice a subtle FastAPI ASGI trap: routes declared def route() run automatically inside AnyIO's worker threadpool (default 40 threads!), whereas routes declared async def route() run directly on the main ASGI event loop! Putting synchronous blocking calls (requests.get(), time.sleep(), synchronous SQLite/psycopg2 locks) inside an async def freezes all concurrent requests cleanly sharing that Uvicorn worker process cleanly!

python
import asyncio
from collections.abc import Awaitable, Callable
from typing import Any
​
Scope = dict[str, Any]
Receive = Callable[[], Awaitable[dict[str, Any]]]
Send = Callable[[dict[str, Any]], Awaitable[None]]
​
async def streaming_asgi_app(scope: Scope, receive: Receive, send: Send) -> None:
"""Raw ASGI 3.0 callable handling lifespan and incremental SSE body streaming."""
if scope["type"] == "lifespan":
while True:
msg = await receive()
if msg["type"] == "lifespan.startup":
await send({"type": "lifespan.startup.complete"})
elif msg["type"] == "lifespan.shutdown":
await send({"type": "lifespan.shutdown.complete"})
return
return
​
if scope["type"] != "http":
return
​
await send({
"type": "http.response.start",
"status": 200,
"headers": [[b"content-type", b"text/event-stream"], [b"cache-control", b"no-cache"]],
})
for chunk in (b"data: frame-1\n\n", b"data: frame-2\n\n"):
await send({"type": "http.response.body", "body": chunk, "more_body": True})
await asyncio.sleep(0.01)
await send({"type": "http.response.body", "body": b"", "more_body": False})

Trade-offs

Using multi-worker ASGI (Granian or Gunicorn managing UvicornWorker processes alongside --loop uvloop and --http httptools) achieves massive C10K open-connection density for LLM SSE streams with minimal per-stream RAM compared to synchronous multi-thread WSGI servers. However, shared single-threaded loops per worker demand strict non-blocking I/O discipline (httpx, asyncpg) across every async def handler, explicit lifespan DB pool cleanup, and configured --timeout-graceful-shutdown buffers so Kubernetes rolling deployments never slice active 20-second streams abruptly cleanly.

Failure modes and misconceptions

  • Putting Blocking Calls Inside async def Endpoints: Invoking synchronous psycopg2, requests, or heavy Pydantic loops inside an async def halts every single concurrent SSE user attached to that Uvicorn PID cleanly until completion.
  • Wrapping Starlette / FastAPI With Legacy WSGI Middlewares: Passing blocking WSGI middleware classes cleanly breaks coroutine yields (await receive()) and crashes ASGI startup cleanly.
  • Forgetting Closing more_body: False or http.response.body: Emitting headers (http.response.start) cleanly then hitting unhandled errors before emitting a terminal body frame leaves HTTP clients hanging indefinitely cleanly.
  • Running Uvicorn --workers 1 Without Multi-Process Scaling or Lifespan Cleanups: Locking all Python requests onto one single GIL core starves JSON parsing under heavy throughput bursts cleanly.

Decision scenario

A production FastAPI LLM gateway deploys behind Traefik cleanly handling 1,500 concurrent SSE streams plus frequent PostgreSQL audit writes. Occasionally latency freezes completely across every user for 3 seconds during PDF uploads, and deploys kill active chats mid-stream. Replace synchronous pypdf/requests calls inside async def via asyncio.to_thread() / httpx, run multi-worker Uvicorn/Granian matched to CPU count, and configure graceful ASGI shutdown drains cleanly.

Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next