Every Python developer who has mixed sync and async code has met the same two errors at 5pm on a Friday. The first is RuntimeError: You cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly, raised verbatim by asgiref’s sync.py, L284. The second is the silent one: a SQLite connection or a GUI handle quietly crosses a thread boundary and starts misbehaving in ways that only appear under load. Both errors exist because the Python event loop is single-threaded by design, while the vast majority of real-world code — database drivers, filesystem helpers, legacy frameworks — is blocking code that must run somewhere else.

The package that solves this is asgiref, the reference implementation of the ASGI auxiliary pieces. Its setup.cfg describes it plainly as “ASGI specs, helper code, and adapters”, and its project metadata links straight to the Django async adapter documentation — because Django itself delegates the hard part of async_to_sync and sync_to_async to this library, and the Django Software Foundation is listed as the author. The current release, version 3.13.0 (October 2026), supports Python 3.11 through 3.15 and carries a beta classifier for free-threaded builds, which tells you how seriously the maintainers treat thread semantics.

This post walks the actual source tree: ten Python modules plus a py.typed marker, with the sync.py, L1 bridge as the centerpiece (28,189 bytes — the largest file in the package), the async-aware Local, the WSGI adapter, and a small server base class. Every file path and line number below was verified against the main branch tree.

asgiref architecture overview: sync and async bridge classes, executors, local state, WSGI adapter, and server contracts

Overview of asgiref: the two bridge wrappers in sync.py, the executor machinery they share, the thread-tagged state in local.py, and the WSGI and server layers built on top of them.

Reading the overview from left to right:

  • SyncToAsync, L427 — wraps a sync callable so it can be awaited, running it in a thread pool instead of on the event loop thread.
  • AsyncToSync, L211 — the mirror wrapper: takes an awaitable and returns a blocking callable that reuses the parent loop when one exists, otherwise spins a new loop in a fresh thread.
  • single_thread_executor, L453 — a class-level ThreadPoolExecutor(max_workers=1) that serializes all thread-sensitive sync work when no more specific target applies.
  • CurrentThreadExecutor, L44 — the trick that makes bidirectional nesting possible: an executor that runs submitted work in the thread it was created in, parking that thread on a condition variable.
  • Local, L80 — threading.local for the async era: task-aware, contextvar-backed, and since 3.13.0 marked @final with two internal specializations.
  • WsgiToAsgi, L8 — a faithful WSGI-to-ASGI adapter, letting legacy WSGI applications run under ASGI servers unchanged.
  • StatelessServer, L11 — a base class for servers of stateless protocols, pooling up to 1000 application instances with LRU eviction.
  • guarantee_single_callable, L40 — the ASGI 2.0 to 3.0 bridge, detecting legacy double-callable applications and wrapping them into the modern single-callable form.
asgiref detail diagram: AsyncToSync and SyncToAsync call internals, CurrentThreadExecutor queue, Local specializations, WsgiToAsgiInstance flow, and server pooling

Detail view: how the wrappers coordinate through the threadlocal and the executor stack, how Local re-tags its storage across threads, and how the WSGI adapter moves request bodies between worlds.

The Bridge Problem: Why Two Wrappers Exist

The two classes in sync.py, L1 are not symmetric utilities glued together; they are designed as a pair with a shared communication channel. SyncToAsync.__call__ (line 502) is the simpler direction: it picks an executor, wraps the sync function with thread_handler, L614, and dispatches it with loop.run_in_executor while await asyncio.shield(exec_coro) protects the future from task cancellation. The shield matters: if the calling task is cancelled, the sync code keeps running to completion rather than being abandoned mid-statement.

