← Back to FastAPI, page 5

fastapi-0091 · Hard senior

What is the difference between pure ASGI middleware and BaseHTTPMiddleware in FastAPI, and why do contextvars and streaming behave differently?

BaseHTTPMiddleware is a convenience wrapper (dispatch(request, call_next)) that runs the downstream app in a separate task, which is why context variables set in the endpoint do not reach the middleware after call_next, and why it adds overhead and complicates streaming and background tasks. Pure ASGI middleware, a class with async __call__(scope, receive, send), runs in the same task and context, adds minimal overhead, and gives full control, at the cost of more code.

Full answer

Two ways to write middleware:

python
# 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_next runs the downstream app in a separate task connected by memory streams. A ContextVar set in the middleware before call_next is visible downstream (the task copies the context), but a value set inside the endpoint is not visible after call_next returns, 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 BaseHTTPMiddleware exceptions from the app propagate through call_next; with pure ASGI you must wrap send yourself to modify headers or status after the app has started responding.
  • Only HTTP: BaseHTTPMiddleware does not handle websockets; pure ASGI sees scope["type"] of http, websocket and lifespan.

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.

python
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