Python asyncio: Ruby Rabbit and the Bakery That Never Stood Still

updated 2026-10-06 · 12 min


ONELINE

For I/O-bound work, there's often nothing useful to compute while the network, database, or OS finishes what it's doing — and asyncio's job is making sure that dead time doesn't block other work that's ready to run, provided nothing in the code blocks the event loop itself. One pair of hands, never two orders in them at once, but never standing idle either.

METAPHOR

A single baker running a bakery full of orders, never two in her hands at once, but never standing still either.

Cheat sheet: the bakery map

StorySystem
Ruby RabbitThe application
Ruby's handsThe single thread running the event loop
An orderA unit of async work
Ruby's recipe for a loafA coroutine function (async def) — the recipe for doing the work
A loaf placed on Ruby's workbenchAn asyncio.Task — a scheduled wrapper around the coroutine that the event loop tracks and runs
Dough rising, bread bakingExternal I/O in progress — Ruby's thread doesn't need to execute Python code while it waits
Ruby stepping away from a loafAn await point — where a coroutine suspends and hands control back
Continuous hand-kneading that can't be set downCPU-bound work — her own hands are the bottleneck, genuinely busy the whole time
Standing watch at the window, unable to step away until something external finishesBlocking I/O (or a blocking wait) — nothing to compute, but the thread can't leave either
A second baker, working at the same instantA separate execution resource that can provide parallelism

Keep these at separate levels: Ruby is the whole application. Her hands are the one execution resource it has. An order is a unit of work; the coroutine is the recipe for doing it; the Task is that recipe placed on the workbench, which the event loop actually keeps track of.

What problem is asyncio actually solving?

Not "do many things at the exact same instant" — Ruby only has two hands. The problem is narrower, and far more common than that: for I/O-bound work — a network call, a database query, a timer — there's often nothing useful to compute while it finishes; the application is just waiting for something external to catch up. CPU-bound work is the opposite: the CPU itself is the bottleneck, genuinely busy the whole time, nothing external to wait on.

The problem isn't simply "work that takes a long time." The problem is work that keeps Ruby's hands occupied while the event loop could otherwise be doing something useful.

One order at a time

Ruby Rabbit ran the busiest bakery in the forest, and for years she ran it the only way she knew: one order, start to finish, before beginning the next.

She'd knead a loaf, set it to rise, and stand there and watch it rise — doing nothing, because the next order hadn't started yet. Then she'd shape it, slide it into the oven, and watch the oven too.

By the time the first loaf came out, she'd spent most of that time doing nothing at all with her own two hands. Three orders took three times as long. Customers queued out the door before dawn, and half of them left empty-handed.

"There has to be a better way to run a kitchen," Ruby muttered, staring at the clock.

Ruby learns to juggle

Ruby tried something new the next morning. She kneaded the first loaf and set it to rise — and instead of standing and watching, she stepped away and started kneading a second order.

While the second rose, she shaped the first, now ready, and slid it into the oven. While it baked, she kneaded a third. While that one rose, she checked back on the second, now ready to shape.

She was never doing two things in her own two hands at once — she still only had one pair of hands. But she was never just standing there either. The instant one order had nothing left for her to do, she stepped away to whichever order was ready and waiting.

By midmorning, three loaves had gone from flour to fresh bread in a fraction of the time it used to take for one.

NAPKIN — Tech translation

Story: Dough rising or bread baking is work happening without needing Ruby at all. The moment she steps away from a loaf to let that happen, she's free — and when she steps back to it, she picks up exactly where she left off.

Python: Each order is represented by a coroutine, created by calling an async def function, then scheduled on the event loop's workbench as a Task. Stepping away is the await: the point where a coroutine suspends itself and hands control back to the event loop, which runs whichever other Task is ready. This is cooperative scheduling — nothing forcibly interrupts Ruby mid-knead; she runs until she chooses to step away, typically at an await. Only one Task's Python code is ever executing at a given instant on this event-loop thread — there's still only one pair of hands.

