3.5 Handlers, middleware, and async
Sync and async inside one chain
How does Django run a synchronous middleware beside an asynchronous view inside one ASGI request without deadlocking the event loop?
Writing an async def view in Django takes one keyword. Drop our newsroom project’s live_wire_status coroutine view into urls.py, leave the standard eight-entry "MIDDLEWARE" list untouched, and Django serves it seamlessly under both WSGIHandler and ASGIHandler. Nothing hangs, database queries succeed, and thread-local state like set_urlconf never bleeds across concurrent requests.
That compatibility promise is carried by two pieces working together: BaseHandler + BaseHandler inside Django, and ThreadSensitiveContext, SyncToAsync, AsyncToSync, and CurrentThreadExecutor inside asgiref.
Capability flags and downward coalescing
Every middleware factory in Django carries two boolean class or function attributes — sync_capable (default True) and async_capable (default False). Function-based factories set them with the decorators sync_only_middleware, async_only_middleware, or sync_and_async_middleware; class-based middleware declares them on the class body.
Now look at the four lines inside BaseHandler that quietly govern the performance of every ASGI deployment:
elif not handler_is_async and middleware_can_sync:
middleware_is_async = False
else:
middleware_is_async = middleware_can_async
Read that rule while remembering that load_middleware walks MIDDLEWARE bottom to top:
- If the inner
handleris already async (handler_is_async = True) and a dual-capable middleware (sync_capable = True, async_capable = True, such as everyMiddlewareMixinbuilt-in) wraps it, theelsebranch runs:middleware_is_async = True. - If a synchronous-only middleware (
sync_capable = True, async_capable = False, such as our newsroom’s timing middleware) wraps an async inner handler,"middleware_is_async"drops toFalse.BaseHandlerwraps the async inner handler in.adapt_method_mode async_to_sync, and"handler_is_async"becomesFalse. - From that point upward to index
0, every dual-capableMiddlewareMixinabove it hitselif not handler_is_async and middleware_can_sync:and coalesces into synchronous mode (middleware_is_async = False) instead of bouncing back to async! Line 101 then adds a singlesync_to_async(..., thread_sensitive=True)wrapper at the very top of the chain.
That coalescing rule is brilliant — until you look at what MiddlewareMixin actually does when no sync-only middleware sits below it. Every one of Django’s seven default built-in middlewares inherits from MiddlewareMixin. When "handler_is_async" stays True all the way up Django’s default "startproject" stack, every single built-in enters async_mode = True — and executes await sync_to_async(self on the way in and await sync_to_async(self on the way out!
Seeing the thread lanes on live Django 6.1.3
ch03-handlers. Compare the fifteen-tooth comb of Django’s default ASGI stack (Panel A) against the coalesced five-crossing block (Panel B) and WSGI’s CurrentThreadExecutor boomerang (Panel C).Instrument SyncToAsync and AsyncToSync directly on our zero-DB async ping endpoint ("/ping/async/") and inspect the exact sequence of crossings line by line:
Exact crossing sequence on /ping/async/ (default 7 built-ins vs desk/ vs coalesced vs WSGI)
ASGI default 7 MiddlewareMixin (15 crossings):
01. sync_to_async [shell ] event-loop -> sync-worker-1 ts=True Signal.asend.<locals>.sync_send
02. sync_to_async [middleware] event-loop -> sync-worker-1 ts=True SecurityMiddleware.process_request
03. sync_to_async [middleware] event-loop -> sync-worker-1 ts=True SessionMiddleware.process_request
04. sync_to_async [middleware] event-loop -> sync-worker-1 ts=True CommonMiddleware.process_request
05. sync_to_async [middleware] event-loop -> sync-worker-1 ts=True CsrfViewMiddleware.process_request
06. sync_to_async [middleware] event-loop -> sync-worker-1 ts=True AuthenticationMiddleware.process_request
07. sync_to_async [middleware] event-loop -> sync-worker-1 ts=True MessageMiddleware.process_request
08. sync_to_async [middleware] event-loop -> sync-worker-1 ts=True CsrfViewMiddleware.process_view
09. sync_to_async [middleware] event-loop -> sync-worker-1 ts=True XFrameOptionsMiddleware.process_response
10. sync_to_async [middleware] event-loop -> sync-worker-1 ts=True MessageMiddleware.process_response
11. sync_to_async [middleware] event-loop -> sync-worker-1 ts=True CsrfViewMiddleware.process_response
12. sync_to_async [middleware] event-loop -> sync-worker-1 ts=True CommonMiddleware.process_response
13. sync_to_async [middleware] event-loop -> sync-worker-1 ts=True SessionMiddleware.process_response
14. sync_to_async [middleware] event-loop -> sync-worker-1 ts=True SecurityMiddleware.process_response
15. sync_to_async [shell ] event-loop -> sync-worker-1 ts=True HttpResponse.close
ASGI coalesced (7 built-ins + Timing bottom) (5 crossings):
01. sync_to_async [shell ] event-loop -> sync-worker-1 ts=True Signal.asend.<locals>.sync_send
02. sync_to_async [middleware] event-loop -> sync-worker-1 ts=True exc_wall(SecurityMiddleware)
03. async_to_sync [middleware] sync-worker-1 -> event-loop ts=- BaseHandler._get_response_async
04. sync_to_async [middleware] event-loop -> sync-worker-1 ts=True CsrfViewMiddleware.process_view
05. sync_to_async [shell ] event-loop -> sync-worker-1 ts=True HttpResponse.close
ASGI pure-async (AsyncAuditMW) (2 crossings):
01. sync_to_async [shell ] event-loop -> sync-worker-1 ts=True Signal.asend.<locals>.sync_send
02. sync_to_async [shell ] event-loop -> sync-worker-1 ts=True HttpResponse.close
Look closely at every row of those three sequences:
- Even pure-async ASGI makes
2sync_to_asynccrossings. Step01(Signal.asend) runs the synchronous receivers connected torequest_started(reset_queriesandclose_old_connections), and step15/05/02(HttpResponseBase) runs.close await sync_to_async(responsefrom.close)() ASGIHandlerline 218..handle - Django’s default seven built-ins add
13middleware crossings. Six defineprocess_request(all exceptXFrameOptionsMiddleware), one definesprocess_view(CsrfViewMiddleware), and six defineprocess_response(all exceptAuthenticationMiddleware). Look at step06:AuthenticationMiddlewarehops all the way onto a worker thread just to assign two lazy lambdas (.process_request "request.user"and"request.auser")! - Coalescing collapses
13middleware crossings down to3. Putting one sync-only middleware at index7(the bottom) makesload_middlewarerun all seven built-inMiddlewareMixinlayers synchronously inside one singlesync_to_asyncentry (step 02), jumping back toevent-looponce (step 03) for_get_response_asyncso the async view still executes natively on the event loop!
Inside ThreadSensitiveContext and CurrentThreadExecutor
Why did all fifteen sync_to_async hops in Panel A land on the same sync-worker-1 thread — and how does Panel C avoid deadlocking when a sync thread calls an async view that calls sync ORM queries?
The answer lives in asgiref: asgiref/ lines 507–546, which resolves the target executor in strict priority order whenever thread_sensitive=True:
- Outermost is sync (
CurrentThreadExecutor): WhenWSGIHandlerruns ourasync defview live_wire_status,BaseHandlerwraps it in._get_response AsyncToSync. Finding no running event loop onwsgi-thread,AsyncToSynccreates aCurrentThreadExecutor, stores it inAsyncToSync, launches.loop_thread_executors[loop] asyncio.run(...)on a one-off sub-thread (async-loop-1), and parkswsgi-threadinsideCurrentThreadExecutor— an idle work-queue loop waiting for callbacks! When live_wire_status awaits.run_until_future QuerySet.acounttwice andQuerySet.afirstonce,SyncToAsyncfinds that.__call__ CurrentThreadExecutorand submits all three SQL queries right back ontowsgi-thread:
WSGI -> async live_wire_status CurrentThreadExecutor round-trip (/wire/status/)
WSGI desk/ stack on /wire/status/ (4 crossings):
01. async_to_sync [view_orm ] wsgi-thread -> async-loop-1 ts=- live_wire_status
02. sync_to_async [view_orm ] async-loop-1 -> wsgi-thread ts=True QuerySet.count
03. sync_to_async [view_orm ] async-loop-1 -> wsgi-thread ts=True StoryQuerySet.count
04. sync_to_async [view_orm ] async-loop-1 -> wsgi-thread ts=True QuerySet.first
- Outermost is async (
ThreadSensitiveContext): WhenASGIHandlerenters.__call__ async with ThreadSensitiveContext():, it binds a fresh context object intoSyncToAsync(a.thread_sensitive_context contextvars). The first.ContextVar sync_to_async(..., thread_sensitive=True)call inside that request allocates a dedicated single-workerconcurrent— the thread-sensitive executor — and caches it in.futures .ThreadPoolExecutor SyncToAsync. Every subsequent.context_to_thread_executor[ctx] thread_sensitive=Truecall in that request reuses that exact single worker thread (sync-worker-1), while concurrent ASGI requests each have their ownThreadSensitiveContextand therefore their own independent worker threads. And whenThreadSensitiveContextruns at the end of the request,.__aexit__ asgirefspawns a small daemon thread to callconcurrentand awaits it via.futures .Executor .shutdown asyncio, so shutting down the worker can never deadlock the event loop!.wrap_future - Context and
Localre-homing: On every crossing in either direction,_restore_contextcopiescontextvarsonto the destination thread and calls.Context _rehomeon anyasgirefstorage objects, carrying.local .Local set_urlconf, active language, and timezone across thread boundaries without leaking them to unrelated threads.
Four real leaks when sync meets async
Run our four edge-case probes against live Django 6.1.3 and watch every seam where the bridge stops hiding the threads:
ThreadSensitiveContext isolation, SQLite :memory: trap, ATOMIC_REQUESTS and AsyncToSync guards
ASGIHandler + SQLite ':memory:' on /wire/status/ -> OperationalError: no such table: newsroom_edition
concurrent ThreadSensitiveContext -> reqA_sticky=True reqB_sticky=True distinct_worker_threads=True off_event_loop=True
ATOMIC_REQUESTS=True + async view -> RuntimeError: You cannot use ATOMIC_REQUESTS with async views.
async_to_sync inside event loop -> RuntimeError: You cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly.
- The SQLite
":memory:"ASGI trap. Look at line 1 above — a bug that bites almost every developer testing ASGI against SQLite for the first time. UnderWSGIHandler, live_wire_status worked on":memory:"SQLite only becauseCurrentThreadExecutorbounced all three ORM queries back onto the main thread that held the seeded in-memory database. UnderASGIHandler,ThreadSensitiveContextran the firstQuerySet.acountonsync-worker-1, where SQLite opened a brand-new empty":memory:"database and crashed withOperationalError: no such table: newsroom_edition! ATOMIC_REQUESTS = Trueforbids async views.BaseHandlerraises.make_view_atomic RuntimeErrorimmediately if any database sets"ATOMIC_REQUESTS": Trueon anasync defview, because a database transaction lives on one synchronous thread and cannot safely stay open across arbitrary coroutine awaits. (Decorating a view withtransactionopts that endpoint out.).non_atomic_requests - Calling
async_to_syncdirectly on the event-loop thread raisesRuntimeError. Blocking the event loop to wait for a coroutine scheduled on that very loop is an instant deadlock, soAsyncToSyncchecks.__call__ asyncioon line 280 and aborts immediately..get_running_loop() - Forgetting
markcoroutinefunction(self)on a class-based async middleware. Because Python’sinspectchecks function flags rather than.iscoroutinefunction __call__on arbitrary instances in all paths, any custom class middleware withasync def __call__must callmarkcoroutinefunction(self)inside__init__— exactly asMiddlewareMixinand.__init__ RemoteUserMiddlewaredo..__init__
Now we know why each crossing happens. Let’s measure exactly how many microseconds every single one of those crossings costs — and decide when ASGI actually beats WSGI — in Measuring the thread-pool crossing.