Sub topic 1
Why asyncio: concurrency for I/O-bound programs
Prerequisites
This chapter assumes you can:
- Write Python functions and classes, and use
withstatements. - Read and write
try/exceptblocks. - Explain what a generator is and how
yieldpauses a function. - Tell I/O-bound work (waiting on a network, disk, or database) apart from CPU-bound work (heavy computation). This chapter reviews the distinction.
The examples run on Python 3.8 or later. Later chapters use features that need Python 3.11 or later, and they say so when they do.
The problem: programs that mostly wait
Consider a script that fetches 100 web pages. Each request sends a few bytes, then waits for a server to answer. Most of that time the CPU does nothing. It waits for packets to cross a network.
A conventional script handles the pages one after another. If each page takes 200 ms, the whole job takes about 20 seconds. Almost all of that time is idle waiting, and the work itself is trivial.
This is an I/O-bound program: its speed is limited by how long it waits on input and output, not by how fast it computes. Web clients, API servers, chat bots, scrapers, and database-heavy services are usually I/O-bound.
A CPU-bound program is limited by computation instead. Examples are image resizing, parsing huge files, and numerical simulation. These need a different tool, as the sections below explain.
Concurrency versus parallelism
These two terms are often confused.
- Concurrency means making progress on several tasks during overlapping periods of time. Only one may be executing at any instant.
- Parallelism means executing several tasks at literally the same instant, which needs multiple CPU cores.
A cook who starts the rice, chops vegetables while it simmers, and returns to stir is concurrent. Two cooks working at two stoves are parallel.
For I/O-bound work, concurrency is enough. While one operation waits for the network, the program can start or continue another one. You don't need more cores, because the cores were idle anyway.
Three ways to overlap waiting
Python offers three common models for doing several things at once.
| Model | Unit of work | Scheduling | Parallel CPU use | Typical cost |
|---|---|---|---|---|
| Threads (`threading`) | OS thread | Preemptive: the OS switches threads at almost any moment | No for pure Python code, because of the global interpreter lock (GIL) | Memory per thread, locking bugs |
| Processes (`multiprocessing`) | OS process | Preemptive, by the OS | Yes | Startup time, data copied between processes |
| asyncio | Coroutine on one thread | Cooperative: code yields control only at `await` | No | You must write code in the async style |
The GIL is a lock inside the standard CPython interpreter that lets only one thread run Python bytecode at a time. Threads can still overlap waiting on I/O, because a thread releases the GIL while it blocks. They cannot speed up pure Python computation.
Asyncio takes a different route. It runs everything on a single thread, and the code decides when to hand control back. The next chapters cover the mechanism in detail. The key idea is that a function marked async def can pause at an await and let other work run, then resume when its result is ready.
What cooperative scheduling means
With threads, the operating system can interrupt your code between any two bytecode instructions. Shared data can change under you, so you need locks to protect it.
With asyncio, a coroutine runs without interruption until it reaches an await that actually has to wait. Code between two await points runs without interruption by other coroutines. That removes a whole class of race conditions, though not all of them, because state can still change across an await.
Cooperation also has a cost. If a coroutine never awaits, nothing else can run. A slow computation or a blocking call like time.sleep freezes every other coroutine on the loop. This is the most common asyncio mistake, and a later chapter covers it in depth.
A first comparison
The sequential version below simulates three I/O waits of one second each. It uses time.sleep, which blocks the whole thread.
import time
def fetch(n):
time.sleep(1) # stands in for a network request
return n * 2
start = time.perf_counter()
results = [fetch(1), fetch(2), fetch(3)]
elapsed = time.perf_counter() - start
print(results, f"{elapsed:.1f}s")It prints [2, 4, 6] 3.0s. Now the asyncio version, with asyncio.sleep standing in for the network call:
import asyncio
import time
async def fetch(n):
await asyncio.sleep(1) # stands in for a network request
return n * 2
async def main():
start = time.perf_counter()
results = await asyncio.gather(fetch(1), fetch(2), fetch(3))
elapsed = time.perf_counter() - start
print(results, f"{elapsed:.1f}s")
asyncio.run(main())It prints [2, 4, 6] 1.0s. The three waits overlap. Don't worry about gather and asyncio.run yet. Later chapters explain both. What matters here is that no extra threads were created. One thread started all three waits and picked each one up when its timer expired.
asyncio.sleep is a stand-in. Real programs await operations such as reading from a socket or querying a database through an async library.
Where asyncio does not help
Asyncio overlaps waiting. It cannot make computation faster. The following program has two coroutines that never wait:
import asyncio
import time
async def crunch(n):
total = 0
for i in range(n):
total += i * i
return total
async def main():
start = time.perf_counter()
await asyncio.gather(crunch(3_000_000), crunch(3_000_000))
elapsed = time.perf_counter() - start
print(f"{elapsed:.2f}s")
asyncio.run(main())The time printed is about the sum of the two computations, not the longer one. Each crunch runs to the end without a pause, so nothing overlaps. Wrapping CPU work in async def adds overhead and no speedup.
For CPU-bound work, use multiprocessing or concurrent.futures.ProcessPoolExecutor, or move the hot loop into a library that releases the GIL (for example NumPy for many operations). Asyncio can drive those from the outside, and a later chapter shows how.
Choosing a model
Use these criteria in practice:
- Number of concurrent operations. Asyncio coroutines are cheap, so thousands of simultaneous connections are practical. Thousands of OS threads are costly.
- Library support. A coroutine needs an async-aware library, such as
aiohttp,httpx, orasyncpg. If your only client is a blocking library, threads are simpler, or you can wrap the blocking call, as a later chapter shows. - Code style. Async code spreads. A function that awaits must itself be
async def, and so must its callers, up to the entry point. Adopt it for a whole component, not one function. - Predictability. Because switches happen only at
await, you can reason about where state may change. Preemptive threads give no such guarantee.
Common misunderstandings
- "Async makes my code faster." It makes waiting overlap. A program with one sequential chain of requests, each depending on the last, gains nothing.
- "Async means multiple threads." Plain asyncio uses one thread. Threads appear only when you ask for them.
- "Adding
asyncto a function makes it non-blocking." Blocking calls inside a coroutine still block the thread.
Summary of the working model
- I/O-bound programs spend most of their time waiting, so overlapping waits shortens total runtime.
- Concurrency is interleaved progress. Parallelism is simultaneous execution.
- Asyncio gives concurrency on one thread through cooperative scheduling: coroutines yield at
await. - It does not speed up CPU-bound code, and a coroutine that never awaits stalls everything else.
The next chapter looks inside the event loop to see how it decides which coroutine runs next.
Exercise
A script makes 50 independent HTTP requests using the blocking requests library, one after another, and takes about 25 seconds. A colleague converts the functions to async def and calls requests.get inside them, then runs them with asyncio.gather. The runtime is still about 25 seconds. Why, and what are two ways to get real overlap?
Show answer
requests.get is a blocking call. It never awaits, so each coroutine holds the only thread until its request finishes, and the other coroutines cannot start. The async def wrapper changes nothing. Two fixes: switch to an async-aware HTTP client such as httpx.AsyncClient or aiohttp, and await its calls; or keep requests and run each call in a worker thread with asyncio.to_thread, which lets the loop continue while the thread blocks.
Exercise
Which of these workloads would benefit most from asyncio: (a) resizing 10,000 images, (b) a chat server holding 5,000 open connections that mostly sit idle, (c) computing a large matrix product in pure Python? Give the reason.
Show answer
(b). The server spends nearly all its time waiting for messages, so one thread can serve all the connections by switching between them at await points. (a) and (c) are CPU-bound, so asyncio would add overhead without overlapping any work. Those need processes or a library that does the computation outside the GIL.