Django 6.1.3

3.6 Handlers, middleware, and async

Measuring the thread-pool crossing

How much latency do sync/async mode switches actually add under ASGI, and how many crossings does a default Django middleware stack trigger?

Now that we can count every mode crossing — a single transition across SyncToAsync or AsyncToSync between an asyncio event-loop thread and a synchronous thread — we can put exact microsecond prices on each one. All three benchmarks below ran on Django 6.1.3 and Python 3.14.8 with zero tracing instrumentation active, taking the median of five timed trials after warm-up (ch03-bench).

What one raw crossing costs

Before running a full HTTP request, measure the six raw primitives on their own:

Recorded on Django 6.1.3 ch03-bench script
Raw bridge primitive latency (median of 5 trials, microseconds per call)
  operation                                                   us_per_call   vs_direct_await
  plain Python call noop_sync()                                      0.03        0.4x
  direct await noop_async()                                          0.09        1.0x
  sync_to_async(thread_sensitive=False) (pooled executor)          108.50     1258.9x
  sync_to_async(thread_sensitive=True) (reused context)            119.54     1387.0x
  fresh ThreadSensitiveContext + 1 sync_to_async (new thread)      405.25     4702.0x
  async_to_sync() from sync (new loop + worker per call)           774.66     8988.2x

Those six rows explain almost everything you will ever see when profiling async Django:

Accounting for every microsecond on a zero-DB request

Now compare the exact crossing census against the measured round-trip latency on our zero-DB ping endpoint across all seven WSGI and ASGI configurations (200 requests × 5 trials = 1,000 requests per bar):