AsyncToSync is the harder direction, and its __call__ (line 261) reveals why the pair needs each other. First it checks that no event loop is running in the current thread — that is where the famous RuntimeError comes from. Then it looks up SyncToAsync.threadlocal for a main_event_loop_pid, comparing it against os.getpid() so a forked child never reuses its parent’s loop (issue #194, noted in a comment at line 272). If a parent loop exists, the awaitable is scheduled onto it with call_soon_threadsafe; otherwise a brand-new loop runs inside a ThreadPoolExecutor(max_workers=1) via asyncio.run. Either way, the calling thread does not simply block on a future: it parks itself in a CurrentThreadExecutor, L58 via run_until_future, idling on a threading.Condition until the awaited result arrives.

That parked thread is the communication channel. Any sync_to_async call made deeper in the async code can look up AsyncToSync.executors.current (line 226, a Local holding a stack of executors) and submit work straight back to the original sync thread. A Django view running ORM queries in a thread-sensitive context, called from async middleware, called from a sync entry point, all share one physical thread — which is exactly what database connection pools assume.

Thread-Sensitive Mode: One Thread, Many Contexts

sync_to_async defaults to thread_sensitive=True, and its executor selection ladder (lines 507 through 543) is the most subtle code in the repository. The order of checks is: an existing CurrentThreadExecutor from a parent sync frame wins; then a ThreadSensitiveContext from a contextvar; then a loop-to-executor map for loops started by AsyncToSync; then a deadlock guard; and finally the shared single_thread_executor. The deadlock_context, L463 check is a direct answer to a real failure mode: calling thread-sensitive sync code from inside the single thread executor would enqueue work onto a thread that is blocked waiting for the very call it is asked to run, so it raises RuntimeError immediately instead of hanging forever.

ThreadSensitiveContext, L110 generalizes this. Without arguments, nested contexts are no-ops and the outermost one owns the scheduling. Since 3.13.0 (changelog entry #596) it also accepts an explicit executor, which must be single-worker, letting a block of thread-sensitive work be moved off the shared executor. The exit path has a comment worth reading twice: the executor’s worker may itself be waiting on this event loop, so a blocking shutdown() would deadlock — the code instead joins it in a dedicated daemon thread (lines 199 through 208). A _exited flag then rejects calls from tasks that inherited the context and outlived it, closing a subtle leak class where orphaned tasks would silently migrate onto an unrelated worker thread.

From 1000 Instances to 64 KiB Buffers: Build Facts

The small numbers in this codebase are deliberate, and they are worth collecting in one place. The StatelessServer, L46 caps pooled application instances at max_applications=1000 and evicts the least recently used one; a checker coroutine polls every application_checker_interval = 0.1 seconds (line 44), logging tracebacks from crashed application coroutines. On the WSGI side, WsgiToAsgi, L13 sets duplicate_header_limit=100, and the adapter raises a ValueError past that limit rather than emitting the request — returning a plain 400 Bad Request response from run_wsgi_app, L150. Request bodies spool in a SpooledTemporaryFile(max_size=65536): 64 KiB in memory, disk-backed beyond that, so a large upload never pins the event loop thread.

Version 3.13.0 shipped two structural changes. First, Local attribute access became 2-3x faster by replacing per-access mode checks with the _DefaultLocal and _ThreadCriticalLocal specializations chosen once in __new__ — and Local became @final, raising TypeError("asgiref.local.Local cannot be subclassed") at line 110, because subclassing could never have worked correctly against specialized implementations. Second, asgiref.timeout.timeout was deprecated in favor of stdlib asyncio.timeout(); the module remains but warns at import of use (timeout.py line 39). The typing module, by contrast, is pure API surface: a 39-name __all__ covering HTTPScope, every HTTP, WebSocket, and Lifespan event as TypedDict, and the ASGI3Application, L253 protocol alias. The test suite mirrors the package: thirteen test files including dedicated suites for contextvars, thread-sensitive scenarios, executor context bridges, and a benchmark file that skips itself unless pytest-benchmark or pytest-codspeed is installed (test_benchmark_local.py, L14).

Local: Thread-Tagged State in a Free-Threaded World

Local, L80 answers a question that plain contextvars cannot: what does “local” mean when one logical task spans three threads? The default variant wraps a cvar, L39 — a contextvar holding a _Storage object that carries a thread_id alongside its data dict, guarded by an RLock. The storage lookup (line 47) discards any storage whose thread_id differs from threading.get_ident(): data that merely inherited into a thread is invisible, while data intentionally moved across a bridge is re-tagged by _rehome, L31.

The re-homing points are the bridge calls themselves. _restore_context, L37 walks a copied contextvars.Context and calls _rehome on every _Storage value it finds, so an attribute set before an async_to_sync hop stays visible after it — documented behavior that Django leans on for request-scoped state. The thread_critical=True variant (line 166) opts out entirely: plain thread-local storage in sync threads, a per-task contextvar only inside async frames, which is the right choice for database handles. This design matters more now that CPython’s free-threaded builds exist: Python 3.14’s sys.flags.thread_inherit_context makes new threads inherit a copy of the spawning context, and the comment block in local.py (lines 13 through 21) explains exactly how thread-tagging neutralizes that. The CPython context machinery behind this is dissected in our CPython source tour.

Honest Limits

The wrappers are pragmatic, not magic. AsyncToSync still cannot be called from a thread that already runs an event loop; you must await instead, and the error message is the code telling you so. Executor selection depends on contextvars flowing correctly — a library that resets contexts at the wrong point can silently move thread-sensitive code off its pinned thread. The CHANGELOG for 3.12.1 records an APM vendor relying on the internal shape of SyncToAsync.__call__ (issue #572), a reminder that the internal code structure is not a stability contract. WsgiToAsgi maps one request-response exchange; WSGI has no server push, no websocket scopes, and no disconnect notifications, so the adapter necessarily drops those ASGI capabilities. And StatelessServer is explicitly a base class, not a product: handle() and application_send() raise NotImplementedError until a subclass implements them. Finally, Local’s isolation is by convention of the bridge calls — only work moved through sync_to_async or async_to_sync gets re-homed; threads spawned directly by user code inherit nothing and see nothing, which is the documented contract rather than a sandbox. The testing harness (ApplicationCommunicator) runs applications in a deliberately empty context (testing.py lines 42 through 47), so leaks into tests reveal themselves early. For Python’s own concurrency internals, our pytest source tour shows the companion test-layer tooling, and the asyncio loop mechanics live in CPython itself.

Watch PyShine on YouTube

Contents