---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

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

> **History.** In DEP 0009 (`deps:accepted/0009-async.rst`, May 2019), Andrew Godwin designed Django's async migration as a three-stage ladder — *sync-only*, then *sync-native with an async wrapper*, then *async-native with a sync wrapper* — explicitly refusing to split Django into two incompatible ecosystems. Because database drivers, transactions, and much of Python's ecosystem expect thread affinity, DEP 0009 introduced a *"sticky thread"* model where synchronous code triggered inside one asynchronous context runs serially on one dedicated thread rather than scattering across random pool threads.

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` (`asgiref:asgiref/sync.py:ThreadSensitiveContext`, `asgiref:asgiref/sync.py:SyncToAsync`, `asgiref:asgiref/sync.py:AsyncToSync`, `asgiref:asgiref/current_thread_executor.py:CurrentThreadExecutor`).

## 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` (`django/utils/decorators.py:sync_only_middleware`, `django/utils/decorators.py:async_only_middleware`, `django/utils/decorators.py:sync_and_async_middleware`); class-based middleware declares them on the class body.

Now look at the four lines inside `BaseHandler.load_middleware` (`django/core/handlers/base.py:BaseHandler.load_middleware`) that quietly govern the performance of every ASGI deployment:

```python
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 `handler` is already async (`handler_is_async = True`) and a dual-capable middleware (`sync_capable = True, async_capable = True`, such as every `MiddlewareMixin` built-in) wraps it, the `else` branch 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 to `False`. `BaseHandler.adapt_method_mode` (`django/core/handlers/base.py:BaseHandler.adapt_method_mode`) wraps the async inner handler in `async_to_sync` (`asgiref:asgiref/sync.py:async_to_sync`), and `"handler_is_async"` becomes `False`.
- From that point upward to index `0`, every dual-capable `MiddlewareMixin` above it hits `elif 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 single `sync_to_async(..., thread_sensitive=True)` (`asgiref:asgiref/sync.py:sync_to_async`) wrapper at the very top of the chain.

That coalescing rule is brilliant — until you look at what `MiddlewareMixin.__acall__` actually does when *no* sync-only middleware sits below it (`django/utils/deprecation.py:MiddlewareMixin.__acall__`). 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

```text figure=thread-lanes
Exact thread-pool crossings on ASGI (default 7 MiddlewareMixin vs coalesced bottom sync middleware) and WSGI (async live_wire_status) from ch03-handlers

Panel A · ASGI default 7 MiddlewareMixin on /ping/async/ (15 sync_to_async hops: event-loop <-> sync-worker-1):
  1. req_start   2..7. 6x process_request   8. Csrf.process_view   [async view on event-loop]
  9..14. 6x process_response   15. resp.close

Panel B · ASGI coalesced (7 built-ins + TimingHeaderMiddleware at bottom, 5 crossings: 3x fewer hops -> 2.08x faster):
  1. req_start (s2a)
  2. exc_wall(SecurityMiddleware) (s2a) -> all 7 built-ins + Timing run synchronously on sync-worker-1
  3. BaseHandler._get_response_async (a2s) -> returns to event-loop
  4. Csrf.process_view (s2a) -> [async view on event-loop] -> 8x sync unwind on sync-worker-1
  5. resp.close (s2a)

Panel C · WSGI desk/ calling async live_wire_status (/wire/status/, 4 crossings: wsgi-thread <-> async-loop-1):
  8 middleware on wsgi-thread (0 hops) -> 1. async_to_sync(live_wire_status) onto async-loop-1
  wsgi-thread idles inside CurrentThreadExecutor.run_until_future():
  2. QuerySet.count (s2a back to wsgi-thread)
  3. StoryQuerySet.count (s2a back to wsgi-thread)
  4. QuerySet.first (s2a back to wsgi-thread)
  returns to wsgi-thread -> 8x sync unwind
```

*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:

