Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 5 · Concept · 20 min · revision 3

Concurrency for I/O: The Event Loop Mental Model

Build an accurate picture of the asyncio event loop: what runs when, what await really suspends, and why one thread can serve thousands of waiting calls.

Contentsand lesson path

What you will learn

  • Explain how the event loop schedules coroutines and predict whether a piece of async code runs concurrently or sequentially.

Prerequisites: Python Foundations

01. Why it matters

A backend service spends most of its life waiting: for a database to answer, for an upstream API to respond, for a file to arrive. While one request waits, the machine is idle. Serving each waiting request with its own operating-system thread works, but threads cost memory and context switches, and in the default CPython build the GIL (global interpreter lock) lets only one thread run Python code at a time (the optional free-threaded build, experimental in Python 3.13 and officially supported since 3.14, removes that limit, but most services do not run on it yet). The alternative used by FastAPI, uvicorn and most modern Python services is one thread that is never supposed to block: it starts a wait, moves on to other work, and comes back when the wait is over.

You have already written async def endpoints in the FastAPI fundamentals skill, and you have met this execution model in JavaScript in The Event Loop: Tasks, Microtasks and Rendering. The ideas transfer: a single thread, a queue of things to resume, and strict rules about when the thread is free. This lesson builds the Python version of that model, so you can look at any async code and predict whether it runs sequentially or with the waits overlapped.

02. One worker, many waits

First, a distinction that decides everything. Work is I/O-bound when the task spends its time waiting for something outside the process: an HTTP response, a database query, a sleep. Work is CPU-bound when the process itself computes: resizing an image, parsing a huge file, hashing passwords. Async helps only the first kind, because waiting is exactly what can be overlapped.

The three words you will meet everywhere:

  • A coroutine is what calling an async def function gives you: an object describing work that can run in steps, pausing at certain points. Calling the function does not yet run the body.
  • await marks a suspension point: this coroutine stops here, hands the thread back, and waits for the awaited thing to finish.
  • The event loop is the scheduler in one thread: it keeps a set of runnable coroutines, runs each until it suspends or finishes, and wakes the ones whose waits have completed.

The key sentence, worth memorising: async def does not make code concurrent. It makes code suspendable. Concurrency appears only when several suspendable pieces are in flight at once, so that when one suspends, the loop has something else to run. Writing await in a straight line, one call after another, is still sequential code with extra steps.

03. Watch it run: sequential, then overlapped

Both scripts below call the same fetch three times, where each call waits 0.30 s. A helper prints the loop clock at every step as t= seconds since the start, rounded to a tenth of a second. The rounding hides the few milliseconds of overhead your machine adds, so you should see exactly the lines shown, and you can read off what the single thread does.

Python · sequential.py
import asyncio

T0 = 0.0


def at(message: str) -> None:
    elapsed = asyncio.get_running_loop().time() - T0
    print(f"[t={elapsed:.1f}] {message}")


async def fetch(name: str, seconds: float) -> str:
    at(f"{name}: request sent")
    await asyncio.sleep(seconds)  # the only wait: pure I/O time
    at(f"{name}: response arrived")
    return name.upper()


async def main() -> None:
    global T0
    T0 = asyncio.get_running_loop().time()
    at("main: start")
    results = [await fetch("a", 0.30), await fetch("b", 0.30),
               await fetch("c", 0.30)]
    at(f"main: done, results={results}")


asyncio.run(main())
Expected output
[t=0.0] main: start
[t=0.0] a: request sent
[t=0.3] a: response arrived
[t=0.3] b: request sent
[t=0.6] b: response arrived
[t=0.6] c: request sent
[t=0.9] c: response arrived
[t=0.9] main: done, results=['A', 'B', 'C']

Each await suspends main until that call finishes, so the three waits happen back to back: 0.90 s in total. The loop is technically free during each sleep, but it has nothing else to do, so the waits add up. Now give it something else to do, by starting all three calls as tasks before waiting for any of them. Tasks are the scheduling wrapper the loop keeps in its list; the next lesson covers them properly.

Python · overlapped.py (only main changes)
async def main() -> None:
    global T0
    T0 = asyncio.get_running_loop().time()
    at("main: start")
    tasks = [asyncio.create_task(fetch(name, 0.30))
             for name in ("a", "b", "c")]
    results = await asyncio.gather(*tasks)
    at(f"main: done, results={results}")
Expected output
[t=0.0] main: start
[t=0.0] a: request sent
[t=0.0] b: request sent
[t=0.0] c: request sent
[t=0.3] a: response arrived
[t=0.3] b: response arrived
[t=0.3] c: response arrived
[t=0.3] main: done, results=['A', 'B', 'C']

