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

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

```text recording=ch03-bench
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 takes **`90 nanoseconds`**.
- Crossing once into an already-running worker thread via `sync_to_async` costs **`108.50 us`** (`thread_sensitive=False`) or **`119.54 us`** (`thread_sensitive=True`) — **over `1,300x` slower than a direct `await`**! Every crossing has to copy `contextvars.copy_context()`, re-home `asgiref.local.Local` storage, enqueue a work item onto the executor, wake an OS thread, run the callable, schedule the completion callback back onto the event loop via `asyncio.AbstractEventLoop.call_soon_threadsafe`, and restore modified context variables.
- Look at line 5: entering a **fresh `ThreadSensitiveContext`** and making one `sync_to_async` call costs **`405.25 us`** — **`285.7 us` more** than a reused context! That extra `~286 us` is the pure OS cost of a single-worker `concurrent.futures.ThreadPoolExecutor` spawning a fresh worker thread on the first `thread_sensitive=True` hop of an ASGI request plus `ThreadSensitiveContext.__aexit__` spawning a daemon thread to join and tear it down (`asgiref:asgiref/sync.py:ThreadSensitiveContext.__aexit__`).
- And calling `async_to_sync` from a synchronous thread with no outer event loop (the exact path `WSGIHandler` takes for every `async def` view) costs **`774.66 us`** — spinning up both a one-off worker thread and a brand-new `asyncio.run` event 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):

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

```text recording=ch03-bench
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):

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

```text recording=ch03-bench
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 `MiddlewareMixin` ASGI (`5,213.6 us`, `18` crossings)** spends **`+1.96 milliseconds` (`37.5%` of the entire request!)** on `13` `MiddlewareMixin` hops compared to pure-async ASGI (`3,257.7 us`, `5` crossings).
- **WSGI (`3,672.7 us`, `4` crossings) beats default ASGI (`5,213.6 us`) by `1.54 milliseconds` (`1.42x` faster)** — *even though the view itself is `async def`* — because WSGI runs all eight middleware with zero crossings and bounces the three ORM queries straight back onto `wsgi-thread` via `CurrentThreadExecutor`.
- **Coalesced ASGI (`3,832.7 us`, `8` crossings)** reclaims **`1.38 milliseconds`** over default ASGI simply by changing middleware order so all seven built-ins coalesce into synchronous mode.

## 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 = True` means zero crossings.** In Django `6.1.3`, all seven default built-ins inherit from `MiddlewareMixin` and execute `sync_to_async` on every `process_request` and `process_response` unless coalesced. Audit your actual stack by checking `isinstance(mw, MiddlewareMixin)`.
- **Do not interleave sync-only and async-only custom middleware.** Placing an async-only layer above a sync-only layer breaks `BaseHandler.load_middleware`'s downward coalescing and injects a paired `sync_to_async` / `async_to_sync` boundary 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 below `MiddlewareMixin` built-ins when you want them to coalesce into one worker pass (understanding that everything above it then runs synchronously inside `sync-worker-1`).
- **Keep pure-async endpoints off heavy `MiddlewareMixin` stacks 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 paying `1.9 ms` of `MiddlewareMixin` hops on every tick.
- **Guard against blocking I/O on the event loop.** Django's `async_unsafe` guard (`django/utils/asyncio.py:async_unsafe`) catches synchronous ORM calls made directly from an `async def` view (`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._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](../routing.md).
