Under The Hood
backend fastapi FastAPI 0.100+ (Starlette / ASGI 3.0)

Starlette Middleware Stack: ASGI Request Pipeline and Exception Handlers

Last updated
Prerequisites:
ASGI specification (`scope`, `receive`, `send`)
FastAPI architecture
  • fastapi
  • starlette
  • asgi
  • middleware
  • routing
  • pipeline

Read at your depth

The practical view

FastAPI is built directly on top of **Starlette**. Starlette handles the low-level ASGI request/response pipeline, HTTP routing, WebSockets, static file serving, and middleware. You add middleware using `@app.middleware('http')`: `async def add_process_time_header(request: Request, call_next): response = await call_next(request); return response`. Middleware executes in an onion-like stack (First-In, Last-Out).

The same idea in other frameworks

fastapi equivalent
Starlette ASGI middleware `async def (request, call_next)`.

Legacy vs modern

Raw WSGI Interception vs Starlette ASGI Async Middleware

WSGI middleware blocked synchronous threads; Starlette ASGI middleware runs non-blocking asynchronous request/response pipelines.

before → after
Legacy WSGI Middleware (Flask)
def __call__(self, environ, start_response): ... // ❌ Synchronous WSGI blocking
Starlette Async ASGI Middleware
@app.middleware('http') async def add_timing(req, call_next): ... // ✅ NEW: Non-blocking async

Interview gotchas

Context

Interviewers test your knowledge of ASGI stream buffering gotchas.

The mechanical answer

`BaseHTTPMiddleware` (which powers `@app.middleware('http')`) abstracts request/response streams by buffering and wrapping them in an internal task group. In high-concurrency or large streaming response workloads, this introduces memory overhead and context switching. For extreme performance or SSE/WebSocket streaming, write a **pure ASGI middleware class** implementing `async def __call__(self, scope, receive, send)` directly.

Trap

`BaseHTTPMiddleware` can break background tasks or streaming responses if not carefully handled.

Under The Hood — a multi-depth technical interview hub.

Third-party licenses Press ⌘ K to search.