---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
part: The request
promise: A request is a function call.
contents: entry-points, the-onion, hooks, exceptions, async-bridge, crossing-cost
---

# 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.

Look at a Django view and it reads like the simplest Python abstraction imaginable: a function takes an `HttpRequest`, does its work, and returns an `HttpResponse`. If you write `async def`, Django awaits it; if you raise `Http404`, the browser gets a clean `404` page; if you list eight dotted strings in `"MIDDLEWARE"`, they appear to run neatly in sequence around every endpoint.

Run an empty view through our newsroom project on Django `6.1.3` and Python `3.14.8`, and that "single function call" splits open into something far more surprising. On synchronous WSGI, our eight-middleware stack serves an empty ping view in **`134.5 microseconds`** with zero thread hops. Move the exact same ping to an `async def` view behind `ASGIHandler` using Django's own default seven-middleware `"startproject"` stack, and the request slows down by **`19.80x`** to **`2,663.7 microseconds`** — bouncing off the event loop onto a worker thread **fifteen separate times** before returning four bytes (`"pong"`).

## The hidden crossing tax

```text figure=crossing-tax
Zero-DB handler + middleware latency and raw asgiref bridge costs on Django 6.1.3 (Python 3.14.8, 200 requests x 5 trials)

full handler + middleware round-trip (microseconds / request, 0 to 3,000 us):
  WSGI desk/ + sync view (/ping/sync/)          0 hops     134.5 us   1.0x
  ASGI pure-async (AsyncAuditMW)                2 hops     771.7 us   5.7x
  WSGI desk/ + async view (/ping/async/)        1 hop    1,016.2 us   7.6x
  ASGI ping-pong (Async/Timing/Async)           4 hops   1,048.8 us   7.8x
  ASGI coalesced (7 built-ins + Timing bottom)  5 hops   1,283.0 us   9.5x
  ASGI desk/ stack (Timing at #2)              15 hops   2,657.0 us  19.8x
  ASGI default 7 MiddlewareMixin               15 hops   2,663.7 us  19.8x

raw asgiref bridge primitives (microseconds / call, 0 to 800 us):
  direct await noop_async()                                  0.09 us
  sync_to_async (reused ThreadSensitiveContext worker)     119.54 us
  fresh ThreadSensitiveContext + 1 sync_to_async           405.25 us
  async_to_sync from sync (new event loop + worker)        774.66 us
```

*Every bar is measured on live Django `6.1.3` (`ch03-handlers` and `ch03-bench`). Django's default seven built-in middleware classes trigger `15` thread-pool crossings per ASGI request (`2,663.7 us`). Moving one synchronous middleware to the bottom of the list drops those crossings to `5` and cuts request latency `2.08x` to `1,283.0 us`.*

Look closely at the middle of that chart, because it overturns the most common assumption engineers carry into async Django. Every built-in middleware in Django's default stack sets `async_capable = True`, yet all seven inherit from `MiddlewareMixin` (`django/utils/deprecation.py:MiddlewareMixin`). Under ASGI, `MiddlewareMixin.__acall__` does not execute natively on the event loop: it wraps `process_request` in `sync_to_async` on the way in and `process_response` in `sync_to_async` on the way out (`13` middleware hops plus `2` handler-shell hops = `15` crossings at roughly `145 us` each).

Now look two bars higher. Place a single synchronous-only middleware at the *bottom* of `"MIDDLEWARE"` — right above the view — and `BaseHandler.load_middleware`'s downward mode-coalescing rule flips all seven built-in `MiddlewareMixin` classes above it into synchronous mode (`django/core/handlers/base.py:BaseHandler.load_middleware`). Instead of bouncing off the event loop thirteen times, all eight middleware run together in one contiguous pass on the worker thread, dropping crossings from `15` to `5` and saving **`1.38 milliseconds`** on every request.

## Three machines behind the illusion

That single benchmark previews the three architectural machines this chapter unpacks from top to bottom.

First come the server-facing protocol adapters, `WSGIHandler` and `ASGIHandler`, which turn raw WSGI dictionaries or ASGI scope, receive, and send coroutines into Django requests, spool incoming request bodies to RAM or disk, cancel abandoned views when an ASGI client disconnects, and run teardown closers only after the final response byte leaves the process.

Second comes the inside-out callable onion built once at worker boot by `BaseHandler.load_middleware`, along with its inverted hook lists (`process_view`, `process_template_response`, and `process_exception`) and the per-layer `convert_exception_to_response` armor walls that guarantee an outer middleware always receives an `HttpResponse` — never a view's raw exception.

Third comes the sync/async execution bridge in `asgiref`: `BaseHandler.adapt_method_mode`, `ThreadSensitiveContext`, `SyncToAsync`, `AsyncToSync`, and `CurrentThreadExecutor` (`asgiref:asgiref/sync.py:ThreadSensitiveContext`, `asgiref:asgiref/current_thread_executor.py:CurrentThreadExecutor`). Understanding how those pieces move work across threads explains not only our `19.80x` crossing tax, but also why an in-memory SQLite database works under WSGI yet fails with `"no such table"` under ASGI, and when switching a Django service to ASGI genuinely pays off.

We begin at the outermost boundary, where a web server hands Django its first bytes, in [WSGI and ASGI entry points](handlers/entry-points.md).
