Every asyncio library author eventually gets the same bug report: “can you support Trio?” The honest answer is usually no, and it is expensive to change. Anything built directly on asyncio.Lock, asyncio.Event, or loop.call_soon is welded to one scheduler. The primitives do not exist under Trio, the cancellation semantics differ, and the event loop object itself is a different beast. Rewriting the concurrency layer of a working library for a second backend is weeks of subtle work, which is why so many projects quietly decline.
AnyIO is the escape hatch from that dilemma. Its README states the pitch plainly: it is an asynchronous networking and concurrency library that works on top of either asyncio or Trio, implements Trio-like structured concurrency on top of asyncio, and lets applications and libraries written against its API run unmodified on either backend. It is widely recognized as the compatibility layer underneath a good part of the modern async Python web stack, so understanding its source is a practical skill rather than an academic one. If you have ever traced a hang through code running on a framework like Starlette or a server like Uvicorn, chances are the scheduler underneath was chosen by AnyIO.
This tour walks the real tree of the master branch, which on the day of writing contains four load-bearing zones: src/anyio/_core/ with the public API facades, src/anyio/abc/ with the abstract contracts, src/anyio/_backends/ with the two loop adapters, and src/anyio/streams/ with the composable stream types. Around them sit top-level bridges (to_thread.py, from_thread.py, to_process.py, to_interpreter.py) and a pytest plugin that parametrizes your tests across backends. Two diagrams anchor the walk.
The overview traces the dispatch spine: one entry function, one backend resolver, one abstract contract, two implementations, and the API facades that all funnel through the resolver.
Reading the overview from left to right:
- run(), L32 — the sanctioned entry point that resolves a backend and runs your coroutine on its loop, refusing outright (with a
RuntimeErrorat line 56) if the thread already has an event loop running. - get_async_backend(), L189 — the lazy loader that imports
src/anyio/_backends/_asyncio.pyor_trio.pyby name and returns its backend class. - AsyncBackend, L56 — the abstract contract every backend must implement:
run, checkpoints, scopes, task groups, primitives, sockets, and worker-thread calls, all as classmethods. - create_task_group(), L235 — a one-line factory whose body at line 244 is simply
get_async_backend().create_task_group(); this delegation pattern is the library’s whole trick. - CancelScope, L40 — the cancellation unit: a deadline, a
cancel_calledflag, and ashieldoption, backed bymove_on_after(L198) andfail_after(L156) helpers. - Event, L82 — the facade whose first await builds the real backend event via
get_async_backend().create_event()at line 87;Lock(L155),Condition(L273),Semaphore(L382), andCapacityLimiter(L530) follow the same shape. - CapacityLimiter, L530 — the token bucket used to bound concurrency, including the one guarding worker threads.
- connect_tcp(), L144 — a stateless Happy Eyeballs client per RFC 6555 with a 250 ms inter-attempt delay (
happy_eyeballs_delay: float = 0.25at line 154), IPv6 preferred, plus an optional TLS handshake. - MemoryObjectReceiveStream, L80 — the receive half of anyio’s in-process channel, sharing one state object (buffer deque, waiter registries, open-channel counters) with its send half at line 216.
The detailed map goes one level deeper: each facade, each ABC, and the internals of both backends, including the worker-thread pool and the 40-token default limiter.
One Entry Point, Two Loops
The run() function in src/anyio/_core/_eventloop.py looks unremarkable until you read what surrounds it. It validates that no loop is already running in the thread, asks get_async_backend() for the right backend class, and calls its run method with your coroutine. The resolver at line 189 does an import_module on a name it constructs from the backend string, so adding a hypothetical third backend is a matter of dropping a _thirdparty.py into _backends/ — nothing in the public API changes.
Detection is deliberately forgiving: when you call an API without ever calling run(), current_async_library() at line 209 consults sniffio, the tiny library Trio’s authors built for exactly this purpose. If sniffio is not installed, the fallback logic assumes you are on asyncio or nothing. Every facade in _core/ repeats this dance — the task helpers, the synchronization primitives, the socket helpers, even open_file — which keeps the public surface backend-neutral while each backend class carries the real logic.
Structured Cancellation: Scope, Not Signals
Cancellation is where asyncio and Trio diverge most, and AnyIO bridges it with CancelScope. The public class in src/anyio/_core/_tasks.py at line 40 exposes deadline, cancel_called, cancelled_caught, and shield; entering the block arms a deadline, and exiting it converts a pending cancellation into the backend’s cancelled exception, which the scope catches and records. The move_on_after() helper at line 198 swallows the cancellation quietly, while fail_after() at line 156 lets it escape as a TimeoutError. This is structured concurrency in its purest form: cancellation is a scoped, inspectable fact rather than a stray exception from anywhere.
Task groups build on scopes. The TaskGroup ABC in src/anyio/abc/_tasks.py at line 86 defines start_soon() at line 135, which schedules a coroutine immediately, and start() at line 158, which blocks until the spawned task calls started() on its TaskStatus (line 71), optionally handing back a startup value. The asyncio implementation at src/anyio/_backends/_asyncio.py line 618 layers this onto raw asyncio.Task objects with its own bookkeeping, while the Trio adapter at src/anyio/_backends/_trio.py line 215 translates the calls onto Trio’s native nursery. Same signatures, radically different internals — and your code cannot tell the difference.
Primitives That Delegate Everything
Open src/anyio/_core/_synchronization.py and the pattern from create_task_group() repeats five times. The Event facade at line 82 does not own a flag; it builds one lazily through get_async_backend().create_event() at line 87 and forwards every operation. Lock at line 155, Condition at line 273, Semaphore at line 382, and CapacityLimiter at line 530 all construct their backend counterparts on demand. Even the statistics NamedTuples clustered at the top of the file (EventStatistics at line 20 through SemaphoreStatistics at line 73) are mirrored by each backend so statistics() returns real waiter counts regardless of loop.
The interesting engineering decision is what the facades deliberately do not contain: queueing policy. Whether a Lock lets a freshly released waiter requeue, or a Semaphore caps how far release() can overshoot max_value, lives in the backend classes — Lock at line 1920, Semaphore at line 2004, and CapacityLimiter at line 2092 of _asyncio.py. The facade layer stays thin and identical across backends; behavior differences are owned where they are implemented.
From Single Backend to Peer Backends: Build Facts in the Code
The file sizes tell the story of the architecture. The asyncio backend, measured on the master checkout, runs 2,625 lines; the Trio adapter runs 1,208. AnyIO had to reimplement, on asyncio’s raw materials, what Trio gives you natively: its own CancelScope at line 198 with deadline bookkeeping and shielding, a WorkerThreadPool at line 879 with its WorkerThread class at line 942 to run blocking calls and marshal results back to the loop, and even a TestRunner at line 2298 for the pytest plugin. The Trio backend is smaller precisely because it delegates to a scheduler that already agrees with AnyIO’s model.
A few concrete numbers worth knowing before you tune anything:
- The default worker-thread cap is
CapacityLimiter(40)— a 40-token limiter instantiated at line 3125 of_asyncio.py— soto_thread.run_sync()calls beyond that queue up unless you swap in your own limiter. - Happy Eyeballs pacing defaults to 250 milliseconds between connection attempts, and the algorithm tries the IPv6 candidate first when one exists.
- The project requires Python 3.11 or newer (
requires-python = ">= 3.11"inpyproject.toml), which lets the codebase useExceptionGroupnatively rather than importing a backport. - The
_core/package holds 17 modules, and thestreams/package six —buffered,file,memory,stapled,text, andtls— a deliberately small, composable surface compared to the sprawling stdlibasyncionamespace.
Streams, Sockets, and the Thread Bridge
The memory stream pair is the cleanest thing in the repository. Both halves of a channel share one _MemoryObjectStreamState (line 56 of src/anyio/streams/memory.py) containing max_buffer_size (line 57), the buffer deque (line 58), open_send_channels and open_receive_channels counters (lines 59 and 60), and two OrderedDict registries for waiting senders and receivers (lines 61 through 66). Cloning a stream increments a counter; closing decrements it; when receivers reach zero, send() raises BrokenResourceError, and when senders are gone and the buffer drains, receive() raises EndOfStream. It is a textbook bounded channel, built almost entirely out of the Event facade above.
The socket layer follows the same contract pattern. create_tcp_listener() at line 310 of _core/_sockets.py returns a backend SocketListener; the asyncio TCPSocketListener at line 1575 of _asyncio.py wraps connected transports in a SocketStream (line 1301) that exposes typed attributes like local and remote addresses. For TLS, TLSStream at line 77 of streams/tls.py wraps any byte stream — it composes with connect_tcp(), which can perform the handshake itself when you pass tls=True — and TLSListener at line 313 upgrades accepted connections for servers.
The thread bridge is the piece most applications feel first. to_thread.run_sync() at line 23 of to_thread.py offloads a blocking function to the backend pool, bounded by the shared limiter returned by current_default_thread_limiter() at line 66. Going the other way, from_thread.run_sync() at line 94 of from_thread.py schedules async code from a worker thread, and the BlockingPortal at line 190 — typically obtained through start_blocking_portal() at line 610 — gives synchronous callers a complete window into the async world. Sibling modules extend the same idea beyond threads: to_process.py for real process isolation and to_interpreter.py for sub-interpreters.
Testing on Both Loops with the pytest plugin
AnyIO ships its own insurance policy for the two-backend promise. src/anyio/pytest_plugin.py adds a --anyio-mode option (line 108, with strict and auto values) and, crucially, defines the anyio_backend fixture at line 318 as module-scoped and parameterized over get_available_backends(). Mark a test with @pytest.mark.anyio (auto-detected by the collection hooks at lines 207 and 283) and it runs once per backend — the same assertion exercised by asyncio and by Trio. The plugin even ships a FreePortFactory at line 339 so servers in tests do not fight over ports. This is why the plugin pairs naturally with pytest: the backend itself becomes a fixture parameter, and any loop-specific bug surfaces as a red test rather than a production mystery.
Honest Limits
The dual-backend promise has edges. Two backends means two code paths that can drift: the asyncio backend’s 2,625 lines of reimplemented cancellation and task bookkeeping will always carry more edge cases than the 1,208-line Trio adapter, and the pytest plugin exists precisely because identical source can behave differently per loop. The 40-token worker-thread default is a heuristic, not a law — CPU-bound and I/O-heavy workloads disagree about the right number, and the limiter is shared, so one hot path can starve another. Memory object streams are strictly in-process with no serialization; crossing a process boundary means reaching for Enjoyed this post? Never miss out on future posts by following us to_process, with all the pickling constraints that implies. And because the public API is the union of what both backends can support, some loop-specific knobs are simply not exposed — if you need raw asyncio transport controls, you eventually drop a level below AnyIO. None of these are secrets; they are the honest price of one API over two schedulers, and the source tree makes that trade-off visible at every layer.