← Back to Django, page 5

django-0085 · Hard senior

How do you write production-grade Django middleware that works in both sync and async mode, handles exceptions and short-circuits requests?

A middleware is a callable factory: __init__(get_response) and __call__(request). To work under both WSGI and ASGI, declare sync_capable and async_capable and, when get_response is a coroutine function, mark the instance with markcoroutinefunction and provide an async __call__. process_view and process_exception hooks add finer control, and returning a response early short-circuits the chain. Avoid blocking calls inside async middleware, because Django will otherwise adapt sync code through a thread pool at a cost.

Full answer

Django wraps middleware so that each layer can be sync or async. When a layer's mode differs from the next one, Django adapts through sync_to_async or async_to_sync threads, which adds overhead. So the best design is a middleware that is natively both.

Pattern:

python
class TimingMiddleware:
    sync_capable = True
    async_capable = True

    def __init__(self, get_response):
        self.get_response = get_response
        if iscoroutinefunction(get_response):
            markcoroutinefunction(self)

    def __call__(self, request):
        if iscoroutinefunction(self):
            return self.__acall__(request)
        ...
        return self.get_response(request)

    async def __acall__(self, request):
        ...
        return await self.get_response(request)

The @sync_and_async_middleware decorator offers function-style middleware with the same effect.

Hooks and flow:

  • __call__: code before get_response runs on the way in, code after on the way out. Returning a response without calling get_response short-circuits: later middleware and the view never run (maintenance mode, rate limiting, IP blocks).
  • process_view(request, view_func, args, kwargs): runs just before the view, after URL resolution; useful for per-view rules via decorators.
  • process_exception(request, exception): called when a view raises; return a response to handle it, or None to continue. It does not see exceptions raised in other middleware.
  • process_template_response: for responses with render().

Production rules: keep it fast (it runs for every request), do not read the body unless necessary (it breaks streaming and upload handlers), avoid blocking I/O in async mode, order carefully in MIDDLEWARE (security and sessions before auth), and keep per-request state on request or a ContextVar, never on the middleware instance (it is shared across requests).

Check adaptation with DEBUG logging: Django logs a debug line when it adapts a middleware to a different mode.

python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    ROOT_URLCONF=__name__,
    MIDDLEWARE=["__main__.Guard", "__main__.Timing"],
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

import asyncio
from asgiref.sync import iscoroutinefunction, markcoroutinefunction

from django.http import HttpResponse, JsonResponse
from django.test import AsyncClient, Client
from django.urls import path

trace = []


class Guard:
    """Short-circuits requests that carry X-Maintenance and turns view errors into JSON."""
    sync_capable = True
    async_capable = True

    def __init__(self, get_response):
        self.get_response = get_response
        if iscoroutinefunction(get_response):
            markcoroutinefunction(self)

    def __call__(self, request):
        if iscoroutinefunction(self):
            return self.__acall__(request)
        if "X-Maintenance" in request.headers:
            return HttpResponse("down for maintenance", status=503)
        return self.get_response(request)

    async def __acall__(self, request):
        if "X-Maintenance" in request.headers:
            return HttpResponse("down for maintenance", status=503)
        return await self.get_response(request)

    def process_exception(self, request, exception):
        trace.append(f"process_exception: {type(exception).__name__}")
        return JsonResponse({"error": "bad request data"}, status=400)


class Timing:
    sync_capable = True
    async_capable = True

    def __init__(self, get_response):
        self.get_response = get_response
        self.is_async = iscoroutinefunction(get_response)
        if self.is_async:
            markcoroutinefunction(self)

    def __call__(self, request):
        if self.is_async:
            return self.__acall__(request)
        trace.append("Timing (sync path)")
        return self.get_response(request)

    async def __acall__(self, request):
        trace.append("Timing (async path)")
        return await self.get_response(request)


def hello(request):
    return HttpResponse("hello")


def broken(request):
    raise ValueError("bad value")


async def ahello(request):
    return HttpResponse("hello from async view")


urlpatterns = [path("hello/", hello), path("broken/", broken), path("ahello/", ahello)]

c = Client()
print(c.get("/hello/").status_code, c.get("/hello/", headers={"X-Maintenance": "1"}).status_code)
print(c.get("/broken/").json())
print(trace)
trace.clear()


async def main():
    ac = AsyncClient()
    r = await ac.get("/ahello/")
    print(r.status_code, r.content)
    r = await ac.get("/ahello/", headers={"X-Maintenance": "1"})
    print(r.status_code)


asyncio.run(main())
print(trace)

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. The middleware classes live in the same file and are referenced through __main__. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): 200 503 {'error': 'bad request data'} ['Timing (sync path)', 'Timing (sync path)', 'process_exception: ValueError'] 200 b'hello from async view' 503 ['Timing (async path)']

Key points

  • Declare sync_capable and async_capable; mark coroutine instances
  • Returning a response early short-circuits the stack
  • process_exception can turn view errors into responses
  • Never store per-request state on the middleware instance
  • Avoid blocking calls in async middleware

Common mistakes

  • Writing sync-only middleware and silently forcing thread adaptation on async stacks
  • Storing request data on self in the middleware instance
  • Reading request.body in middleware and breaking streaming uploads
  • Putting authentication-dependent middleware before SessionMiddleware

Follow-ups

  • How does process_view differ from decorating a view?
  • What happens to middleware order on the response path?
  • How do you test middleware in isolation with RequestFactory?

Tips

  • Explain sync_capable and async_capable
  • Describe short-circuiting
  • Warn about instance state