---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# Building the middleware onion

How does `BaseHandler.load_middleware` turn `settings.MIDDLEWARE` 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.load_middleware` (`django/core/handlers/base.py:BaseHandler.load_middleware`) collapses the entire list once into a single nested callable — the **middleware chain** — and stores the outermost wrapper on **`_middleware_chain`** (`django/core/handlers/base.py:BaseHandler._middleware_chain`). When a request arrives, `BaseHandler.get_response` makes *one* Python call directly into `BaseHandler._middleware_chain`.

## Walking `MIDDLEWARE` backwards

To build an onion from the inside out, `BaseHandler.load_middleware` starts at the core and wraps outward. On lines 38–41 of `django/core/handlers/base.py`, it chooses either `BaseHandler._get_response` (`is_async=False`) or `BaseHandler._get_response_async` (`is_async=True`), wraps that core callable inside `convert_exception_to_response`, and then iterates `reversed(settings.MIDDLEWARE)`.

On each iteration, Django performs six operations in strict order:

1. Imports the middleware factory via `import_string(middleware_path)` (`django/utils/module_loading.py:import_string`).
2. Reads its mode capability flags, defaulting to `sync_capable = True` and `async_capable = False`. If both are `False`, it aborts startup immediately with `RuntimeError`.
3. Decides whether *this* layer should run sync or async (`"middleware_is_async"`), and calls `BaseHandler.adapt_method_mode` (`django/core/handlers/base.py:BaseHandler.adapt_method_mode`) to wrap the inner `handler` in `sync_to_async` or `async_to_sync` if the inner callable is in the opposite mode.
4. Instantiates the middleware by passing the adapted inner handler to the factory. If the constructor raises `MiddlewareNotUsed` (`django/core/exceptions.py:MiddlewareNotUsed`), Django logs a debug message (when `settings.DEBUG` is `True`) and skips to the next entry without altering `handler`. If a factory returns `None` instead of a callable, Django raises `ImproperlyConfigured`.
5. Inspects the new middleware instance for three optional hook methods — `process_view`, `process_template_response`, and `process_exception` — and registers them in three sidecar lists on the handler.
6. Wraps the new middleware instance inside `convert_exception_to_response(mw_instance)` and makes *that* wrapped callable the new inner `handler` for 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._middleware_chain = handler`. 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._middleware_chain is None` as a thread-safe readiness flag.

## Inspecting the live chain on our newsroom project

Run `BaseHandler.load_middleware` on our eight-entry newsroom configuration under both `WSGIHandler` and `ASGIHandler` and walk the resulting closures from outermost to innermost:

```text recording=ch03-handlers
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._get_response`, calling `BaseHandler._middleware_chain` 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](async-bridge.md), 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/core/handlers/base.py`), Django populates three lists on `BaseHandler`:

- `BaseHandler._view_middleware` uses `list.insert(0, ...)`. Because the loop runs bottom-to-top (`7 -> 0`), inserting at index `0` reverses the reverse loop back into top-to-bottom declaration order (`0 -> 7`). In our newsroom project, `CsrfViewMiddleware.process_view` is the lone entry, adapted to `SyncToAsync` under ASGI.
- `BaseHandler._template_response_middleware` uses `list.append(...)`, keeping the reverse order (`7 -> 0`) so template responses pass outward from innermost middleware to outermost.
- `BaseHandler._exception_middleware` also uses `list.append(...)` (innermost to outermost), and notice line 94: `BaseHandler.adapt_method_mode` is called with `is_async=False` on every `process_exception` hook. Even on `ASGIHandler`, Django explicitly adapts `process_exception` hooks to **synchronous** mode (`is_async=False`), because `BaseHandler.process_exception_by_middleware` (`django/core/handlers/base.py:BaseHandler.process_exception_by_middleware`) is still a synchronous loop invoked via `sync_to_async` from `_get_response_async`.

Finally, all three boot-time guardrails behave deterministically when middleware factories misbehave:

```text recording=ch03-handlers
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.load_middleware` 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.started = time.perf_counter()` or `self.current_tenant = tenant`) instead of on local variables or `request`. Under local single-user `"runserver"`, it looks completely fine; under concurrent production traffic, Request B overwrites `"self.current_tenant"` 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](hooks.md).
