Django 6.1.3

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.load_middleware + BaseHandler.adapt_method_mode 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.load_middleware 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:

That coalescing rule is brilliant — until you look at what MiddlewareMixin.__acall__ 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.process_request, thread_sensitive=True)(request) on the way in and await sync_to_async(self.process_response, thread_sensitive=True)(request, response) on the way out!

Seeing the thread lanes on live Django 6.1.3

Figure 3.3 Every crossing and thread transition is parsed straight from 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.__call__ and AsyncToSync.__call__ directly on our zero-DB async ping endpoint ("/ping/async/") and inspect the exact sequence of crossings line by line:

Recorded on Django 6.1.3 ch03-handlers script
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:

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/sync.py lines 507–546, which resolves the target executor in strict priority order whenever thread_sensitive=True:

  1. Outermost is sync (CurrentThreadExecutor): When WSGIHandler runs our async def view live_wire_status, BaseHandler._get_response wraps it in AsyncToSync. Finding no running event loop on wsgi-thread, AsyncToSync creates a CurrentThreadExecutor, stores it in AsyncToSync.loop_thread_executors[loop], launches asyncio.run(...) on a one-off sub-thread (async-loop-1), and parks wsgi-thread inside CurrentThreadExecutor.run_until_future — an idle work-queue loop waiting for callbacks! When live_wire_status awaits QuerySet.acount twice and QuerySet.afirst once, SyncToAsync.__call__ finds that CurrentThreadExecutor and submits all three SQL queries right back onto wsgi-thread:
Recorded on Django 6.1.3 ch03-handlers script
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
  1. Outermost is async (ThreadSensitiveContext): When ASGIHandler.__call__ enters async with ThreadSensitiveContext():, it binds a fresh context object into SyncToAsync.thread_sensitive_context (a contextvars.ContextVar). The first sync_to_async(..., thread_sensitive=True) call inside that request allocates a dedicated single-worker concurrent.futures.ThreadPoolExecutor — the thread-sensitive executor — and caches it in SyncToAsync.context_to_thread_executor[ctx]. Every subsequent thread_sensitive=True call in that request reuses that exact single worker thread (sync-worker-1), while concurrent ASGI requests each have their own ThreadSensitiveContext and therefore their own independent worker threads. And when ThreadSensitiveContext.__aexit__ runs at the end of the request, asgiref spawns a small daemon thread to call concurrent.futures.Executor.shutdown and awaits it via asyncio.wrap_future, so shutting down the worker can never deadlock the event loop!
  2. Context and Local re-homing: On every crossing in either direction, _restore_context copies contextvars.Context onto the destination thread and calls _rehome on any asgiref.local.Local storage objects, carrying 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:

Recorded on Django 6.1.3 ch03-handlers script
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.

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.