Mental model
FastAPI middlewares execute as an onion-layered chain cleanly surrounding every incoming ASGI call (scope, receive, send): requests peel inward through outer wrappers down into matched route handlers cleanly while responses unwind back outward cleanly. Mastering LIFO registration order, raw ASGI pass-through classes (never buffering SSE chunks unlike BaseHTTPMiddleware), and contextvars.ContextVar async task isolation stops silent token stalls and cross-request trace leakage cleanly.
Learning outcomes
- Contrast lightweight pure ASGI middleware (
__call__(scope, receive, send)) cleanly against StarletteBaseHTTPMiddlewareunder real-time LLM Server-Sent Events streaming cleanly. - Predict exact LIFO onion registration ordering cleanly so outer CORS and exception correlation middlewares stay intact cleanly even when inner auth rejects
HTTP 401. - Propagate request correlation IDs and tenant context cleanly across async coroutines using
ContextVar.set()paired deterministically withtry...finally: var.reset(token).
Theory
Two subtle FastAPI behaviors catch experienced backend engineers immediately cleanly when scaling AI gateways:
- Starlette
BaseHTTPMiddlewareStream Buffering: Decorating@app.middleware("http")invokes Starlette'sBaseHTTPMiddleware, which historically wraps responses inside memory iterators/AnyIO task barriers—breaking streamingContextVarpropagation across generators cleanly, inflating RAM on multi-megabyte downloads cleanly, and intermittently introducing micro-stalls onto token-by-tokenEventSourceResponsestreams cleanly! Writing a tiny pure ASGI middleware wrapssendcleanly in-place with zero buffering tax. - Reverse LIFO Execution Ordering: Calling
app.add_middleware(First); app.add_middleware(Second)placesSecondoutermost cleanly (Second -> First -> Route -> First -> Second). PuttingCORSMiddlewareinside an auth blocker dropsAccess-Control-Allow-Originheaders cleanly onHTTP 401 / 403errors—making frontend browsers hide readable error messages cleanly! Always add CORS and global timing/correlation middleware last so they wrap outermost cleanly.
| Mechanism | Execution Scope | SSE Token Streaming Impact | Best Production Role |
|---|---|---|---|
| Pure ASGI Middleware | All HTTP & WebSocket endpoints globally cleanly | Zero buffering, passes chunks straight to Uvicorn socket | Request IDs, edge timing, OpenTelemetry spans, CORS |
@app.middleware("http") (BaseHTTPMiddleware) | All HTTP routes (skips WebSockets or wraps streams) | Can buffer/wrap streams & break ContextVar scopes in async tasks | Simple internal non-streaming CRUD APIs cleanly |
Route Depends(...) | Targeted routes / router groups cleanly | Full zero-overhead pre-handler run; clean yield teardown | Auth JWT decode, tenant DB RLS setup, RBAC scopes |
pythonimport timeimport uuidfrom contextvars import ContextVarfrom collections.abc import Awaitable, Callablefrom typing import Anycorrelation_id_ctx: ContextVar[str] = ContextVar("correlation_id", default="")ASGIApp = Callable[[dict[str, Any], Callable, Callable], Awaitable[None]]class PureAsgiCorrelationMiddleware:"""Zero-buffering pure ASGI middleware safe for SSE token streams and WebSockets."""def __init__(self, app: ASGIApp) -> None:self.app = appasync def __call__(self, scope: dict[str, Any], receive: Callable, send: Callable) -> None:if scope["type"] not in ("http", "websocket"):await self.app(scope, receive, send)returnheaders_dict = {k.lower(): v for k, v in scope.get("headers", [])}req_id = headers_dict.get(b"x-request-id", b"").decode() or str(uuid.uuid4())token = correlation_id_ctx.set(req_id)start_ns = time.perf_counter_ns()async def send_with_headers(message: dict[str, Any]) -> None:if message["type"] == "http.response.start":elapsed_ms = (time.perf_counter_ns() - start_ns) / 1_000_000.0headers = list(message.get("headers", []))headers.append([b"x-request-id", req_id.encode("ascii")])headers.append([b"x-latency-ms", f"{elapsed_ms:.2f}".encode("ascii")])message = {**message, "headers": headers}await send(message)try:await self.app(scope, receive, send_with_headers)finally:# Always reset inside finally so pooled sync threads or subsequent ticks never leak IDscorrelation_id_ctx.reset(token)
Trade-offs
Pure ASGI middleware classes keep latency nearly zero (microseconds per call), forward infinite SSE / WebSocket frames untouched without RAM copies, and work uniformly across HTTP and WebSockets cleanly—trading away the convenient Request / Response object wrapper (forcing direct byte-header parsing unless lightweight Starlette Headers(scope=scope) helpers wrap them cleanly). Meanwhile, keeping authentication, tenant permissions, and database transactions inside route-scoped Depends(...) functions rather than bloated global middlewares avoids checking heavy SQL grants unnecessarily cleanly across static /health probes cleanly.
Failure modes and misconceptions
- Buffering LLM SSE Streams Inside
BaseHTTPMiddleware: Inspectingresponse.bodyor wrappingcall_next()carelessly breaks streamingTTFTand risksEndOfStream/anyiotask group errors cleanly under client disconnects. - Inverted Middleware Order Dropping CORS Headers on 401/500: Adding an Auth/Rate-Limit middleware after
CORSMiddlewarewraps auth outside CORS, returning browser-blocked CORS errors on auth rejection cleanly! - Forgetting
ContextVar.reset(token)infinally: Reusing worker threads or custom loop callbacks leaks User A's correlation/tenant trace identifiers straight onto User B's subsequent log lines cleanly. - Putting Expensive DB Lookups Globally Ahead of
/health: Performing Postgres session acquisition inside global middleware drags down Kubernetes liveness probe responsiveness completely under DB stalls cleanly.
Decision scenario
A FastAPI streaming copilot reports browser CORS errors strictly on HTTP 401 rejections (working fine on 200s), sluggish buffered SSE token arrival, and occasional swapped request_id values across worker threads. Fix registration ordering so CORSMiddleware wraps outermost cleanly, convert timing/request-ID logging cleanly onto a pure ASGI send wrapper cleanly (never BaseHTTPMiddleware), reset ContextVar tokens inside finally, and keep JWT auth cleanly inside route Depends() cleanly.