Two loaves interleaved by a single baker Loaf A is kneaded, then left to rise while Loaf B is kneaded during that same window, then Loaf A is shaped once it's ready. Loaf A Loaf B active — needs Ruby's hands passive — I/O in progress, no hands needed
While Loaf A rises (passive), Ruby's hands are free for Loaf B.

The kneading that wouldn't wait

One afternoon a customer ordered a specialty seeded loaf. The dough needed ten straight minutes of hand-kneading — not the usual kind, where Ruby could set it down and come back. This dough had to be worked continuously, or it wouldn't rise right at all.

Ruby started kneading. While she did, the oven timer on Loaf A went off. Dough for Loaf B finished rising, ready to shape. Ruby couldn't even glance over — both hands were buried in dough that would collapse the instant she let go.

For ten full minutes, nothing else in the kitchen got touched. Not because the other loaves needed anything complicated — they were just sitting there, finished waiting, needing thirty seconds of attention Ruby didn't have to give.

By the time she finished the seeded loaf, Loaf A had overbaked slightly and Loaf B had overproofed. Nothing about those two loaves had gone wrong on its own. Ruby had simply been unavailable the entire time, for work that had nothing to do with either of them.

This wasn't the same as the time she'd stood at the delivery window for twenty minutes, refusing to look away in case she missed the flour cart arriving. That time, her hands had been perfectly free — she simply wouldn't leave her post. This time, her hands genuinely could not leave; the dough demanded them.

NAPKIN — Tech translation

Story: Continuous hand-kneading demands Ruby's hands for its entire duration — there's nothing to hand off, because she's the one doing the work. Standing at the window is different: nothing needs her hands at all, she's just stuck there, unable to step away until the cart arrives.

Python: The kneading is CPU-bound work — a tight computation, the CPU itself is the bottleneck, genuinely busy the whole time. The window is blocking I/O (or a plain blocking wait, for something like time.sleep()): nothing is being computed at all, the thread is just stuck waiting for something external, in a way that doesn't hand control back. Both freeze the event loop for the same practical reason, even though the root cause is different.

WATCHOUT

The magic only works when the wait gives control back to the event loop. async def doesn't change that on its own — wrapping a blocking call in async def doesn't make it non-blocking.

  • await session.get(...) (aiohttp) — can suspend while the I/O is pending
  • requests.get(...) — doesn't
  • time.sleep(10) — doesn't
  • a tight CPU loop — doesn't

Any of the three "doesn't" cases freezes the entire event loop — every other Task in the program, including ones already ready to run, simply stops. For blocking I/O, use an async-native equivalent when one exists (asyncio.sleep(), aiohttp instead of requests), or move the blocking call to a thread with asyncio.to_thread(). For genuinely CPU-bound work, use a separate execution resource such as a process.

Blocking code freezes every coroutine, not just its own While the special loaf is kneaded continuously, Loaf A and Loaf B both finish their passive waiting and sit ready, untouched, until the special loaf is done. Special loaf Loaf A Loaf B Ruby free again
Dashed segments: ready and waiting, untouched — not because they need anything complicated, but because Ruby's hands are occupied with something that can't be paused.

RECALL

If the seeded loaf needs ten straight minutes of hand-kneading, and two other loaves finish their rise during those ten minutes, how long do they sit fully risen before Ruby can get to them? And would hiring a second baker, standing right next to Ruby and kneading her own dough, change that answer? Why or why not?

ASIDE

Exactly how the event loop decides which Task is "ready" next — the OS event-notification machinery such as select/epoll, watching dozens of sockets and timers at once — is its own lesson. For now: one baker, one pair of hands, one thing actually executing at any instant.

Putting the day together

Strip the bakery away and this is three outgoing API calls — pricing, shipping, inventory — each mostly spent waiting on a network, not computing anything:

Blocking, one at a time:

import requests

def get_all_prices():
    shipping = requests.get("https://shipping.internal/rate").json()
    pricing = requests.get("https://pricing.internal/quote").json()
    stock = requests.get("https://inventory.internal/stock").json()
    return shipping, pricing, stock

One baker, overlapping the waits:

import asyncio
import aiohttp

