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

FastAPI Custom ASGI Middleware

Request processing chains, correlation IDs, ContextVars, and response header mutation.

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

Key Learning Outcomes

  • ✓Build custom ASGI HTTP middlewares
  • ✓Track correlation IDs safely with ContextVars
Full Technical Reference Document

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.

ASGI ingress socket
Outer middleware sets ContextVar token
Inner auth/rate middlewares evaluate
Route / SSE streams chunks via send()
Finally block resets ContextVar & logs timing
Conceptual teaching model synthesized from:FastAPI Framework Architecture & Dependency Injection SpecificationUvicorn ASGI Server Architecture and Lifespan ReferenceOpenTelemetry Traces specification

Learning outcomes

  • Contrast lightweight pure ASGI middleware (__call__(scope, receive, send)) cleanly against Starlette BaseHTTPMiddleware under 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 with try...finally: var.reset(token).

Theory

Two subtle FastAPI behaviors catch experienced backend engineers immediately cleanly when scaling AI gateways:

  1. Starlette BaseHTTPMiddleware Stream Buffering: Decorating @app.middleware("http") invokes Starlette's BaseHTTPMiddleware, which historically wraps responses inside memory iterators/AnyIO task barriers—breaking streaming ContextVar propagation across generators cleanly, inflating RAM on multi-megabyte downloads cleanly, and intermittently introducing micro-stalls onto token-by-token EventSourceResponse streams cleanly! Writing a tiny pure ASGI middleware wraps send cleanly in-place with zero buffering tax.
  2. Reverse LIFO Execution Ordering: Calling app.add_middleware(First); app.add_middleware(Second) places Second outermost cleanly (Second -> First -> Route -> First -> Second). Putting CORSMiddleware inside an auth blocker drops Access-Control-Allow-Origin headers cleanly on HTTP 401 / 403 errors—making frontend browsers hide readable error messages cleanly! Always add CORS and global timing/correlation middleware last so they wrap outermost cleanly.
MechanismExecution ScopeSSE Token Streaming ImpactBest Production Role
Pure ASGI MiddlewareAll HTTP & WebSocket endpoints globally cleanlyZero buffering, passes chunks straight to Uvicorn socketRequest 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 tasksSimple internal non-streaming CRUD APIs cleanly
Route Depends(...)Targeted routes / router groups cleanlyFull zero-overhead pre-handler run; clean yield teardownAuth JWT decode, tenant DB RLS setup, RBAC scopes
python
import time
import uuid
from contextvars import ContextVar
from collections.abc import Awaitable, Callable
from typing import Any
​
correlation_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 = app
​
async 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)
return
​
headers_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.0
headers = 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 IDs
correlation_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: Inspecting response.body or wrapping call_next() carelessly breaks streaming TTFT and risks EndOfStream / anyio task group errors cleanly under client disconnects.
  • Inverted Middleware Order Dropping CORS Headers on 401/500: Adding an Auth/Rate-Limit middleware after CORSMiddleware wraps auth outside CORS, returning browser-blocked CORS errors on auth rejection cleanly!
  • Forgetting ContextVar.reset(token) in finally: 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.

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