---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
part: The request
promise: "A request is a function call."
---

# Handlers, middleware, and async

A `WSGIHandler` or `ASGIHandler` turns a flat list of middleware strings into a nested chain of callables around the view, trapping exceptions at every layer and bridging sync and async across threads.

Django never opens a listening socket. A server owns the wire and hands each request to a single callable object: the **handler**. When that handler starts, `BaseHandler.load_middleware` builds `BaseHandler._middleware_chain` from the inside out, wrapping the centre view resolver in each layer listed in `settings.MIDDLEWARE` (`django/core/handlers/base.py:BaseHandler.load_middleware`).

## The onion and its boundaries

Each middleware layer receives a request on the way in, invokes the inner callable, and inspects or replaces the response on the way out. Because `BaseHandler.load_middleware` wraps every layer separately in `convert_exception_to_response`, an unhandled exception inside one layer becomes an HTTP response before the outer layer ever sees it (`django/core/handlers/exception.py:convert_exception_to_response`).

> **Why.** Wrapping each boundary individually guarantees that outer middleware — security headers, session saving, response compression — still run on error responses rather than being skipped by a bubbling traceback.

## Crossing between event loop and thread

Under `ASGIHandler`, synchronous middleware and synchronous views cannot run directly on the event loop without blocking every other connection (`django/core/handlers/asgi.py:ASGIHandler`). Django inspects `sync_capable` and `async_capable` on each layer and adapts mismatches with `sync_to_async` or `async_to_sync` (`django/core/handlers/base.py:BaseHandler.adapt_method_mode`). Each mode change along the chain crosses between the event loop and a worker thread, turning an invisible middleware ordering choice into measurable request latency.
