Full answer
Two ways to write middleware:
# convenience
class Timing(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
response = await call_next(request)
return response
# pure ASGI
class Timing:
def __init__(self, app): self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
return await self.app(scope, receive, send)
...
await self.app(scope, receive, send_wrapper)Differences:
- Task boundary:
BaseHTTPMiddleware.call_nextruns the downstream app in a separate task connected by memory streams. AContextVarset in the middleware beforecall_nextis visible downstream (the task copies the context), but a value set inside the endpoint is not visible aftercall_nextreturns, because it lives in the other task's context. Pure ASGI middleware calls the app in the same task, so changes are visible both ways (for async endpoints; sync endpoints run in a thread with a copied context). - Performance: the extra task and stream cost per request; pure ASGI is leaner, which matters for high-throughput services.
- Streaming and disconnects: the wrapper buffers or proxies body streams; reading
request.body()in the middleware and then letting the endpoint read it needs care (modern Starlette handles it better but it remains subtle). Background tasks run after the response, and the wrapper's handling of them has had edge cases. - Exceptions: with
BaseHTTPMiddlewareexceptions from the app propagate throughcall_next; with pure ASGI you must wrapsendyourself to modify headers or status after the app has started responding. - Only HTTP:
BaseHTTPMiddlewaredoes not handle websockets; pure ASGI seesscope["type"]ofhttp,websocketandlifespan.
Guidelines: use BaseHTTPMiddleware for simple request-in/response-out logic where you do not need contextvars written downstream or streaming control (adding a header, simple auth gate). Use pure ASGI for request IDs and logging context that downstream code writes, tracing, body size limits, compression, anything performance sensitive or streaming. Libraries like asgi-correlation-id and Starlette's own middleware (CORS, GZip, TrustedHost) are pure ASGI for these reasons.
Order matters: middleware added last runs outermost; exception handlers and ServerErrorMiddleware sit at the edges.
import asyncio
from contextvars import ContextVar
from fastapi import FastAPI
from starlette.middleware.base import BaseHTTPMiddleware
request_id = ContextVar("request_id", default=None)
user = ContextVar("user", default=None)
seen = {}
class SimpleMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
request_id.set("req-1") # set before the app runs
response = await call_next(request)
seen["basehttp: user visible after call_next"] = user.get()
return response
class PureMiddleware:
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
return await self.app(scope, receive, send)
request_id.set("req-1")
await self.app(scope, receive, send)
seen["pure asgi: user visible after the app"] = user.get()
def build(middleware_class):
app = FastAPI()
@app.get("/who")
async def who():
seen["endpoint sees request_id"] = request_id.get()
user.set("asha") # written downstream
return {"ok": True}
app.add_middleware(middleware_class)
return app
async def call(app):
scope = {"type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": "GET", "scheme": "http",
"path": "/who", "raw_path": b"/who", "query_string": b"", "headers": [], "server": ("t", 80),
"client": ("127.0.0.1", 1), "root_path": ""}
async def receive():
return {"type": "http.request", "body": b"", "more_body": False}
async def send(message):
pass
await app(scope, receive, send)
for cls in (SimpleMiddleware, PureMiddleware):
seen.clear()
user.set(None)
asyncio.run(call(build(cls)))
print(cls.__name__, seen)
Standalone script. Run it with `python file.py`; it drives the ASGI app directly. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): SimpleMiddleware {'endpoint sees request_id': 'req-1', 'basehttp: user visible after call_next': None} PureMiddleware {'endpoint sees request_id': 'req-1', 'pure asgi: user visible after the app': 'asha'}
Key points
- BaseHTTPMiddleware runs the app in a separate task
- ContextVars set in middleware reach the endpoint; values set in the endpoint do not come back
- Pure ASGI shares the task and context, with less overhead
- Use pure ASGI for streaming, contextvars written downstream and performance
- BaseHTTPMiddleware is HTTP-only and simpler to write
Common mistakes
- Expecting ContextVars set in endpoints to be visible in BaseHTTPMiddleware
- Using BaseHTTPMiddleware for streaming or high-throughput paths
- Forgetting to pass non-http scopes through in pure ASGI middleware
- Assuming middleware order is first added, first run
- Reading the body in middleware without restoring it for the endpoint
Follow-ups
- How do you wrap send to add a response header in pure ASGI?
- How does middleware order work in Starlette?
- Why is request ID logging usually pure ASGI?
Tips
- Explain the extra task
- Describe the contextvar effect
- Give guidance on when to use each