Skip to content

Lesson 1 of 9 · 22m

The Event Loop Is a Scheduler, Not a Thread Pool

The single-threaded cooperative scheduling model behind asyncio, what actually happens at await, and why one blocking call can freeze a service.

The first async outage I debugged had no deadlock, no exception, and no obvious slowdown. A health-check endpoint simply stopped responding for twenty seconds at a time. The cause was one innocent-looking call to requests.get() inside an async request handler. Nothing crashed; the entire process was just busy waiting on one socket because asyncio never had a chance to run anything else.

That is the mental model: an asyncio program is usually one OS thread running a scheduler. Your coroutines are cooperatively scheduled work items. They run until they hit an await that cannot complete immediately, then control returns to the loop so another coroutine can run. Nobody preempts CPU-bound or blocking work for you.

A coroutine is a paused computation

import asyncio

async def fetch_user(user_id):
    row = await db.fetchrow('select * from users where id = $1', user_id)
    return dict(row)

coro = fetch_user(42)      # creates a coroutine object; no query has run
result = await coro        # now it executes inside the current task

Calling an async function does not execute it. It creates a coroutine object. await drives that coroutine until completion, while allowing the surrounding task to yield whenever the inner operation is pending.

The loop only switches at await points

async def noisy_worker():
    for n in range(10_000_000):
        _ = n * n
    return 'done'

async def ticker():
    while True:
        print('tick')
        await asyncio.sleep(1)

If noisy_worker() starts first, ticker() will not print anything until the loop finishes all ten million iterations. There is no scheduler quantum in Python instructions. A task yields when it awaits something that suspends, such as asyncio.sleep, a network read, or a queue operation.

await asyncio.sleep(0) is the manual yield. It is occasionally useful inside a long loop that must remain cooperative, but needing it everywhere is usually a sign the work belongs in a thread or process.

Blocking calls are process-wide stalls

These calls do not magically become async because they are inside an async function:

time.sleep(1)                 # blocks the whole event loop
requests.get(url)             # blocking socket I/O
open(path).read()             # normal file I/O is synchronous
result = psycopg2.execute()   # blocking database driver

Use async-native libraries (aiohttp, httpx.AsyncClient, asyncpg, aioredis-era successors such as redis.asyncio) or explicitly offload blocking work with asyncio.to_thread() when no async library exists.

What async is good at

Async shines when one process must juggle many mostly-idle connections: HTTP APIs, websocket fan-out, database-heavy services, queues, and proxies. It does not make Python computation parallel. For CPU-heavy work you still need worker processes, native extensions, or a different runtime boundary.

Field notes

  • If every endpoint latency rises together, suspect one blocking call rather than ten unrelated slow endpoints.
  • asyncio.run() creates and closes a loop; use it once at the application boundary, not inside library functions.
  • Coroutine objects never run just because they exist. Forgetting await often produces the warning 'coroutine was never awaited' long after the real mistake.
  • The event loop is cheap, but context switches still cost something. Millions of tiny tasks can be slower than a bounded pipeline.

Was this lesson helpful?

Sign in to rate