TonIO and Multi-core Async Python, a Visual Guide
TL;DR: asyncio runs on one thread, so on an 18-core machine your async Python code uses about one core, however fast its event loop is. Free-threaded Python 3.14t takes the GIL away, and TonIO, a new runtime from Granian creator Giovanni Barillari, is built for it: one worker thread per core, a short list of primitives in place of asyncio's many, and a hard refusal to start if the GIL is present. It's alpha, it brings real thread hazards with it, and at the time of recording it ran only on Linux and macOS.
How many cores does your machine have? 10? 18? Your async Python code uses just one of them. asyncio runs its event loop on a single thread by design (not by accident), and for most of Python's history the GIL made that a sensible choice. Want more cores? Run more copies of your app, which is why a server like Granian starts several processes and each one carries its own copy of your code.
Python 3.14 changes the ground rules. The free-threaded build, the one with no GIL, is considered stable from 3.14 on, and you can install it with a single uv command. What it doesn't come with is an async runtime that knows what to do with real threads.
TonIO is that runtime. It's written from scratch for free-threaded Python by Giovanni Barillari, the creator of Granian, the Rust-based server that runs Talk Python's web apps. It starts one worker thread per CPU core, swaps asyncio's tasks, futures, handles, transports and protocols for a few primitives you can keep in your head, and won't run at all under the GIL.
This guide follows the story in order: why a faster event loop isn't enough, what the GIL really costs (hint: memory), how TonIO's spawn model works, the two rules that keep multi-threaded async code sane, and how TonIO might reach your web apps through tonio-monkey and a future Granian. TonIO is alpha and has one maintainer, so read this as a look at where async Python could go, not a drop-in replacement for asyncio today.
Why a faster asyncio event loop won't use your other cores
asyncio's event loop runs in one thread. Every task and callback executes there, and while one of them is running, no other can. The loop switches tasks only when one hits an await. That's how asyncio juggles thousands of waiting connections cheaply, and it's also a ceiling. Here's a quick way to see it:
import asyncio
import threading
async def work(n):
await asyncio.sleep(0.01)
return threading.get_ident()
async def main():
ids = await asyncio.gather(*(work(n) for n in range(100)))
print(len(set(ids)))
asyncio.run(main())
A hundred coroutines, one thread id, so the program prints 1. (Checked on Python 3.14.10, with and without the GIL.) On an 18-core machine, one thread is about 5% of the hardware.
The usual advice for slow async code is a faster event loop. uvloop is a drop-in replacement for the built-in loop, written in Cython on top of libuv. rloop is an asyncio selector loop implemented in Rust on top of the mio crate. zuvloop is another libuv-based replacement, written in Zig. Should you install one? The case for it is that it's performance you'd otherwise leave on the table, and, arguably, these projects also expose some of asyncio's inefficiencies. Check each project's own maturity notes first, though: rloop's README calls it a work in progress, not suited for production.
A faster loop only speeds up the hot parts of the loop's cycle and leaves the shape of how things work alone. The best case is probably in the order of 20%, and that's raw throughput in a test doing TCP and nothing else. Real programs do a lot more than move bytes.
When does a faster loop matter at all? When the work is very fine-grained, there's tons of it, and there's lots of switching. Ten tasks that each run for two seconds see no difference. And when one thread is 5% of the machine, what does it matter whether a loop gets you 4.9% or 5.1%? What you want is 95%.
rloop's author ran into the same wall from the inside. Once the loop was optimized there was nothing left to squeeze: most of the CPU time went to asyncio's own primitives, all of it on a single thread. No loop swap fixes that, and it's the point where TonIO began.
“all of these event loops, yes, they can optimize some of the hot part of the cycle. But basically, that's it. Nothing really changed the shape of how things work.”
Giovanni Barillari
The real cost of the GIL is memory, not CPU
The GIL lets only one thread run Python bytecode at a time in a process. So to use eight cores, a Python server has to replicate your app, usually as several single-threaded worker processes. Granian, for one, works that way on a standard build. Threads inside one process share a single interpreter, so they don't solve this while the GIL is there. Either way you end up with copies of your code, and the copies are the cost.
Memory is the first thing to multiply. If your process takes 500 MB and you need four of them, that's 2 GB just to run your code. Memory is also what's expensive on a server today, more than compute. Talk Python Training is a 178,000-line Python app, which is not a toy, and lazy imports, a switch to async and a few other changes took it from about 1.3 GB to 450 MB. It's one of the apps in a post on cutting a Python web app's memory by over 31%.
Memory is just the first thing to multiply. Anything held in process memory gets built once per copy, an LRU cache included. Observability gets awkward too: point the Prometheus SDK at four processes and you get four separate instances, so tracking one set of metrics takes some weird tricks with the multiprocessing library. Here's the difference in a few lines:
import multiprocessing
import threading
cache = {}
def warm(key):
cache[key] = 'built'
if __name__ == '__main__':
t = threading.Thread(target=warm, args=('from-thread',))
t.start()
t.join()
p = multiprocessing.Process(target=warm, args=('from-process',))
p.start()
p.join()
print(sorted(cache))
It prints ['from-thread']. The thread wrote into the shared dictionary. The child process wrote into its own copy and the parent never sees it. (Checked on Python 3.14.10.)
Sentry shows the same thing at a much bigger scale. Its Django monolith is 18 years old, and it's deployed several different ways with only some parts switched on in each. Even so, using a single CPU of a cloud VM takes four processes and four to six gigabytes of memory per pod.
Free-threaded Python can turn those copies into threads in one process, with one cache and one set of metrics. There's a catch: the Python docs say the free-threaded build typically uses more memory than the default build, so the saving comes from not multiplying copies, not from a leaner interpreter. Free-threading also solves a whole set of very ordinary web development problems, well before any AI workload comes into it.
“I know your process takes 500 megs of RAM, but we need four of them. So now you need two gigs just to run your code.”
Michael Kennedy
Free-threaded Python 3.14t: the biggest change in Python's history?
Free-threaded Python is a separate build of CPython that runs without the GIL, so threads in one process can run Python code at the same time. In Python 3.13 it shipped as an experiment. PEP 779 laid out the criteria for making it officially supported but still optional, and since Python 3.14 it has been officially supported, though it is still a separate, optional build. It took something like 15 years of talk to get here. Larry Hastings' Gilectomy experiment was one earlier attempt that never landed.
Is it the biggest change in Python's history? Giovanni Barillari thinks so: bigger than the move from Python 2 to 3 and its everything-is-Unicode shift. What it gives you is easy to state. You can use real threads for CPU work without reaching for a C library, and cores keep multiplying - even a $200 CPU probably has 12 or so.
Getting the interpreter takes one command, and you can check which one you're running:
uv python install 3.14t
uv run --python 3.14t python -c "import sys; print(sys._is_gil_enabled())"
That prints False. (Checked with uv and Python 3.14.10.) python -VV also reports a free-threading build, and sysconfig.get_config_var('Py_GIL_DISABLED') tells you whether a build supports it at all. The check matters because the GIL can come back. Running with PYTHON_GIL=1 or -X gil=1 turns it on, and per the Python docs importing a C extension that isn't marked as supporting free threading can switch it on too, with a warning.
That points at one big reason for slow adoption: native code. Every compiled C extension has to be made thread safe, and for some of the older ones that's neither simple nor easy. The community compatibility tracker in the resources below is where to check your own dependencies. Deployment has a gap as well. At the time of recording there was still no official free-threaded 3.14 Docker image, even though it takes little more than a t on the uv install.
That's why TonIO runs only on this build: a runtime designed around real threads has nothing to offer on an interpreter that serializes them.
“every native C compiled extension has to be fixed to be thread safe. And probably like on a bunch of ancient extensions, that's not simple or easy.”
Giovanni Barillari
What is TonIO? An async runtime built from scratch for free-threaded Python
TonIO is a multi-threaded async runtime for free-threaded Python. Its README describes it as built in Rust on top of the mio crate and inspired by tinyio, Trio and Tokio. It exists because asyncio's loop is stuck on one thread: instead of speeding that loop up, TonIO starts from the blank-whiteboard question of what async Python would look like if asyncio had never existed. Roughly three or four weeks later there was a complete alternative runtime running on multiple threads.
The biggest influence isn't Python at all. Tokio is an asynchronous runtime for Rust with a multi-threaded scheduler, and TonIO's author calls it the number one Rust async runtime. TonIO takes the same shape. By default it starts one worker thread per CPU core, so an 18-core machine runs your code on 18 threads. The threads option on tonio.main or tonio.run changes that, which is how you leave some cores free for other work. Here's a quick way to see it:
import threading
import tonio.colored as tonio
async def work():
await tonio.sleep(0.05)
return threading.get_ident()
@tonio.main(threads=4)
async def main():
ids = await tonio.spawn(*[work() for _ in range(200)])
print(len(set(ids)))
main()
Two hundred coroutines run on four worker threads, so it prints 4. Drop the threads=4 and the count follows your core count. (Checked against TonIO 0.10.7 on Python 3.14.10 free-threaded; spawn gets its own section later.)
There's one hard requirement. TonIO only runs on free-threaded Python, because real threads are the whole design. Start it on a build that has the GIL and it raises RuntimeError: GIL detected instead of limping along. There's no fallback mode.
How finished is it? At the time of recording, TonIO was at around version 0.9.14 and still alpha. The API is close to stable and few modules or primitives are left to build, with Windows support the big missing piece. The alpha label is mostly because there's only one person working on it. The README still warns that APIs are subject to breaking changes.
“let's just assume for a second, like asyncio never existed. And I want to do like async stuff in Python. What that look like?”
Giovanni Barillari
Processes, event loops and threads: where TonIO fits
Python offers three ways to use a modern machine, and each one trades something away.
- Many processes. Every core gets used, but only by copying the whole app, so memory, caches and metrics all multiply. See the real cost of the GIL.
- One event loop. asyncio juggles thousands of waiting operations cheaply, and uvloop or rloop make it faster, but everything still runs on a single core. See why a faster event loop isn't enough.
- Real threads. Free-threaded Python 3.14t plus TonIO gives one process, a worker thread per core and shared memory. See free-threaded Python and what TonIO is.
TonIO's API has far fewer moving parts than asyncio's, but a whole program is not simpler for it: shared memory across real threads brings back problems that asyncio's single thread quietly hid. The topic ends with two rules for locks and shared state that keep those problems manageable.
Why asyncio feels overcomplicated, and what TonIO leaves out
asyncio looks small from the outside: async def and await. Underneath sits a long list of concepts. There are protocols and transports, events and futures. A coroutine handed to the event loop gets wrapped in a task, and when the loop actually runs it, it becomes a handle. Everyday code rarely touches any of these, but debugging does. Once something goes wrong, you need to know all of them.
The documentation shows how much surface that is. The documentation has a whole chapter on the difference between a protocol and a transport, a distinction most application code never needs. A talk about rloop at PyCon Italia 2025 put that exact question to the audience on a slide. The Zen of Python says simple is better than complex, and the protocol-versus-transport chapter is a spot where asyncio is not.
A second pain is loop juggling. You want to make a request, but the event loop you are on is not the one your async web framework created. An async database connection initialized before the framework started its loop is bound to the wrong loop, and nothing works until you find out why. The awkwardness probably traces back to Python never having had true threads. The hope is that a runtime that owns the loop and its threads makes the question go away.
TonIO's answer is to ship far fewer primitives. Starting work comes down to two calls, spawn and spawn_blocking, covered in the next two sections. The price is compatibility. TonIO does not support asyncio's primitives, so code that leans heavily on asyncio tasks or futures will not port directly.
“if you need three different ways to explain the same thing, something is deeply wrong.”
Giovanni Barillari
How spawn works in TonIO: start now, await later
TonIO's async code looks familiar if you know asyncio. You write coroutines with async def and await them. The imports change: sleep, timers and the rest come from TonIO instead of asyncio, and there are far fewer of them. The one big new idea is spawn.
asyncio ties launching to waiting. Awaiting a coroutine starts it and waits for it in one step. To start work now and collect it later, you create a task, or reach for gather, a task group or a Trio-style scope. Await a list of bare coroutines in turn and they run one after another. Run on Python 3.14, three half-second sleeps awaited in turn take about 1.5 seconds, and about 0.5 seconds with create_task or gather.
TonIO's spawn starts the coroutine immediately and hands back something you can join. You can forget it, await it right away, or park it in a variable and await it later. Because TonIO runs a pool of real threads, with one per CPU core by default, spawned work runs in parallel across them, not just concurrently on one thread. Here is the pattern from TonIO's documentation:
import tonio.colored as tonio
async def double(v):
await tonio.sleep(0.5)
return v * 2
@tonio.main
async def main():
parallel = tonio.spawn(double(2), double(3))
v3 = await double(4)
v1, v2 = await parallel
print([v1, v2, v3])
main()
Save it as spawn_demo.py and run it with uv run --python 3.14t --with tonio spawn_demo.py. It prints [4, 6, 8] after about half a second, not a second and a half: the two spawned calls are already running while the third is awaited. (Checked against TonIO 0.10.7, the latest release at the time of writing.)
@tonio.main is the entry point. asyncio needs asyncio.run even for a small script, while TonIO lets you configure everything through tonio.run or put the one decorator on your function. tonio.run takes options such as threads for the number of runtime threads.
The tonio.colored import points to a second feature. TonIO supports two syntaxes. async/await is built on generators underneath, so a plain yield syntax cost very little to add. The base tonio module uses yield and needs no async def anywhere. The functions are still colored: anything that calls a generator function has to be a generator too.
“So instead of await, you just yield from the next coroutine you want to suspend for or wait for. And that's it. You don't need to write async def everywhere.”
Giovanni Barillari
CPU-bound work in TonIO: spawn_blocking and the blocking pool
TonIO has two thread pools: the standard pool that runs your coroutines, and a separate blocking pool. The second pays off only for mixed workloads.
What you need depends on the workload. A purely CPU-bound program can use the standard pool, since there is nothing to block, and the default of one thread per core is what that work wants. A purely I/O-bound program is fine on the standard pool too. The blocking pool pays off when the two mix, with network, disk or terminal work on one side and heavy computation on the other. A long computation can then hold up the threads that serve the I/O, and moving it to the blocking pool keeps the I/O side responsive.
Using it is one call. Every await, yield or spawn runs on the standard pool, and tonio.spawn_blocking sends a function to the blocking pool instead. You do not create or size the pool: blocking threads start on demand, up to a configurable maximum (blocking_threadpool_size on tonio.run), and barriers or semaphores limit how many run at once.
A function can also declare that it is computational, so any caller, even code in another library built on TonIO, gets it scheduled on the blocking pool without knowing. The idea was floated under the placeholder name tonio.cpu, with a guess that it would land in TonIO 0.10. It did, as mark: tonio.mark.blocking routes a function through spawn_blocking, tonio.mark.max_concurrency(n) caps how many run at once, and tonio.mark.cpu_bound(n) does both. Here is spawn_blocking next to the marker:
import tonio.colored as tonio
def crunch(n):
return sum(i * i for i in range(n))
@tonio.mark.cpu_bound(4)
def crunch_marked(n):
return sum(i * i for i in range(n))
@tonio.main
async def main():
total = await tonio.spawn_blocking(crunch, 1_000_000)
marked = await crunch_marked(1_000_000)
print(total == marked)
main()
Run it with uv run --python 3.14t --with tonio plus the file name and it prints True. (Checked against TonIO 0.10.7.)
“The blocking thread pool is useful only when you have mixed workloads and you need to balance them”
Giovanni Barillari
TonIO's built-in modules: time, sync, net and fs
A runtime is more than a scheduler. Code also needs to wait, coordinate and talk to the outside world, and TonIO groups those jobs into a few modules:
tonio.timehas timeouts, timers and similar primitives.tonio.synchas the synchronization primitives: locks, semaphores and barriers.tonio.netis the network module, with sockets and streams.tonio.fsis the filesystem module, with asyncopenand aPathclass.
Networking is where TonIO differs most from asyncio. With asyncio's low-level socket support, you create a regular socket with the standard library's socket module, hand it to the event loop and work with it through the loop. TonIO's tonio.net.socket has the same interface as the standard library module, except that every method that would block is async. Above it sits a higher-level, Trio-like interface for streams and listeners that makes networking easier to manage.
The filesystem module follows the same idea. It has an async open, and its Path mirrors pathlib, with async versions of the methods that touch the disk. Both come in two flavors to match the two syntaxes, so with async/await you import them from tonio.colored:
import tonio.colored as tonio
from tonio.colored import fs, sync
from tonio.colored.fs import Path
@tonio.main
async def main():
path = Path('hello.txt')
await path.write_text('hi')
print(await path.read_text())
async with await fs.open('hello.txt') as f:
print(await f.read())
async with sync.Lock():
print('locked')
main()
This writes a file, reads it back twice and takes a lock, and prints hi, hi and locked. (Checked against TonIO 0.10.7.) There is also a pytest plugin, so tests can run under TonIO.
“So right now, again, this is all alpha. That's mostly because there's only me working on this.”
Giovanni Barillari
Running httpx, psycopg and FastAPI on TonIO with tonio-monkey
One of asyncio's real strengths is that everyone uses it. Write async with around an httpx client, await its get, and it runs on asyncio. Does that work on TonIO? No. TonIO has no asyncio tasks or futures, so a library built on them can't run on it as is. So what do you do?
The current answer is tonio-monkey. Monkey patching means replacing parts of a library at runtime, and tonio-monkey does that for popular asyncio-native libraries so they run on TonIO. At the time of recording it covered psycopg, httpx and Redis, and it also had patches for FastAPI. A Django patch was in progress, with a hope of having it in a month or so. You install it with the extra for the package you need, then import that package from tonio_monkey instead of the original:
# pip install "tonio-monkey[httpx]"
import tonio.colored as tonio
from tonio_monkey.colored import httpx
@tonio.main
async def main():
async with httpx.AsyncClient() as client:
r = await client.get('http://www.example.com')
print(r.status_code)
main()
Keep in mind that it patches specific libraries rather than making any asyncio code run as is. Code that leans heavily on asyncio tasks or futures is the hard case. If you try TonIO on an existing codebase and need a package patched, open an issue on the tonio-monkey repo or start a TonIO discussion. The maintainer is after as many real use cases as possible right now.
Alongside the patches there's a small set of libraries that target TonIO directly, mostly for the web. httpunk is a low-level HTTP library that works with both asyncio and TonIO. On top of it sits punkreq, a higher-level HTTP client that you can use with either runtime, because the adapter lives inside the package. There's also a very beta port of Uvicorn that runs on TonIO, built as a test server for the runtime.
The longer-term idea is less patching. Once the API is stable, the hope is to talk to the AnyIO maintainers about a TonIO backend for AnyIO, which would reach a lot of libraries at once. How feasible that is remains an open question, because TonIO doesn't support asyncio's primitives.
“If anyone from the listeners want to try Tonio to an existing code base and you have a package you would like to see monkey patched, just open an issue in the TonioMonkey repo or even in Tonio discussions, and I will look at it.”
Giovanni Barillari
Using AI to stress-test a new runtime: users before you have users
A new runtime has a chicken-and-egg problem. It needs real programs to shake out its bugs, and real programs don't exist until people trust it. The way out is to generate the users: have an AI model write programs that use the runtime for everything.
Here's how that played out for TonIO. The example was Pi, a coding agent harness that's written in TypeScript despite the name. An AI model rewrote the whole thing in Python, mirroring every behavior and using TonIO for all the I/O. That one project caught probably 95% of the bugs in TonIO, by the maintainer's own estimate. The same approach is now being used on the libraries around TonIO. A solo open source maintainer who wants to focus on the runtime doesn't have time to write all those other packages by hand, so this has been super useful.
The pattern works because you pick the use cases. A web app that uses an async database. A terminal app. Whatever shape of program you're worried the runtime can't handle, you ask for it.
It's worth being clear about where AI didn't go. TonIO itself is maybe 1% AI-written code. The only piece an AI wrote was the pytest plugin, which lets tests be marked to run under TonIO. The rest was written by hand in a text editor, with no code suggestions at all.
One surprise: when frontier models were pointed at a project and asked to implement it with TonIO, they got the API right most of the time, even though there's no training data about TonIO.
“It's just like, I need users before I have users. I need these three use cases covered. So give me a web app that uses an async database. Give me this terminal app and so on.”
Michael Kennedy
Granian and free-threaded Python: the road to a TonIO web stack
A TonIO web stack is where things are heading, not where they are today. To see why, start with Granian.
In Python, for historical reasons, the web application and the HTTP server are separate packages. The server imports your app and talks to it through a protocol: WSGI, defined in PEP 3333 (the Python 3 update of PEP 333), or ASGI, its async successor. Granian is one of those servers, an alternative to uWSGI, Uvicorn, Hypercorn and the rest. What makes it different is that it's written in Rust, on top of the Hyper library, so the whole HTTP and network layer runs outside the Python interpreter. When your app gets busy, a pure-Python server adds its own load to an interpreter that's already struggling. Granian doesn't. Depending on the context, that can mean more throughput or steadier latency.
You point it at your app and pick the protocol:
granian --interface asgi --workers 2 app:app
granian --interface wsgi app:app
Because WSGI and ASGI are standard, moving a Flask or Django app to a new server doesn't mean changing code. (Mostly. There are subtleties, and Granian has an environment key added just for Werkzeug.) Talk Python picked it, as its host recalls, for the p95 rather than raw speed - how badly things slow down under weird circumstances - and at the time of recording it ran about 15 of the 33 containers there. Granian may have recently passed Hypercorn in downloads, though that was a recollection, not a checked figure. It is used at Microsoft, Google and Sentry, which runs all three of its protocols, including Granian's own RSGI.
On free-threaded Python, Granian already uses threads (though its own start-up log still calls free-threaded support experimental). Since about version 2.0, its workers become threads rather than processes, which skips the socket-sharing dance between processes, a common source of its GitHub issues. The catch is that each thread has its own event loop. A request that lands on one worker stays there, and connections can pile up on one thread while another sits idle.
There is also a plan for Granian 3. It involves a second revision of RSGI, an async-independent, callback-based protocol, so Granian can support many runtimes: asyncio, Trio, TonIO, gevent, eventlet and more. There are no promises on timing. If it lands, the async endpoints in a FastAPI or Quart app would run on TonIO.
“the only thing I'm sure about Granian is that like the HTTP stack, that's super safe. Like that's like, I could bet like everything I have on that. So if something is wrong in Granian, like that's on me, not on Hyper”
Giovanni Barillari
Trying TonIO today: free-threaded Python, Linux, macOS and the Windows question
TonIO needs two things: the free-threaded interpreter and the package. With uv, that's two commands:
uv venv --python 3.14t
uv pip install tonio
Then a first program, saved as hello.py:
import tonio.colored as tonio
@tonio.main
async def main():
await tonio.sleep(0.1)
print('Hello from TonIO')
main()
Run it with .venv/bin/python hello.py. TonIO is alpha, so expect the API to change, and at the time of recording it ran only on POSIX systems, Linux and macOS. (Later releases list Windows on a best-effort basis; check the TonIO README for the current state.)
What about Windows? Supporting it is a pain, and the maintainer isn't joking. One example: a bug that apparently dates back to Windows NT 4 makes a shared socket become blocking. And mio, the Rust library TonIO uses to drive its event loop, supports Windows only in a weird way. A few months before recording, the answer would have been never. Since then, working it through with an AI model, there's a possible way to get mio to treat certain file descriptors as TCP sockets. Partial Windows support might arrive by the end of the year, with no promise attached. Windows Subsystem for Linux is an escape hatch for developers. The reason to want Windows support is deployment: a program written with TonIO should run wherever it ends up.
Free-threaded Python is here, AI agents are here, and if asyncio has given you any of the pain points in this guide, now is the time to try something new. If TonIO doesn't fit your use case, or the API could be better, open an issue or start a discussion. The maintainer is gi0baro on GitHub and on X, and blogs at blog.baro.dev.
If you want the foundations first, Talk Python Training's Async Techniques and Examples in Python covers asyncio, threads, multiprocessing and thread safety. Granian, rloop and TonIO are all Rust underneath, and Up and Running with Rust goes from zero Rust to a PyO3 extension. And for the memory side of this story, there's Python Memory Management and Tips.
“it's not about developers. It's about like where the software runs at the end of the day.”
Giovanni Barillari