Recorded on Django 6.1.3 ch03-handlers script
Mode-crossing census on zero-DB async ping (/ping/async/)
  configuration                                 status  total  s2a  a2s  shell  mw  view_orm  workers
  ASGI pure-async (AsyncAuditMW)                200     2      2    0    2      0   0         sync-worker-1
  ASGI coalesced (7 built-ins + Timing bottom)  200     5      4    1    2      3   0         sync-worker-1
  ASGI desk/ stack (Timing at #2)               200     15     14   1    2      13  0         sync-worker-1
  ASGI default 7 MiddlewareMixin                200     15     15   0    2      13  0         sync-worker-1
  ASGI ping-pong (Async/Timing/Async)           200     4      3    1    2      2   0         sync-worker-1
  WSGI desk/ stack                              200     1      0    1    0      0   1         async-loop-1
Recorded on Django 6.1.3 ch03-bench script
Zero-DB handler + middleware latency (200 requests x 5 trials, microseconds per request)
  configuration                                 median_us   least_us   vs_wsgi_sync
  WSGI desk/ + sync view (/ping/sync/)              134.5      131.6     1.00x
  ASGI pure-async (AsyncAuditMW)                    771.7      764.7     5.74x
  ASGI coalesced (7 built-ins + Timing bottom)     1283.0     1276.0     9.54x
  ASGI ping-pong (Async/Timing/Async)              1048.8     1043.6     7.80x
  ASGI desk/ stack (Timing at #2)                  2657.0     2632.0    19.75x
  ASGI default 7 MiddlewareMixin                   2663.7     2636.6    19.80x
  WSGI desk/ + async view (/ping/async/)           1016.2     1004.4     7.55x

The arithmetic closes cleanly across all seven rows:

  1. Pure synchronous WSGI (134.5 us, 0 crossings) sets the floor: eight middleware callables, URL resolution, view dispatch, and HttpResponseBase.close all run straight on one Python stack without touching a thread queue.
  2. Pure-async ASGI (771.7 us, 2 crossings) adds +637.2 us over WSGI sync even with zero middleware crossings — paid to ASGIHandler’s tempfile.SpooledTemporaryFile, asyncio.TaskGroup + listen_for_disconnect, per-request ThreadSensitiveContext thread spin-up/teardown (~286 us), and the two shell crossings (request_started via Signal.asend and HttpResponseBase.close).
  3. Default 7 MiddlewareMixin ASGI (2,663.7 us, 15 crossings) adds +1,892.0 us on top of pure-async ASGI for those 13 extra MiddlewareMixin hops — 145.5 us per middleware hop (119.5 us for SyncToAsync plus MiddlewareMixin and convert_exception_to_response wrapper overhead). Putting our sync timing layer at index 1 (our newsroom stack, 2,657.0 us) leaves the bottom six built-ins in async mode and pays the exact same 15-crossing bill.
  4. Coalesced ASGI (1,283.0 us, 5 crossings) runs the exact same eight middleware as our newsroom stack — merely moving the sync-only timing layer from index 1 to index 7 (the bottom) — and cuts latency 2.08x (saving 1.38 milliseconds per request) by collapsing 13 middleware crossings into 3!
  5. WSGI calling an async view (1,016.2 us, 1 crossing) adds +881.7 us over WSGI sync — matching our 774.66 us raw async_to_sync new-loop cost plus wrapper overhead.

What happens on a real database endpoint (GET /wire/status/)

Empty pings exaggerate framework overhead. Does the crossing tax still matter once our newsroom endpoint live_wire_status executes three real asynchronous ORM queries (QuerySet.acount twice and QuerySet.afirst once) against SQLite?

Measure GET "/wire/status/" across all six configurations (100 requests × 5 trials):

Recorded on Django 6.1.3 ch03-handlers script
Mode-crossing census on desk/ live_wire_status (/wire/status/, 3 async ORM queries)
  configuration                                 status  total  s2a  a2s  shell  mw  view_orm  workers
  ASGI pure-async (AsyncAuditMW)                200     5      5    0    2      0   3         sync-worker-1
  ASGI coalesced (7 built-ins + Timing bottom)  200     8      7    1    2      3   3         sync-worker-1
  ASGI desk/ stack (Timing at #2)               200     18     17   1    2      13  3         sync-worker-1
  ASGI default 7 MiddlewareMixin                200     18     18   0    2      13  3         sync-worker-1
  ASGI ping-pong (Async/Timing/Async)           200     7      6    1    2      2   3         sync-worker-1
  WSGI desk/ stack                              200     4      3    1    0      0   4         async-loop-1
Recorded on Django 6.1.3 ch03-bench script
desk/ GET /wire/status/ latency (100 requests x 5 trials, microseconds per request)
  configuration                                 median_us   least_us   vs_pure_async
  ASGI pure-async (AsyncAuditMW)                   3257.7     3209.7     1.00x
  ASGI coalesced (7 built-ins + Timing bottom)     3832.7     3771.1     1.18x
  ASGI ping-pong (Async/Timing/Async)              3543.8     3529.1     1.09x
  ASGI desk/ stack (Timing at #2)                  5178.5     5164.1     1.59x
  ASGI default 7 MiddlewareMixin                   5213.6     5197.5     1.60x
  WSGI desk/ stack                                 3672.7     3618.9     1.13x

Even with three real database queries in the view, the crossing tax does not vanish into noise:

When ASGI wins — and engineering rules for production

Those numbers make it easy to draw the wrong conclusion (“ASGI is always slower”), so state the real trade-off plainly. Every benchmark above measured single-request serial latency against a fast local SQLite database. ASGI was never invented to shave microseconds off a serial database query; it exists for high-concurrency non-blocking I/O.

When an endpoint waits 400 ms on three parallel upstream HTTP calls via asyncio.gather, streams server-sent events (SSE) for ten minutes, or holds 5,000 concurrent long-polling clients, a WSGI worker pool needs 5,000 OS threads (gigabytes of stack RAM and heavy scheduler contention) while a single ASGI event-loop process multiplexes all 5,000 waiting coroutines effortlessly — and 1.9 ms of middleware overhead disappears next to 400 ms of network wait.

Conversely, for a classic database-backed CRUD application (like a newsroom CMS or admin dashboard) where requests spend 5–20 ms in PostgreSQL and Django templates, WSGI remains faster, simpler, and safer: lower per-request latency, zero per-request ThreadSensitiveContext thread churn, full "ATOMIC_REQUESTS" support, and no risk of one accidental blocking library call freezing every concurrent request on the event loop.

When you do deploy Django under ASGI, four concrete rules follow directly from our recordings:

Every request that makes it through the handler, the middleware onion, the exception walls, and the sync/async bridge lands inside BaseHandler._get_response — where Django still has to parse the raw HTTP message into HttpRequest, compile and match the URL regex tree, and dispatch function or class-based views. That inner core is the subject of HTTP, routing, and views.