```text recording=ch03-handlers
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 `2` `sync_to_async` crossings.** Step `01` (`Signal.asend`) runs the synchronous receivers connected to `request_started` (`reset_queries` and `close_old_connections`), and step `15`/`05`/`02` (`HttpResponseBase.close`) runs `await sync_to_async(response.close)()` from `ASGIHandler.handle` line 218.
- **Django's default seven built-ins add `13` middleware crossings.** Six define `process_request` (all except `XFrameOptionsMiddleware`), one defines `process_view` (`CsrfViewMiddleware`), and six define `process_response` (all except `AuthenticationMiddleware`). Look at step `06`: `AuthenticationMiddleware.process_request` (`django/contrib/auth/middleware.py:AuthenticationMiddleware.process_request`) hops all the way onto a worker thread just to assign two lazy lambdas (`"request.user"` and `"request.auser"`)!
- **Coalescing collapses `13` middleware crossings down to `3`.** Putting one sync-only middleware at index `7` (the bottom) makes `load_middleware` run all seven built-in `MiddlewareMixin` layers synchronously inside one single `sync_to_async` entry (`step 02`), jumping back to `event-loop` once (`step 03`) for `_get_response_async` so 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/sync.py` lines 507–546 (`asgiref:asgiref/sync.py:SyncToAsync.__call__`), 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` (`asgiref:asgiref/sync.py:AsyncToSync.__call__`). 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` (`asgiref:asgiref/current_thread_executor.py:CurrentThreadExecutor.run_until_future`) — an idle work-queue loop waiting for callbacks! When live_wire_status awaits `QuerySet.acount` twice and `QuerySet.afirst` once (`django/db/models/query.py:QuerySet.acount`, `django/db/models/query.py:QuerySet.afirst`), `SyncToAsync.__call__` finds that `CurrentThreadExecutor` and submits all three SQL queries **right back onto `wsgi-thread`**:

```text recording=ch03-handlers
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
```

2. **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:asgiref/sync.py:ThreadSensitiveContext.__aexit__`), `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!
3. **Context and `Local` re-homing:** On every crossing in either direction, `_restore_context` (`asgiref:asgiref/sync.py:_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:

```text recording=ch03-handlers
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. Under `WSGIHandler`, live_wire_status worked on `":memory:"` SQLite only because `CurrentThreadExecutor` bounced all three ORM queries *back onto the main thread* that held the seeded in-memory database. Under `ASGIHandler`, `ThreadSensitiveContext` ran the first `QuerySet.acount` on `sync-worker-1`, where SQLite opened a brand-new empty `":memory:"` database and crashed with `OperationalError: no such table: newsroom_edition`!
- **`ATOMIC_REQUESTS = True` forbids async views.** `BaseHandler.make_view_atomic` (`django/core/handlers/base.py:BaseHandler.make_view_atomic`) raises `RuntimeError` immediately if any database sets `"ATOMIC_REQUESTS": True` on an `async def` view, because a database transaction lives on one synchronous thread and cannot safely stay open across arbitrary coroutine awaits. (Decorating a view with `transaction.non_atomic_requests` opts that endpoint out.)
- **Calling `async_to_sync` directly on the event-loop thread raises `RuntimeError`.** Blocking the event loop to wait for a coroutine scheduled on that very loop is an instant deadlock, so `AsyncToSync.__call__` checks `asyncio.get_running_loop()` on line 280 and aborts immediately.
- **Forgetting `markcoroutinefunction(self)` on a class-based async middleware.** Because Python's `inspect.iscoroutinefunction` checks function flags rather than `__call__` on arbitrary instances in all paths, any custom class middleware with `async def __call__` must call `markcoroutinefunction(self)` inside `__init__` — exactly as `MiddlewareMixin.__init__` and `RemoteUserMiddleware.__init__` (`django/contrib/auth/middleware.py:RemoteUserMiddleware.__init__`) do.

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](crossing-cost.md).