Same thread, same three 0.30 s waits, 0.30 s total. create_task does not run a coroutine on the spot: it puts the new task on the loop's list of work to start. All three start, and send their requests at t=0.0, as soon as main suspends at await asyncio.gather(...). While all three sleeps are pending, the loop simply idles until the first completes. This is the whole trick behind async I/O: not doing the waits faster, but refusing to queue waits that could be happening at the same time.

04. Calling is not running

Because calling an async def function only creates a coroutine object, forgetting to drive it is a classic silent bug:

Python · never_awaited.py
import asyncio


async def save(item: str) -> None:
    await asyncio.sleep(0.10)
    print(f"saved {item}")


async def main() -> None:
    save("ticket-1")  # creates a coroutine object, then discards it
    print("main: returned without saving")


asyncio.run(main())
Expected output (stdout)
main: returned without saving

Nothing is saved: the body of save never ran. Python also prints a RuntimeWarning: coroutine 'save' was never awaited on stderr, which is your main clue when this happens in a bigger program. The reverse mistake exists too: await only works on awaitables (coroutines, tasks, futures), so await time.sleep(1) raises a TypeError rather than waiting politely. Every await needs an async thing on the right; every async thing needs an await or a task to run it.

05. What the loop is not

The loop is not a pool of threads and it is not parallelism. It is one thread that must never be held. The moment any code on the loop stops waiting and starts grinding — a blocking library call, time.sleep, a tight loop — everything else stops too, because there is no other thread to pick up the work. You can watch it happen:

Python · blocked.py
import asyncio
import time

T0 = 0.0


def at(message: str) -> None:
    elapsed = asyncio.get_running_loop().time() - T0
    print(f"[t={elapsed:.1f}] {message}")


async def heartbeat() -> None:
    """A cheap task that logs every 0.20 s, like a health check."""
    while True:
        at("heartbeat: alive")
        await asyncio.sleep(0.20)


async def report() -> None:
    at("report: blocking the thread with time.sleep(1.0)")
    time.sleep(1.0)  # blocks: there is no await inside
    at("report: done")


async def main() -> None:
    global T0
    T0 = asyncio.get_running_loop().time()
    beater = asyncio.create_task(heartbeat())
    await asyncio.sleep(0.30)  # let the heartbeat tick twice
    await report()
    await asyncio.sleep(0.30)
    beater.cancel()


asyncio.run(main())
Expected output
[t=0.0] heartbeat: alive
[t=0.2] heartbeat: alive
[t=0.3] report: blocking the thread with time.sleep(1.0)
[t=1.3] report: done
[t=1.3] heartbeat: alive
[t=1.5] heartbeat: alive

The heartbeat is a perfectly good task that should tick every 0.20 s. Between t=0.2 and t=1.3 it goes silent and misses five ticks: time.sleep holds the single thread, and the loop cannot run anyone else. Its late tick at t=1.3 comes only after report has finished. In a real service this gap is every request you are not serving, which is why detecting and fixing blocking calls gets its own lab later in this skill.

Two more boundaries of the model. A process normally runs one loop: one uvicorn worker is one event loop shared by all its async def endpoints, so they all feel the same blockage. And for CPU-bound work, async gives you nothing: there is no wait to overlap. The GIL aside, the honest summary is that async Python is a tool for I/O-bound concurrency, and the lab shows what to do when the slow thing is not I/O. Async database drivers are the same idea applied to queries; the SQLAlchemy data access skill covers them.

06. Check your understanding

Practice check · 3 questions

Predict what the loop does

Apply the model to three small pieces of code.

Q1. Both functions below are started as shown. In what order do the four prints happen? left sleeps 0.20 s, right sleeps 0.10 s. async def left(): print("left: start") await asyncio.sleep(0.20) print("left: end") async def right(): print("right: start") await asyncio.sleep(0.10) print("right: end") async def main(): task = asyncio.create_task(left()) await right() await task
Q2. Which of these jobs is the best fit for asyncio in a web service?
Q3. Inside an async def, a colleague writes `await time.sleep(1)`. What happens when that line runs?
Practice only: not graded, not saved, not evidence.

07. Apply it

Take an endpoint you know (from the FastAPI labs, or a service you use) and list every operation it performs per request. Mark each one I/O-bound or CPU-bound, and for the I/O ones note which of them could be in flight at the same time — those are your overlappable waits.

Then time it like the demos: wrap the handler body with time.perf_counter() before and after, log the total, and predict whether the current code is sequential or overlapped. Keep the numbers; the practice for this skill has you fan out calls and prove the improvement with exactly this kind of timing log.

08. Review prompt

Without looking back: explain in three sentences what the event loop does when a coroutine hits await. Then say what these four programs have in common in their failure: save(item) called without await, await time.sleep(1), time.sleep(1) inside an async endpoint, and a 2 s image resize inside an async endpoint. Two of them are about suspension, two are about the single thread — which are which?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check