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:
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:
- Calling a plain Python function takes
30 nanoseconds; awaiting a coroutine directly takes90 nanoseconds. - Crossing once into an already-running worker thread via
sync_to_asynccosts108.50 us(thread_sensitive=False) or119.54 us(thread_sensitive=True) — over1,300xslower than a directawait! Every crossing has to copycontextvars, re-home.copy_context() asgirefstorage, enqueue a work item onto the executor, wake an OS thread, run the callable, schedule the completion callback back onto the event loop via.local .Local asyncio, and restore modified context variables..AbstractEventLoop .call_soon_threadsafe - Look at line 5: entering a fresh
ThreadSensitiveContextand making onesync_to_asynccall costs405.25 us—285.7 usmore than a reused context! That extra~286 usis the pure OS cost of a single-workerconcurrentspawning a fresh worker thread on the first.futures .ThreadPoolExecutor thread_sensitive=Truehop of an ASGI request plusThreadSensitiveContextspawning a daemon thread to join and tear it down..__aexit__ - And calling
async_to_syncfrom a synchronous thread with no outer event loop (the exact pathWSGIHandlertakes for everyasync defview) costs774.66 us— spinning up both a one-off worker thread and a brand-newasyncio.runevent loop per call.
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):
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
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:
- Pure synchronous WSGI (
134.5 us,0crossings) sets the floor: eight middleware callables, URL resolution, view dispatch, andHttpResponseBaseall run straight on one Python stack without touching a thread queue..close - Pure-async ASGI (
771.7 us,2crossings) adds+637.2 usover WSGI sync even with zero middleware crossings — paid toASGIHandler’stempfile,.SpooledTemporaryFile asyncio+.TaskGroup listen_for_disconnect, per-requestThreadSensitiveContextthread spin-up/teardown (~286 us), and the two shell crossings (request_startedviaSignal.asendandHttpResponseBase)..close - Default 7
MiddlewareMixinASGI (2,663.7 us,15crossings) adds+1,892.0 uson top of pure-async ASGI for those13extraMiddlewareMixinhops —145.5 usper middleware hop (119.5 usforSyncToAsyncplusMiddlewareMixinandconvert_exception_to_responsewrapper overhead). Putting our sync timing layer at index1(our newsroom stack,2,657.0 us) leaves the bottom six built-ins in async mode and pays the exact same15-crossing bill. - Coalesced ASGI (
1,283.0 us,5crossings) runs the exact same eight middleware as our newsroom stack — merely moving the sync-only timing layer from index1to index7(the bottom) — and cuts latency2.08x(saving1per request) by collapsing.38 milliseconds 13middleware crossings into3! - WSGI calling an async view (
1,016.2 us,1crossing) adds+881.7 usover WSGI sync — matching our774.66 usrawasync_to_syncnew-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 "/ across all six configurations (100 requests × 5 trials):
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
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:
- Default 7
MiddlewareMixinASGI (5,213.6 us,18crossings) spends+1(.96 milliseconds 37.5%of the entire request!) on13MiddlewareMixinhops compared to pure-async ASGI (3,257.7 us,5crossings). - WSGI (
3,672.7 us,4crossings) beats default ASGI (5,213.6 us) by1(.54 milliseconds 1.42xfaster) — even though the view itself isasync def— because WSGI runs all eight middleware with zero crossings and bounces the three ORM queries straight back ontowsgi-threadviaCurrentThreadExecutor. - Coalesced ASGI (
3,832.7 us,8crossings) reclaims1over default ASGI simply by changing middleware order so all seven built-ins coalesce into synchronous mode..38 milliseconds
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:
- Never assume
async_capable = Truemeans zero crossings. In Django6.1.3, all seven default built-ins inherit fromMiddlewareMixinand executesync_to_asyncon everyprocess_requestandprocess_responseunless coalesced. Audit your actual stack by checkingisinstance(mw, MiddlewareMixin). - Do not interleave sync-only and async-only custom middleware. Placing an async-only layer above a sync-only layer breaks
BaseHandler’s downward coalescing and injects a paired.load_middleware sync_to_async/async_to_syncboundary at every switch. Group native async middleware at the bottom (closest to async views) and synchronous middleware together — or place a single sync-only layer belowMiddlewareMixinbuilt-ins when you want them to coalesce into one worker pass (understanding that everything above it then runs synchronously insidesync-worker-1). - Keep pure-async endpoints off heavy
MiddlewareMixinstacks where possible. If an ASGI service mixes classic HTML admin pages with a high-RPS async streaming or webhook endpoint, serving the async paths with a minimal async middleware stack (or a separate ASGI router mount) avoids paying1.9 msofMiddlewareMixinhops on every tick. - Guard against blocking I/O on the event loop. Django’s
async_unsafeguard catches synchronous ORM calls made directly from anasync defview (SynchronousOnlyOperation), but it cannot stop a synchronous HTTP client, file read, or CPU loop from stalling every other coroutine sharing that event loop.
Every request that makes it through the handler, the middleware onion, the exception walls, and the sync/async bridge lands inside BaseHandler — 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.