3.2 Handlers, middleware, and async
Building the middleware onion
How does BaseHandler turn settings into a single nested callable, and why does order invert on the way out?
In "desk.settings", "MIDDLEWARE" looks like a flat list of eight strings — "SecurityMiddleware" at index 0, our custom timing layer at index 1, down to "XFrameOptionsMiddleware" at index 7. Developers often picture Django looping over that list on every request: call middleware 0, then 1, then 2, call the view, then loop backward from 7 to 0.
Django does not loop over "MIDDLEWARE" during a request at all. At worker startup, BaseHandler collapses the entire list once into a single nested callable — the middleware chain — and stores the outermost wrapper on _middleware_chain. When a request arrives, BaseHandler makes one Python call directly into BaseHandler.
Walking MIDDLEWARE backwards
To build an onion from the inside out, BaseHandler starts at the core and wraps outward. On lines 38–41 of django/, it chooses either BaseHandler (is_async=False) or BaseHandler (is_async=True), wraps that core callable inside convert_exception_to_response, and then iterates reversed(settings.
On each iteration, Django performs six operations in strict order:
- Imports the middleware factory via
import_string(middleware_path). - Reads its mode capability flags, defaulting to
sync_capable = Trueandasync_capable = False. If both areFalse, it aborts startup immediately withRuntimeError. - Decides whether this layer should run sync or async (
"middleware_is_async"), and callsBaseHandlerto wrap the inner.adapt_method_mode handlerinsync_to_asyncorasync_to_syncif the inner callable is in the opposite mode. - Instantiates the middleware by passing the adapted inner handler to the factory. If the constructor raises
MiddlewareNotUsed, Django logs a debug message (whensettings.DEBUGisTrue) and skips to the next entry without alteringhandler. If a factory returnsNoneinstead of a callable, Django raisesImproperlyConfigured. - Inspects the new middleware instance for three optional hook methods —
process_view,process_template_response, andprocess_exception— and registers them in three sidecar lists on the handler. - Wraps the new middleware instance inside
convert_exception_to_response(mw_instance)and makes that wrapped callable the new innerhandlerfor the next outer ring.
After the loop finishes index 0, line 101 adapts the outermost callable one last time to match the handler’s own mode (is_async), and line 104 assigns self. Notice the comment right above line 104: Django deliberately waits until every layer and hook list is complete before assigning _middleware_chain, because callers inspect self as a thread-safe readiness flag.
Inspecting the live chain on our newsroom project
Run BaseHandler on our eight-entry newsroom configuration under both WSGIHandler and ASGIHandler and walk the resulting closures from outermost to innermost:
desk/ MIDDLEWARE capabilities and BaseHandler.load_middleware construction
index middleware mixin sync async hooks
0 SecurityMiddleware True True True process_request,process_response
1 TimingHeaderMiddleware False True False (direct __call__)
2 SessionMiddleware True True True process_request,process_response
3 CommonMiddleware True True True process_request,process_response
4 CsrfViewMiddleware True True True process_request,process_view,process_response
5 AuthenticationMiddleware True True True process_request
6 MessageMiddleware True True True process_request,process_response
7 XFrameOptionsMiddleware True True True process_response
WSGI load_middleware(is_async=False):
adaptations (0):
hooks: _view_middleware=1 _template_response_middleware=0 _exception_middleware=0
outer->inner chain:
00. SecurityMiddleware async_mode=False
01. TimingHeaderMiddleware (sync-only)
02. SessionMiddleware async_mode=False
03. CommonMiddleware async_mode=False
04. CsrfViewMiddleware async_mode=False
05. AuthenticationMiddleware async_mode=False
06. MessageMiddleware async_mode=False
07. XFrameOptionsMiddleware async_mode=False
08. BaseHandler._get_response
ASGI load_middleware(is_async=True):
adaptations (3):
adapt(CsrfViewMiddleware.process_view): SyncToAsync
adapt(middleware desk.middleware.TimingHeaderMiddleware): AsyncToSync
adapt(convert_exception_to_response.<locals>.inner): SyncToAsync
hooks: _view_middleware=1 _template_response_middleware=0 _exception_middleware=0
outer->inner chain:
00. SyncToAsync(thread_sensitive=True)
01. SecurityMiddleware async_mode=False
02. TimingHeaderMiddleware (sync-only)
03. AsyncToSync(thread_sensitive=-)
04. SessionMiddleware async_mode=True
05. CommonMiddleware async_mode=True
06. CsrfViewMiddleware async_mode=True
07. AuthenticationMiddleware async_mode=True
08. MessageMiddleware async_mode=True
09. XFrameOptionsMiddleware async_mode=True
10. BaseHandler._get_response_async
Look at two things in that trace. First, why does middleware order invert on the way out? There is no reverse loop at request time. Because index 0 (SecurityMiddleware) holds index 1 as its get_response, which holds index 2, down to BaseHandler, calling BaseHandler simply pushes eight Python stack frames onto the call stack. Code before calling get_response executes top-to-bottom (0 -> 7); once the core returns an HttpResponse, those frames unwind in strict last-in, first-out order (7 -> 0), executing every layer’s post-view code automatically in reverse!
Second, look at layers 01 through 04 in the ASGI chain. Because load_middleware walks from index 7 up to index 0, XFrameOptionsMiddleware through SessionMiddleware all saw an async inner handler and entered async_mode=True. When the loop reached index 1 (our synchronous-only timing middleware), Django wrapped SessionMiddleware in AsyncToSync and flipped "handler_is_async" to False. Then, at index 0, SecurityMiddleware saw handler_is_async = False and chose async_mode=False to stay synchronous with the layer beneath it — leaving line 101 to add one SyncToAsync(thread_sensitive=True) cap at the very top. We will return to that coalescing rule in Sync and async inside one chain, because it turns out to be worth over a millisecond per request.
Why the three sidecar lists insert at opposite ends
During that same reverse walk (lines 79–95 of django/), Django populates three lists on BaseHandler:
BaseHandleruses._view_middleware list. Because the loop runs bottom-to-top (.insert(0, ...) 7 -> 0), inserting at index0reverses the reverse loop back into top-to-bottom declaration order (0 -> 7). In our newsroom project,CsrfViewMiddlewareis the lone entry, adapted to.process_view SyncToAsyncunder ASGI.BaseHandleruses._template_response_middleware list.append(...), keeping the reverse order (7 -> 0) so template responses pass outward from innermost middleware to outermost.BaseHandleralso uses._exception_middleware list.append(...)(innermost to outermost), and notice line 94:BaseHandleris called with.adapt_method_mode is_async=Falseon everyprocess_exceptionhook. Even onASGIHandler, Django explicitly adaptsprocess_exceptionhooks to synchronous mode (is_async=False), becauseBaseHandleris still a synchronous loop invoked via.process_exception_by_middleware sync_to_asyncfrom_get_response_async.
Finally, all three boot-time guardrails behave deterministically when middleware factories misbehave:
load_middleware edge cases: MiddlewareNotUsed, None factory, invalid flags
MiddlewareNotUsed -> silently skipped; top callable wraps BaseHandler._get_response
returns_none_factory -> ImproperlyConfigured: Middleware factory ch03_edge_mw.returns_none_factory returned None.
NeitherModeMW -> RuntimeError: Middleware ch03_edge_mw.NeitherModeMW must have at least one of sync_capable/async_capable set to True.
Where the onion leaks
Because BaseHandler runs once when the handler is constructed, every middleware instance is a process-wide singleton shared across all concurrent threads (under threaded WSGI) and all concurrent coroutines (under ASGI).
That single fact produces one of the nastiest silent bugs in production Django: storing per-request state on self (for example, self or self) instead of on local variables or request. Under local single-user "runserver", it looks completely fine; under concurrent production traffic, Request B overwrites "self while Request A is waiting on the database, leaking one user’s state into another user’s response. Every piece of per-request state belongs either in local variables inside __call__ or attached to request, never on self.
Now that we have the onion built, let’s trace what happens when a middleware uses MiddlewareMixin hooks — or returns a response early without ever calling the view — in MiddlewareMixin and short-circuits.