async def fetch(session, url):
    async with session.get(url) as resp:
        return await resp.json()

async def get_all_prices():
    async with aiohttp.ClientSession() as session:
        return await asyncio.gather(
            fetch(session, "https://shipping.internal/rate"),
            fetch(session, "https://pricing.internal/quote"),
            fetch(session, "https://inventory.internal/stock"),
        )

Each fetch is an order — a coroutine, turned into a Task the moment asyncio.gather() schedules it. gather() doesn't create three bakers; it hands the same baker three pieces of work to juggle, lets each one make progress whenever it's ready, and waits until all three are done. The asynchronous waits inside fetch are the moments the dough goes to rise — Ruby stepping away while the network does its part, not the rising itself. Here's what that actually looks like on the clock, using Ruby's own numbers — ten minutes to knead, thirty to rise, five to shape, forty to bake, for every loaf:

One baker, three loaves, overlapping waits Timeline from 0 to 105 minutes. Loaf A is kneaded first, then rises while Loaf B is kneaded, then Loaf C is kneaded while Loaf A and B rise. Each loaf's rise and bake overlap with another loaf's active work, until all three finish baking by 105 minutes, compared to 255 minutes if done one at a time. Loaf A Loaf B Loaf C 0 min 50 min 100 min
Solid = active (Ruby's hands). Outlined = passive (rising, baking — safe to overlap).

Sequential, one loaf fully finished before the next starts: 3 × 85 minutes = 255 minutes. One baker, overlapping the waits: 105 minutes.

That's not three times faster. It can't be — one baker still only has one pair of hands, and her 45 total minutes of kneading and shaping still happen one loaf at a time, in order. What's gone is the 150 minutes Ruby used to spend just standing there, watching bread she couldn't do anything about. The whole bakery finishes in roughly the length of the longest chain of active work plus whatever waiting couldn't be overlapped — not the sum of every loaf's waiting time end to end.

One last distinction: concurrency ≠ parallelism

Go back to the RECALL above. Two loaves finish rising while the seeded loaf is being kneaded — they simply wait, however long that kneading takes, because there's still only one Ruby.

Concurrency is what asyncio gives you: multiple Tasks in progress during overlapping periods, their execution interleaved, but never more than one actually running at a given instant on Ruby's one thread. It's an excellent trade when most of the time is spent waiting — network calls, database queries, anything I/O-bound — because that waiting was never real work to begin with.

Parallelism is different: multiple things genuinely executing at the same instant. Hiring a second baker, standing right next to Ruby and kneading her own dough, gives you that — now two pairs of hands are moving at once, not one pair juggling two jobs.

In Python specifically, that distinction has a sharp edge: a second thread doesn't automatically mean a second pair of hands. On a standard GIL-enabled CPython build, only one thread executes Python bytecode at a time, so for CPU-bound work — continuous computation, the kind the seeded loaf represents — threads give you the same single pair of hands, just switching which task holds them. (Free-threaded CPython builds, available from Python 3.13 onward, can disable the GIL and let threads run in parallel — a different execution model, and not the default.) A second process is what actually hires the second baker: a separate Python interpreter, a separate GIL, genuinely simultaneous. Threads still earn their keep for blocking calls that release the GIL while they wait — just not for CPU-bound work.

So the fix matches the kind of work: a blocking call that's fine to hand off and wait on just needs a thread —

result = await asyncio.to_thread(blocking_call)

— but continuous hand-kneading is genuinely CPU-bound, and no amount of thread-juggling frees Ruby's one set of hands. That needs an actual second baker, running at the same instant as her own:

from concurrent.futures import ProcessPoolExecutor

loop = asyncio.get_running_loop()
with ProcessPoolExecutor() as pool:
    result = await loop.run_in_executor(pool, knead_seeded_dough)

asyncio doesn't make Ruby's hands faster. It makes sure they're doing useful work instead of standing around waiting.

One thread. Many Tasks. Cooperative scheduling. Yield while waiting. Never block the event loop.

Next lesson The Singleton Pattern: Ruby Rabbit and the Bakery's One Price Board