01C.1 Concurrency, Parallelism and Context Switching

FoundationsLesson 1 of 717,160 words7 parts
Module 01C · 0 of 7 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7

Your AI service waits on slow LLM calls, parses PDFs, embeds batches of text, and serves many users at once, all in the same process. Before you can reason about any of that (async, threads, locks, the GIL, shared memory), you need five precise ideas: what concurrency is, what parallelism is, whether a task is I/O-bound or CPU-bound, what blocking and non-blocking really mean at the operating-system level, and what a context switch costs. This lesson builds those five ideas from zero, then proves each one with small standard-library experiments you can run on your own machine. It is the foundation for the rest of Module 01C: async internals (01C.2), race conditions (01C.3), deadlocks and starvation (01C.4), the GIL (01C.5), memory (01C.6) and shared memory (01C.7).

What you'll learn

  • The difference between dealing with many things at once (concurrency) and doing many things at once (parallelism), with the one-cook and two-cooks analogy and Rob Pike's definitions
  • The four combinations: neither, concurrency without parallelism, parallelism without concurrency, and both, each shown in running code
  • The same two jobs (an I/O-bound one and a CPU-bound one) done four ways: sequential, threads, asyncio and processes, with timings and an honest reading of the results
  • How to classify a task as I/O-bound, CPU-bound or mixed: CPU time versus wall time, time.process_time, time.thread_time, top, and a reusable classify() helper
  • Mixed workloads, Amdahl's law (in code, no notation) and how it caps every speed-up, plus a pointer to Little's law
  • What blocking means: system calls, parked threads, O_NONBLOCK, EAGAIN, select/poll/epoll/kqueue/IOCP, the selectors module and socket.setblocking(False)
  • Which calls cannot be made non-blocking (regular files, DNS, CPU work), how blocking calls hide inside async code, and three ways to detect them
  • What a context switch saves and restores, how thread, process, coroutine and generator switches differ, typical costs and why they are only orders of magnitude, preemptive versus cooperative scheduling, voluntary versus involuntary switches, sys.getswitchinterval and thread oversubscription
  • A decision table: which model for LLM fan-out, embedding batches, PDF parsing, tokenization and file ingestion, and a failure gallery of the mistakes the topics above cause

What you don't need

  • Any operating-systems course. Every kernel idea here is explained in plain words first and precise terms second.
  • Knowledge of asyncio internals. 01B.3 teaches the practical API and 01C.2 opens the engine; this lesson only uses asyncio as one of four tools.
  • Threads and locks beyond "a thread is a separate flow of execution in the same process". Lock-related bugs start in 01C.3.
  • Any LLM, API or provider. Every example is pure Python.

Setup

No API key needed, nothing to install: every example uses only the standard library (asyncio, threading, multiprocessing, concurrent.futures, selectors, socket, time, resource). You need Python 3.11 or newer. If you are not inside a project, a plain python3 file.py works; inside a uv project from 01B.1 use uv run python file.py.

bash
python3 --version
# Is this a free-threaded build? (3.13+ only; True means the GIL is on, which is the normal case)
python3 -c "import sys; print(sys._is_gil_enabled())"

All Output: blocks in this lesson were produced on Python 3.14.6 (the normal build, GIL enabled) on macOS with 10 CPU cores. Anything that depends on the machine (timings, switch counts) is labelled illustrative: the exact numbers on your computer will differ, but the ordering and the ratios should match. Multi-process examples use if __name__ == "__main__":. This is mandatory on macOS and Windows, where child processes re-import your file, and good practice everywhere.


What you must be able to do after this lesson#

  • Explain the difference between concurrency and parallelism
  • Classify a task as I/O-bound, CPU-bound or mixed by measuring CPU time against wall time
  • Choose between threads, asyncio and processes for a given task
  • Explain what blocking means and spot blocking calls inside async code
  • Explain what a context switch costs and why
  • Use Amdahl's law to estimate the limit of a speed-up

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"Concurrency is not parallelism" Part 1
"Our LLM calls are I/O-bound, so use asyncio" Part 2 and Part 3
"Embedding the corpus is CPU-bound, threads won't help" 3.2 and Part 6
"Parsing the PDFs saturates one core" 3.3 and 3.4
"That SDK call is blocking, it froze the whole server" 4.5
"Why is epoll the reason Node and asyncio scale?" 4.3
"Too many threads makes it slower" 5.7
"Context switches are expensive" (and "no, cheap") 5.4
"Use a thread pool for the sync SDK, a process pool for tokenizing" Part 6

Part 1: Two words people mix up#

1.1 The kitchen#

Imagine you are making dinner: a curry that needs 40 minutes of simmering, rice that needs 15 minutes of boiling, and a salad that needs 10 minutes of chopping.

One cook, one stove, working sequentially. You start the curry, stand watching it for 40 minutes, then boil the rice for 15, then chop for 10. Total: 65 minutes. The curry simmered while you did nothing else. That is a sequential program that blocks: it waits, idle, for something slow.

One cook, juggling. You start the curry, and while it simmers you start the rice, and while both are on the stove you chop the salad. You never stand still waiting. You glance at the pots now and then, and you stir whichever needs attention. Total: about 40 minutes, the length of the slowest simmer. There is still one cook: at any single instant you are doing exactly one thing (chopping, or stirring, or turning a dial). But you are dealing with three dishes at once. That is concurrency.

Two cooks. One cook handles the curry and the rice, and the other chops the salad and makes the dessert. At the same instant two things are being done by two people. That is parallelism.

Notice something important: the single juggling cook got the dinner done in 40 minutes without any extra help, because most of the time was waiting (simmering, boiling), not working. Hiring a second cook would have helped much less than learning to juggle. But if the work was chopping 50 kilos of onions, no amount of clever juggling helps: you need more hands. Keep that in mind: it is the entire lesson in miniature.

Kitchen Programming
The cook A unit of execution: a CPU core running a thread, a process or the event loop
A simmering pot An I/O wait: a network call, a disk read, a database query
Chopping onions CPU work: parsing, hashing, tokenizing, matrix maths
Juggling three dishes Concurrency: several tasks in progress at once
Two cooks at once Parallelism: several tasks executing at the same instant
The cook dropping the knife to stir a pot A context switch

1.2 Pike's definitions#

The most quoted distinction comes from Rob Pike, co-designer of Go, in his talk Concurrency is not parallelism (Heroku's Waza conference; the Go blog's write-up is dated 16 January 2013):

In programming, concurrency is the composition of independently executing processes, while parallelism is the simultaneous execution of (possibly related) computations.

Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once.

Those two sentences are the whole story, and they separate two different kinds of statements:

  • Concurrency is a property of the structure of your program. You have broken the problem into pieces (tasks, coroutines, threads, services) that can make progress independently of each other, in any interleaving. A concurrent program is designed to deal with many things at once. Whether it actually runs two things at the same instant is a different question.
  • Parallelism is a property of the execution. Two or more computations are literally running at the same physical moment on different CPU cores (or different machines, or a GPU). That needs hardware: at least two cores.

You can design for concurrency and get parallelism for free if the hardware and the runtime allow it; you can also get concurrency with no parallelism at all.

1.3 The four combinations#

Every program sits in one of four cells. The table first, then each one running.

One thing runs at a time Several things run at the same instant
Work is one sequential task Ordinary script: no concurrency, no parallelism Parallelism with the most trivial concurrency structure: one task split into identical independent chunks, no interaction, only a final merge (data parallelism). Parallelism with no concurrency structure at all lives below the program: SIMD, vector instructions, one GPU kernel launch
Work is several independent tasks in progress Concurrency without parallelism: one thread juggling (asyncio, generators, a single-core machine) Concurrency and parallelism: a thread or process pool on a multi-core machine, or a fleet of services

Concurrency without parallelism

One thread, three jobs, each of which yields control back to a juggler between steps. A generator's yield is a pause point: the function stops, remembers where it was, and later resumes. This is the same idea as an await in asyncio (01C.2 shows they are literally related), without any event loop:

python
# conc_vs_par.py (first half): ONE thread juggling three jobs
import threading
from collections import deque


def job(name: str, steps: int):
    for step in range(1, steps + 1):
        yield f"{name} step {step}"  # a pause point: control goes back to the juggler


def round_robin(jobs):
    ready = deque(jobs)  # popleft() is O(1); a plain list's pop(0) is O(n)
    while ready:
        current = ready.popleft()
        try:
            print(" ", next(current))
            ready.append(current)  # not finished: back of the queue
        except StopIteration:
            pass


print("one thread, three jobs, interleaved:")
print(" thread:", threading.current_thread().name)
round_robin([job("ticket", 2), job("invoice", 3), job("contract", 1)])
Output8 lines
one thread, three jobs, interleaved:
 thread: MainThread
  ticket step 1
  invoice step 1
  contract step 1
  ticket step 2
  invoice step 2
  invoice step 3

The three jobs were in progress together, their steps interleaved, yet only MainThread ever ran. This is concurrency with zero parallelism. If the "steps" were network waits instead of print calls, the one thread could keep hundreds of requests in flight at once: that is what asyncio does.

Parallelism with trivial concurrency

One job, split into identical chunks that never talk to each other and never wait for each other, each chunk handled by its own process on its own core. The "juggling" is trivial: there is nothing to juggle, only a final addition. This is data parallelism, the shape of most CPU-bound speed-ups (image batches, token counting over files, scoring rows):

python
# conc_vs_par.py (second half): one task, four identical chunks, four processes
from concurrent.futures import ProcessPoolExecutor


def chunk_sum(bounds: tuple[int, int]) -> int:
    lo, hi = bounds
    return sum(i * i for i in range(lo, hi))


def main() -> None:
    chunks = [(0, 250_000), (250_000, 500_000), (500_000, 750_000), (750_000, 1_000_000)]
    with ProcessPoolExecutor(max_workers=4) as pool:
        parts = list(pool.map(chunk_sum, chunks))  # map() keeps input order
    print("four processes, one task split in four:")
    print(" partial sums:", parts)
    print(" total matches serial:", sum(parts) == chunk_sum((0, 1_000_000)))


if __name__ == "__main__":
    main()
Output3 lines
four processes, one task split in four:
 partial sums: [5208302083375000, 36458239583375000, 98958177083375000, 192708114583375000]
 total matches serial: True

Save both fragments together as conc_vs_par.py to run them. The second one has no interleaving to reason about: it is "embarrassingly parallel", which is why it is the easiest kind of parallelism to get right.

Both

A thread pool downloading 20 files while another process pool parses the ones that have arrived: many tasks in progress (concurrency) and several executing at the same instant (parallelism). Most production AI services are in this cell, and most bugs live here, because the pieces now interact. Parts 2 and 3 build one.

1.4 Why the distinction is not pedantry#

If you believe... You will... The reality
"Concurrent means faster" Add asyncio to a CPU-heavy function and see no gain Concurrency helps only when there is waiting to overlap. Interleaving two CPU jobs on one core makes both finish later, not sooner
"Parallel means concurrent" Assume a process pool "handles many requests at once" Four workers is parallelism of degree four. They have no scheduler for 10,000 waiting clients: concurrency needs structure for cheap waiting
"More threads, more speed" Create 500 threads for CPU work Threads beyond the number of cores add switching overhead; in standard CPython the GIL (01C.5) stops CPU-bound Python threads running in parallel at all
"Concurrency bugs only come from parallelism" Think a single-threaded asyncio program is race-free Races exist whenever another task can run between two of your steps, even on one thread (01C.3)

Three practical consequences follow, and the rest of the module keeps returning to them:

  1. Concurrency is a design choice; parallelism is a resource. Structure code so tasks are independent (concurrency). Then the runtime and hardware decide how much parallelism you actually get.
  2. Throughput and latency are different goals. Concurrency usually improves throughput (work finished per second) when waiting dominates. It rarely improves the latency of one task: a single LLM call takes as long as it takes. Parallelism can improve latency of one big computation (split it up), at a coordination cost.
  3. Whatever you add must pay for itself. Every concurrent or parallel mechanism has overheads: memory per task, switching cost, coordination, new bug classes. Part 6 makes that into a decision table.

What it means for an AI engineer. An LLM call is 99 % waiting on the network and on someone else's GPU. That is a concurrency problem: structure your code so hundreds of waits overlap, on one thread. Embedding a local corpus or parsing PDFs is a parallelism problem: you need more cores, and structure matters much less. Knowing which problem you have chooses the tool before you write a line.


Part 2: Four Python models, one task#

Python gives you four ordinary ways to run more than one thing: sequential (no concurrency), threads, asyncio, and processes. Let us run the same two jobs through all four, so the differences are measured, not asserted.

2.1 The two jobs#

  • Job A, I/O-bound. Eight "LLM calls" that each take 0.2 seconds of pure waiting. time.sleep(0.2) is the stand-in for a network round trip: the program uses essentially no CPU while it waits, exactly like a real HTTP call. (A real model call takes far longer, often seconds; shorter waits keep the experiment quick.)
  • Job B, CPU-bound. Four tasks that each compute 400,000 chained SHA-256 hashes. Think "tokenize four batches of documents": the CPU is busy the whole time and nothing is waiting.
python
# four_ways.py: the same two jobs done four ways (sequential, threads, asyncio, processes).
import asyncio
import hashlib
import time
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

CALLS = 8
LATENCY = 0.2


def fake_llm_call(i: int) -> str:
    time.sleep(LATENCY)  # blocking wait: the thread is parked, no CPU used
    return f"answer-{i}"


async def fake_llm_call_async(i: int) -> str:
    await asyncio.sleep(LATENCY)  # suspends only this coroutine
    return f"answer-{i}"


def burn(n: int) -> str:
    h = b"seed"
    for _ in range(n):
        h = hashlib.sha256(h).digest()
    return h.hex()[:8]


def timed(label: str, fn) -> tuple[str, float, object]:
    t0 = time.perf_counter()
    result = fn()
    return label, time.perf_counter() - t0, result


async def gather_all() -> list[str]:
    return await asyncio.gather(*(fake_llm_call_async(i) for i in range(CALLS)))


async def _wrap(n: int) -> str:
    return burn(n)  # an async function that never awaits: it runs to completion


async def _cpu_async(n: int, jobs: int) -> list[str]:
    # 'async' does not make CPU work parallel: each burn() runs to completion
    return await asyncio.gather(*(_wrap(n) for _ in range(jobs)))


def main() -> None:
    rows = []
    # ---- Job A: I/O-bound ----
    rows.append(("A io", *timed("sequential", lambda: [fake_llm_call(i) for i in range(CALLS)])))
    with ThreadPoolExecutor(max_workers=CALLS) as pool:
        rows.append(("A io", *timed("threads", lambda: list(pool.map(fake_llm_call, range(CALLS))))))
    rows.append(("A io", *timed("asyncio", lambda: asyncio.run(gather_all()))))
    with ProcessPoolExecutor(max_workers=CALLS) as pool:
        list(pool.map(fake_llm_call, range(CALLS)))  # warm-up: start the workers
        rows.append(("A io", *timed("processes", lambda: list(pool.map(fake_llm_call, range(CALLS))))))
    # ---- Job B: CPU-bound ----
    N, JOBS = 400_000, 4
    rows.append(("B cpu", *timed("sequential", lambda: [burn(N) for _ in range(JOBS)])))
    with ThreadPoolExecutor(max_workers=JOBS) as pool:
        rows.append(("B cpu", *timed("threads", lambda: list(pool.map(burn, [N] * JOBS)))))
    rows.append(("B cpu", *timed("asyncio", lambda: asyncio.run(_cpu_async(N, JOBS)))))
    with ProcessPoolExecutor(max_workers=JOBS) as pool:
        list(pool.map(fake_llm_call, range(JOBS)))  # warm-up: sleeping tasks force all JOBS workers to exist
        rows.append(("B cpu", *timed("processes", lambda: list(pool.map(burn, [N] * JOBS)))))

    base = {}
    for job, label, secs, _ in rows:
        base.setdefault(job, secs)
        print(f"{job:6} {label:11} {secs:6.2f}s  speed-up x{base[job] / secs:4.1f}")


if __name__ == "__main__":
    main()

Save the script as four_ways.py to run it. A warm-up must run at least as many concurrent tasks as the pool has workers (here each task sleeps, so no single fast worker can take them all); otherwise some workers start inside the timer.

Example output · illustrative8 lines
A io   sequential    1.64s  speed-up x 1.0
A io   threads       0.21s  speed-up x 8.0
A io   asyncio       0.20s  speed-up x 8.1
A io   processes     0.21s  speed-up x 7.9
B cpu  sequential    0.30s  speed-up x 1.0
B cpu  threads       0.28s  speed-up x 1.1
B cpu  asyncio       0.29s  speed-up x 1.0
B cpu  processes     0.12s  speed-up x 2.5

Measured on Python 3.14.6 (GIL enabled), macOS, 10 cores. The seconds depend on your machine; the pattern does not.

2.2 Reading the results#

Job A (waiting): three models win, equally. Sequential costs 8 × 0.2 = 1.6 seconds. Threads, asyncio and processes all finish in about the time of one wait (0.2 s), a speed-up of about eight, because the work was never computation: it was eight waits, and all three models overlap them. The process pool only matched threads because we paid its start-up cost before timing (the warm-up line); a pool you create per request would lose badly (see 2.4).

Job B (computing): only processes win. Threads and asyncio finish in about the same time as the plain loop, a speed-up of about 1.0. Processes finish in roughly 40 % of the time (with four workers the ideal is about 4×; pickling, scheduling and sharing cores with the OS mean you rarely reach it: here about 2.5×). Why? CPU work needs a core, and in standard CPython ("with the GIL") only one thread at a time may execute Python bytecode. The asyncio row shows a different cause with the same effect: an async def that never awaits runs to completion on the loop, one after another. 01C.5 covers the GIL in depth; here you only need the observation.

2.3 What each model is#

The four models differ in what the unit of concurrency is, who decides when it switches, and what it costs. This table is the core reference of the lesson; Parts 4 and 5 explain every cell.

Sequential Threads asyncio Processes
Unit The one function call OS thread inside your process Coroutine / Task on one thread OS process with its own interpreter
Who schedules? You (program order) The operating system (preemptive) The event loop, at your await points (cooperative) The operating system (preemptive)
Switch happens... Never At any instruction boundary (the OS interrupts; CPython also hands over the GIL every 5 ms) Only at await At any time (OS time slices)
Memory Shared (one thread) Shared address space: threads see the same objects Shared, one thread Separate address spaces; data is copied or explicitly shared (01C.7)
Overlaps waiting? No Yes Yes Yes
Overlaps computing (standard CPython)? No No (GIL), except inside C code that releases it No Yes
Typical cost per unit None An OS stack (megabytes reserved, tens of KiB resident) and a kernel object About one kilobyte of Python objects A whole interpreter: tens of MB, tens to hundreds of ms to start
Typical scale One Hundreds to low thousands Tens of thousands of tasks About one per core for CPU-bound work
Typical bugs Slow Data races, deadlocks (01C.3, 01C.4) A blocking call freezing everyone; races at await Pickling errors, copying huge data
Bound by Everything adds up Cores (minus the GIL) and memory One core and the slowest callback Cores and memory

(The "typical scale" row is deliberately approximate: it depends on memory, the OS and the workload. The point is the orders of magnitude: thousands of OS threads is already heavy, tens of thousands of tasks is routine, and processes cap out at about the number of cores for CPU-bound work.)

The mental pictures:

  • Threads are several cooks in one kitchen sharing all the pots and ingredients. Fast hand-offs, but two cooks reaching for the same pot cause trouble.
  • asyncio is the one juggling cook. No two actions collide, because there is one cook, but a single cook who stops to stare at a pot freezes the whole kitchen.
  • Processes are cooks in separate kitchens. They cannot knock over each other's pots, but passing an ingredient means carrying it across the street (serialization), and each kitchen costs rent (memory and start-up).

The event loop's trick is worth one picture before Part 4 explains it: one thread asks the operating system "tell me which of these 5,000 sockets has data" and sleeps until the answer arrives.

flowchart LR
    subgraph one ["One thread, many waits"]
        loop["event loop"] -->|"register sockets"| sel["selector<br/>(epoll / kqueue / select)"]
        sel -->|"which sockets are ready?"| loop
        loop -->|"resume coroutine"| c1["coroutine A"]
        loop -->|"resume coroutine"| c2["coroutine B"]
    end
    c1 -->|"await: hand control back"| loop
    c2 -->|"await: hand control back"| loop

2.4 Start-up costs: why "warm the pool" matters#

A process is the most expensive unit. In our benchmark we started the process pool before the stopwatch. If you pay start-up on every call, the picture changes:

Model Cost to create one unit (order of magnitude) When it hurts
Thread tens to a few hundred microseconds Creating a thread per tiny task
Task / coroutine A few microseconds Almost never
Process (fork) milliseconds (copy-on-write page tables) Per-request processes
Process (spawn / forkserver) tens to hundreds of milliseconds (a fresh interpreter, re-importing your modules) Every call, and especially with heavy imports (import numpy, a tokenizer, a model)

The operational rules that follow: create pools once and reuse them; have the worker initializer load heavy resources (a tokenizer, a model, a connection) once per worker instead of once per task; and remember that on macOS and Windows the default start method is spawn, so every worker re-imports your module, which is why the if __name__ == "__main__": guard is mandatory. On Linux the default start method is fork up to Python 3.13 and forkserver from 3.14 (verified in the 3.14 release notes: "On Unix platforms other than macOS, 'forkserver' is now the default start method"). 01C.7 covers start methods properly.

What it means for an AI engineer. For an I/O-bound LLM fan-out, asyncio and threads are the contenders; the choice is mostly about whether your SDK has a native async client (01B.3, 03.9). For CPU-bound work such as tokenizing a corpus, processes (or native code that releases the GIL) are the answer. Everything in between is Part 3's subject: you must measure which one you have.


Part 3: I/O-bound vs CPU-bound#

01B.3 §1.2 gave the two-sentence version. Here is the version you can measure, because "is it I/O-bound?" decides the tool for everything that follows.

3.1 The definitions, and the spectrum#

A task is I/O-bound when its speed is limited by waiting for something outside the CPU: a network reply, a disk, a database, a user, another process. Make the CPU ten times faster and the task finishes at almost the same time. A task is CPU-bound when its speed is limited by how fast the CPU executes instructions: parsing, hashing, compressing, tokenizing, matrix maths, running a model on the CPU. Make the CPU ten times faster and the task finishes about ten times sooner.

Real tasks sit on a spectrum, and the same code can move along it depending on its input and its environment:

Task Mostly Why
Calling a hosted LLM (from your side) I/O Seconds of network and queueing, microseconds of your CPU
Waiting on a database or vector store I/O The work is on their CPU, not yours
Downloading a PDF I/O Network
Extracting text from a PDF (pypdf, pdfminer) CPU Parsing, decoding fonts, laying out characters
json.loads of a 200 MB file CPU Pure computation (and memory)
Tokenizing a corpus with tiktoken or a Hugging Face tokenizer CPU Native code, CPU-heavy
Embedding with a local model CPU or GPU Matrix maths on your hardware
Embedding via a provider API I/O A network call again
Regex over a million log lines CPU Matching engine work
Reading a big file from a fast SSD Mixed The disk is quick, so the CPU for decoding often dominates
TLS handshakes, compression (gzip) CPU Cryptography and compression inside "I/O" code
Validating 10,000 objects with Pydantic CPU (fast, native) Small per item, large in bulk

There are also other limits, worth naming so you do not blame the wrong thing:

  • Memory-bound: speed is limited by how fast data moves between RAM and the CPU (large array scans, matrix ops on data that does not fit in cache). More cores can barely help once memory bandwidth is saturated.
  • Network-bandwidth-bound: you are downloading gigabytes: the pipe, not latency, limits you. More concurrent connections help only until the link is full.
  • Rate-limit-bound / provider-bound: the remote service limits you (01B.4 Part 4). More concurrency makes it worse.
  • Lock-bound: threads queue on a lock (01C.4).

3.2 Measuring CPU time versus wall time#

The simplest, most reliable test uses two clocks:

  • Wall-clock time (time.perf_counter()): the real time that passed, as if you watched a stopwatch.
  • CPU time (time.process_time()): the time the CPU spent executing your process (user plus kernel time, summed across all its threads), excluding time spent sleeping or waiting.

Their ratio, CPU time / wall time, is the diagnosis:

cpu / wall Meaning
Near 0 (below about 0.2) The process was mostly waiting: I/O-bound. Concurrency (threads, asyncio) will help
Near 1.0 One core was busy the whole time: CPU-bound. Concurrency will not help; you need less work or more cores (processes, native code)
Above 1.0 (up to the number of cores) Several threads were genuinely executing in parallel: native code released the GIL, or a free-threaded build
Between, such as 0.5 to 0.8 Mixed: split the pipeline (3.3)
python
# classify.py: is this function I/O-bound or CPU-bound? Compare CPU time with wall time.
import hashlib
import json
import time
from collections.abc import Callable


def classify(fn: Callable[[], object]) -> tuple[str, float]:
    """Run fn once and return (label, cpu_share) where cpu_share = CPU time / wall time."""
    wall0, cpu0 = time.perf_counter(), time.process_time()
    fn()
    wall = time.perf_counter() - wall0
    cpu = time.process_time() - cpu0  # CPU time of this process (all its threads)
    share = cpu / wall if wall else 0.0
    if share < 0.2:
        label = "I/O-bound (mostly waiting)"
    elif share > 0.8:
        label = "CPU-bound (mostly computing)"
    else:
        label = "mixed"
    return label, share


def wait_for_llm() -> None:
    time.sleep(0.3)  # stands in for a network call: the process uses no CPU


def parse_big_json() -> None:
    doc = json.dumps([{"id": i, "text": "refund request " * 20} for i in range(300_000)])
    json.loads(doc)  # pure computation


def hash_loop() -> None:
    h = b"x"
    for _ in range(400_000):
        h = hashlib.sha256(h).digest()


def fetch_then_parse() -> None:
    time.sleep(0.15)  # wait for the "download"
    parse_big_json()  # then compute on it


if __name__ == "__main__":
    for fn in (wait_for_llm, parse_big_json, hash_loop, fetch_then_parse):
        label, share = classify(fn)
        # share is rounded to one decimal so the printed value is stable across machines
        print(f"{fn.__name__:16} cpu/wall ~ {share:.1f}  -> {label}")
Example output · illustrative4 lines
wait_for_llm     cpu/wall ~ 0.0  -> I/O-bound (mostly waiting)
parse_big_json   cpu/wall ~ 1.0  -> CPU-bound (mostly computing)
hash_loop        cpu/wall ~ 1.0  -> CPU-bound (mostly computing)
fetch_then_parse cpu/wall ~ 0.7  -> mixed

Three details worth knowing:

  • Which clock? time.process_time() counts the whole process, including every thread. time.thread_time() counts only the calling thread. Use thread_time to profile one thread inside a threaded program. Neither counts time spent inside child processes: for those use os.times() or resource.getrusage(resource.RUSAGE_CHILDREN) (Unix). So classify() run on code that uses a process pool will report "I/O-bound", because the work happens in the children: classify the worker function itself, or compare getrusage(RUSAGE_CHILDREN).
  • perf_counter for wall time. time.time() can jump if the system clock is adjusted; perf_counter() and monotonic() never go backwards.
  • Sleeping is not CPU. time.sleep(0.3) consumes 0.3 s of wall time and about zero CPU time. That is why a thread blocked in sleep or in a socket recv costs the CPU nothing and many of them can overlap.

The same idea, with no code, from the shell. The shell's time reports the three numbers:

console
$ time python3 -c "import time; time.sleep(1)"
real    0m1.03s
user    0m0.02s
sys     0m0.01s
$ time python3 -c "sum(i*i for i in range(10_000_000))"
real    0m0.55s
user    0m0.54s
sys     0m0.01s

Example output (illustrative — your exact output will differ). real is wall time; user + sys is CPU time. In the first command user + sys is far below real: I/O-bound (a sleep). In the second they are almost equal: CPU-bound. In PowerShell use Measure-Command { python3 file.py } for wall time; Windows' Task Manager shows CPU use per process.

And for a running service, look at CPU use per process or per thread:

console
$ top -o cpu              # macOS: sort by CPU
$ top -H -p <PID>         # Linux: -H shows threads, -p picks a process
$ ps -o pid,pcpu,etime,time -p <PID>   # CPU share, elapsed time, total CPU time

A service pinned at about 100 % CPU in top while requests queue is CPU-bound on one core (a Python process using a single thread of Python code cannot go over about 100 % in standard CPython). A service idling at 3 % CPU while latency is high is I/O-bound: it is waiting on something else.

If you need where the time goes, not just the ratio, profilers answer it: cProfile for CPU time per function, py-spy for sampling a running process, and asyncio debug mode (4.5) for stalls. 01B.10 covers debugging tools.

3.3 Mixed workloads: the usual case#

Real jobs are pipelines of waiting and computing. A PDF-ingestion service downloads a file (wait), parses it (CPU), calls an embedding API (wait), and writes to a vector store (wait). Pure I/O-bound or CPU-bound tasks are the exception.

The failure mode is putting the CPU stage inside the I/O model. In asyncio, a CPU stage runs on the event-loop thread and freezes every other coroutine while it runs. The fix is to split the pipeline: let the cheap-to-wait model (the loop) do the waits and send the CPU stage to a worker that can compute in parallel.

python
# mixed_pipeline.py: a PDF-ingestion-shaped job: wait for a download (I/O), then parse (CPU).
# Three designs: sequential; asyncio only (CPU runs on the loop); asyncio + a process pool.
import asyncio
import hashlib
import time
from concurrent.futures import ProcessPoolExecutor

DOCS = 12
DOWNLOAD_SECONDS = 0.2
PARSE_ROUNDS = 150_000  # roughly 0.03 s of CPU per document


def parse(doc_id: int) -> str:
    # stands in for PDF text extraction: pure CPU, no waiting
    h = str(doc_id).encode()
    for _ in range(PARSE_ROUNDS):
        h = hashlib.sha256(h).digest()
    return f"doc{doc_id}:{h.hex()[:6]}"


def sequential() -> list[str]:
    out = []
    for i in range(DOCS):
        time.sleep(DOWNLOAD_SECONDS)
        out.append(parse(i))
    return out


async def asyncio_only() -> list[str]:
    async def one(i: int) -> str:
        await asyncio.sleep(DOWNLOAD_SECONDS)
        return parse(i)  # runs ON the event loop: blocks every other coroutine meanwhile

    return await asyncio.gather(*(one(i) for i in range(DOCS)))


async def asyncio_plus_processes(pool: ProcessPoolExecutor) -> list[str]:
    loop = asyncio.get_running_loop()

    async def one(i: int) -> str:
        await asyncio.sleep(DOWNLOAD_SECONDS)
        return await loop.run_in_executor(pool, parse, i)  # CPU leaves the loop

    return await asyncio.gather(*(one(i) for i in range(DOCS)))


def timed(fn):
    t0 = time.perf_counter()
    out = fn()
    return time.perf_counter() - t0, out


if __name__ == "__main__":
    t_seq, ref = timed(sequential)
    t_async, out_async = timed(lambda: asyncio.run(asyncio_only()))
    with ProcessPoolExecutor(max_workers=4) as pool:
        list(pool.map(time.sleep, [0.2] * 4))  # sleeping tasks force all 4 workers to start before timing
        t_mix, out_mix = timed(lambda: asyncio.run(asyncio_plus_processes(pool)))
    print(f"sequential          {t_seq:5.2f} s")
    print(f"asyncio only        {t_async:5.2f} s")
    print(f"asyncio + processes {t_mix:5.2f} s")
    print("all three agree:", ref == out_async == out_mix)
Example output · illustrative4 lines
sequential           3.08 s
asyncio only         0.56 s
asyncio + processes  0.35 s
all three agree: True

Read it carefully, because both obvious conclusions are partly wrong:

  • asyncio alone beat sequential by a wide margin (0.56 s versus 3.08 s). The 12 downloads (12 × 0.2 s) overlapped, which is the big win. So async is not "useless" for mixed workloads.
  • Sequential (3.08 s) is slower than the sum of its parts (12 × 0.2 s of waiting plus 12 × 0.03 s of parsing is about 2.7 s), probably because each parse starts on a core that has just been idle and cores ramp up after sleeping: a real benchmarking trap.
  • The process pool (four workers, all started before the timer) added a further improvement (0.35 s versus 0.56 s) because the parses ran in parallel instead of one at a time on the loop.
  • The bigger risk is not in this table: during asyncio only, each parse froze the loop. In a real service handling other requests, every other user's request would stall for the duration of each parse. A benchmark of one job hides that; a latency measurement under load shows it. 4.5 measures the freeze directly.

loop.run_in_executor(pool, fn, *args) is the bridge. 01B.3 §3.8 covers it and asyncio.to_thread. The general recipe for a mixed pipeline:

  1. Make every wait stage native-async (or thread-pooled if its SDK is sync-only).
  2. Make every compute stage a plain function run in a process pool (or a thread pool if the heavy lifting is a C extension that releases the GIL, which you have measured).
  3. Connect the stages with bounded queues (01B.4 Part 3) so a fast stage cannot flood a slow one.
  4. Size each stage's concurrency to its own bottleneck: roughly cores for the CPU stage, a provider-safe limit for the wait stage.

3.4 Amdahl's law: the ceiling on every speed-up#

Suppose you parallelize a job across 8 cores. Do you get 8 times faster? Only if everything parallelizes. Amdahl's law (Gene Amdahl, 1967) says the part that stays serial puts a hard ceiling on the speed-up, however many workers you add:

python
# amdahl.py: how much faster can N workers make a job that is partly serial?
def speedup(parallel_fraction: float, workers: int) -> float:
    serial = 1.0 - parallel_fraction
    return 1.0 / (serial + parallel_fraction / workers)


if __name__ == "__main__":
    # A PDF ingestion job: download (serial per file but overlappable), parse (CPU),
    # then a final single-threaded index write that cannot be split.
    print("parallel_fraction  " + "  ".join(f"w={n:<4}" for n in (2, 4, 8, 16, 1000)))
    for p in (0.50, 0.90, 0.95, 0.99):
        cells = [f"{speedup(p, n):5.2f}" for n in (2, 4, 8, 16, 1000)]
        print(f"{p:>17.2f}  " + "  ".join(cells))
    print()
    print("ceiling when 10% is serial:", round(1 / 0.10, 1), "x, however many workers")
Output7 lines
parallel_fraction  w=2     w=4     w=8     w=16    w=1000
             0.50   1.33   1.60   1.78   1.88   2.00
             0.90   1.82   3.08   4.71   6.40   9.91
             0.95   1.90   3.48   5.93   9.14  19.63
             0.99   1.98   3.88   7.48  13.91  90.99

ceiling when 10% is serial: 10.0 x, however many workers

In words: the time is serial part + parallel part / workers. The serial part never shrinks. If 10 % of the job is serial, then even with 1,000 workers you can never beat 10×; with 8 workers you get about 4.7×, not 8×. Two things to take from the table:

  1. The first workers help most. Going from 1 to 4 workers on a 90 %-parallel job gives 3.08×; going from 4 to 16 gives only about 2× more. Past the knee in the curve you are paying for hardware that barely helps.
  2. Shrinking the serial part is worth more than adding workers. Moving a job from 90 % to 99 % parallel raises the 16-worker speed-up from 6.4× to 13B.2×. In an ingestion job the serial part is often a single database writer, a lock around a shared structure, a final merge, the very first download, or the Python start-up of each worker. Profile first, then attack the serial part.

For I/O-bound concurrency the sizing question is "how many requests should be in flight?". Little's law answers it with concurrency = throughput × latency: to sustain 50 requests per second against a call that takes 2 seconds you need about 100 in flight. 01B.4 §6.1 teaches it with a worked calculation, and §6.3 shows how to turn it into a limit. Amdahl's law is the equivalent for CPU parallelism: it tells you what cores can deliver; Little's law tells you what in-flight requests must be.

3.6 "I/O" code hides CPU work#

The classification of a function is not the classification of its name. Code that "just calls an API" does CPU work too, and at scale that CPU is the bottleneck:

  • Serialization and parsing. Building a 50 KB JSON request body and parsing a 200 KB response, 5,000 times, can cost seconds of CPU. LLM streaming adds a parse per chunk.
  • TLS and compression. Encryption, decryption and gzip use CPU in the I/O path (usually in C, off your Python bytecode).
  • Validation. Pydantic validates in compiled Rust, but 100,000 objects is still real CPU.
  • Logging and tracing. Formatting, serializing and exporting spans costs CPU, often in the hot path.
  • Token counting. tiktoken is native but CPU-bound; counting tokens for every message of every request adds up.

A fan-out that is "obviously I/O-bound" at 10 concurrent calls can turn CPU-bound at 2,000, because the per-call CPU now saturates the one thread that does the parsing. That is exactly when an asyncio service's latency suddenly jumps while CPU sits at 100 %. The cpu/wall check on a loaded service catches it.

What it means for an AI engineer. Before choosing between threads, asyncio and processes, run the two-clock check (or top) on the real function under realistic load. Classify each stage of the pipeline, not the job. Expect most AI services to be a mix: I/O-bound stages around CPU-bound stages (parsing before embedding, validation after generation). And before buying more cores, use Amdahl's law to ask how much of the job can possibly use them.


Part 4: Blocking vs non-blocking#

Deep-dive

4.1 What "blocking" really means#

A blocking call is one that does not return until the thing it is waiting for has happened. time.sleep(1) blocks for a second. sock.recv(1024) blocks until at least one byte arrives (or the connection closes). lock.acquire() blocks until the lock is free. requests.get(url) blocks until the whole response is in. input() blocks until the user presses Enter.

Underneath, almost every blocking call is a system call (a syscall): a request from your program to the operating-system kernel, such as read, recv, accept, connect, futex (the Linux primitive behind locks), nanosleep. When a thread makes a blocking syscall and the answer is not ready, the kernel does not make the CPU spin. It marks the thread blocked (sometimes called sleeping), removes it from the list of runnable threads, and runs something else. When the data arrives (a network packet interrupt, a timer) the kernel marks the thread runnable again and the scheduler will eventually give it a CPU. From the thread's point of view the call simply took a long time.

You can see these calls: strace -c -f python3 script.py on Linux (or dtruss on macOS, which needs elevated privileges) lists the recv, futex and epoll_wait calls a program makes and how long it spent in each.

This is why blocking is cheap for the CPU and expensive for the thread:

  • The CPU is not wasted: while the thread sleeps, other threads and processes run.
  • The thread is wasted: while it is parked it can do nothing else, and it still holds its stack memory and a kernel object.

So "blocking" describes what happens to the calling thread, not to the machine. A blocking call inside a thread is fine if you have another thread for the other work. A blocking call inside the one thread that runs your event loop is a disaster, because that thread was supposed to serve everyone.

Term Meaning Common confusion
Blocking The call does not return until done; the thread is parked Not the same as slow: sleep is blocking and costs no CPU
Non-blocking The call returns immediately: either with the result or with "not ready yet" (EAGAIN/EWOULDBLOCK) Does not mean "fast": it means the call never makes the thread wait
Synchronous The caller waits for the result before continuing (a programming model: the call stack is held) A synchronous call can use a non-blocking mechanism underneath, and often does
Asynchronous The caller continues and gets the result later, through a callback, a future or an await Not the same as parallel: asyncio is single-threaded
Busy-waiting / polling The caller keeps asking "ready yet?" in a loop, burning CPU The wrong way to use non-blocking calls; use a selector instead (4.3)

(01C.2 owns synchronous vs asynchronous as programming models. This lesson owns blocking vs non-blocking as the property of a single call.)

4.2 Non-blocking I/O and readiness#

You can ask the kernel to make a descriptor non-blocking. In C, the flag is O_NONBLOCK on the file descriptor (set with fcntl). In Python, socket.setblocking(False) (or sock.settimeout(0.0)) does it for sockets. Then a call that would have had to wait raises BlockingIOError instead:

python
# nonblocking.py (part 1): blocking with a timeout, then truly non-blocking
import socket
import time


def blocking_recv_with_timeout() -> None:
    a, b = socket.socketpair()  # two connected sockets inside this process: no network involved
    a.settimeout(0.2)  # a timeout makes recv() give up instead of waiting forever
    t0 = time.perf_counter()
    try:
        a.recv(1024)  # nothing has been sent: this call blocks until the timeout
    except TimeoutError:
        print(f"blocking recv gave up after the timeout (waited >= 0.15 s: {time.perf_counter() - t0 >= 0.15})")
    a.close(), b.close()


def nonblocking_recv() -> None:
    a, b = socket.socketpair()
    a.setblocking(False)  # O_NONBLOCK: recv() must return immediately
    try:
        a.recv(1024)
    except BlockingIOError as exc:  # EAGAIN / EWOULDBLOCK
        print("non-blocking recv with no data ->", type(exc).__name__)
    b.send(b"hello")
    print("non-blocking recv with data    ->", a.recv(1024))
    a.close(), b.close()


if __name__ == "__main__":
    blocking_recv_with_timeout()
    nonblocking_recv()
Output3 lines
blocking recv gave up after the timeout (waited >= 0.15 s: True)
non-blocking recv with no data -> BlockingIOError
non-blocking recv with data    -> b'hello'

Python (3.3+) maps the C errors EAGAIN and EWOULDBLOCK to the exception BlockingIOError, and a socket with a timeout raises TimeoutError (3.10+: socket.timeout became an alias of the built-in TimeoutError). Three timeout modes exist for a socket, and they are worth memorizing:

settimeout(...) Mode recv on an empty socket
None (default) Blocking Waits forever
a positive number Blocking with a timeout Waits up to that many seconds, then TimeoutError
0.0 (same as setblocking(False)) Non-blocking Returns immediately or raises BlockingIOError

A non-blocking call on its own is only half a tool: how do you know when to call it again? Looping and retrying is busy-waiting and wastes a core. The answer is the next section.

4.3 Waiting for many things at once: select, poll, epoll, kqueue and IOCP#

The operating system offers calls that say: here is a list of descriptors; put me to sleep and wake me when any of them is ready. This is I/O multiplexing, and it is the single trick behind every high-concurrency server (nginx, Redis, Node.js, and asyncio).

The historical reason it exists is the C10K problem (Dan Kegel, 1999): a server using one thread or process per connection struggled to hold ten thousand simultaneous connections, because of the memory and scheduling cost of that many threads. epoll (Linux) and kqueue (BSD and macOS) were designed to make waiting on thousands of descriptors cheap.

Mechanism Where How it scales Note
select Everywhere (POSIX, Windows) O(n) per call; descriptor limit (often 1,024 via FD_SETSIZE; asyncio's Windows SelectorEventLoop is limited to 512 sockets) The oldest; portable fallback
poll POSIX O(n) per call; no fixed descriptor limit Better interface than select
epoll Linux O(1) per ready event; scales to very large numbers of descriptors Kernel keeps the interest list; you only pay for the ready ones
kqueue macOS and BSDs Similar to epoll; also watches files, signals, timers The macOS/BSD answer
IOCP (I/O completion ports) Windows A different model: the kernel completes the operation and notifies you, rather than telling you it is ready What asyncio's ProactorEventLoop uses, the Windows default since Python 3.8

Two models are worth distinguishing, because you will see both names:

  • Readiness-based (select/poll/epoll/kqueue): the kernel says "this socket is ready to read." You then call recv, which returns immediately because data is there. This is what selectors exposes and what Unix asyncio uses.
  • Completion-based (IOCP, Linux io_uring): you submit "read 4 KB into this buffer" and the kernel tells you when it has completed. Fewer syscalls, a different programming model. asyncio's Windows ProactorEventLoop is completion-based. (io_uring is mentioned for awareness; asyncio does not use it.)

Python wraps the readiness family in the selectors module. selectors.DefaultSelector is documented as "an alias to the most efficient implementation available on the current platform": EpollSelector on modern Linux, KqueueSelector on macOS, and SelectSelector on Windows. You can check which one you got with type(selectors.DefaultSelector()). On the machine used here:

pycon
>>> import selectors
>>> selectors.DefaultSelector.__name__
'KqueueSelector'

Here is the pattern at work. One thread watches three sockets (stand-ins for three clients: tickets, invoices, contracts) and is told which one has data:

python
# nonblocking.py (part 2): one thread, three sockets, one selector
import selectors
import socket


def selector_demo() -> None:
    sel = selectors.DefaultSelector()  # kqueue on macOS/BSD, epoll on Linux, select on Windows
    pairs = {name: socket.socketpair() for name in ("tickets", "invoices", "contracts")}
    for name, (reader, _writer) in pairs.items():
        reader.setblocking(False)
        sel.register(reader, selectors.EVENT_READ, data=name)

    print("ready before anything is sent:", sel.select(timeout=0.05))

    pairs["invoices"][1].send(b"INV-42 paid")
    pairs["contracts"][1].send(b"renewal due")
    ready = sorted(
        (key.data, key.fileobj.recv(1024)) for key, _events in sel.select(timeout=1.0)
    )
    print("ready after two sends:", ready)

    for reader, writer in pairs.values():
        sel.unregister(reader)
        reader.close(), writer.close()
    sel.close()


if __name__ == "__main__":
    selector_demo()
Output2 lines
ready before anything is sent: []
ready after two sends: [('contracts', b'renewal due'), ('invoices', b'INV-42 paid')]

sel.select(timeout=...) is where the thread sleeps (a blocking call: one call that waits for many things). Nothing in the output depends on the platform's selector. Compare the alternative, one parked thread per waiting socket:

python
# nonblocking.py (part 3): the thread-per-wait alternative
import socket
import threading


def how_many_threads_does_waiting_cost() -> None:
    pairs = [socket.socketpair() for _ in range(5)]
    started = threading.active_count()

    def wait_on(sock: socket.socket) -> None:
        sock.recv(16)

    threads = [threading.Thread(target=wait_on, args=(r,)) for r, _ in pairs]
    for t in threads:
        t.start()
    print("threads needed to wait on 5 sockets:", threading.active_count() - started)
    for _, w in pairs:
        w.send(b"x")
    for t in threads:
        t.join()
    for r, w in pairs:
        r.close(), w.close()
    print("threads needed with one selector: 0 extra (the main thread polls all five)")


if __name__ == "__main__":
    how_many_threads_does_waiting_cost()
Output2 lines
threads needed to wait on 5 sockets: 5
threads needed with one selector: 0 extra (the main thread polls all five)

(Save the three parts together as nonblocking.py to run them.) The cost difference between five and five thousand is the whole case for event loops. Part 5 puts numbers on it, and 01C.2 shows an event loop built from exactly these pieces: a selector, a ready queue and generators.

4.4 Blocking versus non-blocking: which side are you on?#

Most Python code you write is blocking by default: open().read(), requests.get, time.sleep, queue.get(), lock.acquire(), subprocess.run(), sqlite3, psycopg2, most SDK methods. That is fine and correct: simple, easy to reason about, and it parks one thread. The questions are which thread, and how many threads you can afford.

Situation Blocking code is...
A script that does one thing Fine. Simplicity wins
A thread-pool worker doing one request at a time Fine. That is what pool threads are for
A web server with a thread per request Fine up to the thread limit; every in-flight request holds a thread
The thread running an asyncio event loop A bug. Everything else on that loop stops
A GUI's main thread A bug: the window freezes ("Not Responding")
A signal handler or a callback called by the loop A bug of the same kind

4.5 Blocking calls hidden inside async code#

The most common production bug in async Python is a blocking call inside a coroutine: an async def that looks asynchronous, but calls something that parks the one event-loop thread. Everything on that loop (every other request, timeouts, heartbeats, health checks) stops until the call returns. 01B.3 §8.1 shows the symptom and 03.9 §2.6 shows the LLM-SDK version. Here is the mechanism and the three ways to detect it.

What commonly blocks an event loop:

Hidden blocker Why it blocks Async-safe alternative
time.sleep() Parks the loop thread await asyncio.sleep()
requests.get/post, urllib.request, any sync SDK client Socket waits httpx.AsyncClient, the SDK's Async client, or asyncio.to_thread
Synchronous database drivers (psycopg2, sqlite3, pymysql) Socket / disk waits An async driver (asyncpg, psycopg async mode, aiosqlite) or a thread
open(...).read() on large files, Path.read_text Disk reads asyncio.to_thread(path.read_text) or aiofiles
subprocess.run, os.system Waits for the child asyncio.create_subprocess_exec
socket.gethostbyname, socket.getaddrinfo DNS loop.getaddrinfo (runs in an executor)
queue.Queue.get(), threading.Lock.acquire(), thread.join() Waits for another thread asyncio.Queue, asyncio.Lock, or await asyncio.to_thread(...)
input() Waits on the keyboard A thread, or an async-aware prompt library
CPU-heavy functions: json.loads of a huge file, re on large text, PDF parsing, pickle, compression, tokenizing The loop thread is busy computing loop.run_in_executor(process_pool, ...)
Logging to a slow handler (file on NFS, network handler) I/O inside logger.info logging.handlers.QueueHandler plus a listener thread

The last two rows are the sneaky ones: "async-looking" code with no time.sleep anywhere can still stall the loop through plain CPU work.

Detection 1: a heartbeat that measures its own lateness. Start a coroutine that should wake every 50 ms and record the gap between wake-ups. If something blocks the loop, the gaps grow. The same function with the blocking call moved off the loop (asyncio.to_thread) shows normal gaps:

python
# blocking_in_async.py: a hidden blocking call freezes every other coroutine.
import asyncio
import time


async def heartbeat(gaps: list[float], stop: asyncio.Event) -> None:
    # Should wake every 50 ms. The gap between wake-ups shows how long the loop was stuck.
    last = time.perf_counter()
    while not stop.is_set():
        await asyncio.sleep(0.05)
        now = time.perf_counter()
        gaps.append(now - last)
        last = now


def sync_sdk_call() -> str:
    time.sleep(0.4)  # stands in for a synchronous HTTP client / SDK call
    return "answer"


async def bad_handler() -> str:
    return sync_sdk_call()  # no await: nothing else can run for 0.4 s


async def good_handler() -> str:
    return await asyncio.to_thread(sync_sdk_call)  # runs in a worker thread


async def measure(handler) -> float:
    gaps: list[float] = []
    stop = asyncio.Event()
    beat = asyncio.create_task(heartbeat(gaps, stop))
    await asyncio.sleep(0.2)  # let the heartbeat settle
    await handler()
    await asyncio.sleep(0.2)
    stop.set()
    await beat
    return max(gaps)


async def main() -> None:
    worst_bad = await measure(bad_handler)
    worst_good = await measure(good_handler)
    print("heartbeat stalled > 0.35 s with the blocking call:", worst_bad > 0.35)
    print("heartbeat stalled > 0.35 s with to_thread:     ", worst_good > 0.35)


if __name__ == "__main__":
    asyncio.run(main())
Output2 lines
heartbeat stalled > 0.35 s with the blocking call: True
heartbeat stalled > 0.35 s with to_thread:      False

The bad_handler is a perfectly valid async def; Python will not warn you. The good_handler hands the blocking function to a worker thread and awaits its completion: the event loop keeps ticking.

Detection 2: asyncio debug mode. The documentation lists four ways to turn it on: set the environment variable PYTHONASYNCIODEBUG=1, use Python Development Mode (python -X dev), pass debug=True to asyncio.run(), or call loop.set_debug(). Among other checks it logs any callback that takes longer than 100 ms (configurable through loop.slow_callback_duration). The log line looks like this (captured with python3 -X dev and logging.basicConfig() on the machine used here; the task's address and path are machine-specific):

Example output · illustrative1 line
WARNING:asyncio:Executing <Task finished name='Task-1' coro=<m() done, defined at <string>:4> result=None created at .../asyncio/runners.py:110> took 0.305 seconds

The same check from code, which is how we can assert it deterministically (a custom logging handler captures the message):

python
# blocking_in_async.py (second half): catch the slow-callback warning in code
import asyncio
import logging
import time


def sync_sdk_call() -> str:
    time.sleep(0.4)
    return "answer"


async def bad_handler() -> str:
    return sync_sdk_call()


async def debug_mode_demo() -> None:
    loop = asyncio.get_running_loop()
    loop.slow_callback_duration = 0.1  # the documented threshold of 100 ms, set explicitly
    await bad_handler()


class Capture(logging.Handler):
    def __init__(self) -> None:
        super().__init__()
        self.messages: list[str] = []

    def emit(self, record: logging.LogRecord) -> None:
        self.messages.append(record.getMessage())


if __name__ == "__main__":
    cap = Capture()
    logging.getLogger("asyncio").addHandler(cap)
    asyncio.run(debug_mode_demo(), debug=True)  # same effect as PYTHONASYNCIODEBUG=1
    slow = [m for m in cap.messages if "took" in m and "seconds" in m]
    print("debug mode logged a slow-callback warning:", bool(slow))
    print("warning shape:", slow[0].split("<")[0] + "<...> took 0.4xx seconds")
Output2 lines
debug mode logged a slow-callback warning: True
warning shape: Executing <...> took 0.4xx seconds

Detection 3: loop-lag metric in production. The heartbeat from Detection 1, exported as a metric (event_loop_lag_seconds), is the cheapest production alarm: it measures how late a timer fired, which is exactly how long the loop was unavailable. Alert when the 99th percentile is above, say, 100 ms. That turns "the service feels slow at times" into a number and a graph. (11A.2 covers metrics and alerting.)

The fixes, in order of preference:

  1. Use the async-native version of the library (an AsyncClient, an async driver).
  2. Move blocking I/O to a thread: await asyncio.to_thread(fn, *args) (01B.3 §3.8). The thread blocks; the loop does not. This is not free capacity: to_thread uses the loop's shared, bounded default executor (min(32, cpu+4) threads, the same pool that runs getaddrinfo), so 200 simultaneous to_thread calls run about 12 to 32 at a time and the rest queue. For a long-lived blocking workload create a dedicated ThreadPoolExecutor and use run_in_executor (01C.2 covers the default executor).
  3. Move CPU-heavy work to a process pool: await loop.run_in_executor(process_pool, fn, *args). A thread would not help here in standard CPython: it would still hold the GIL and slow the loop thread down (01C.5).
  4. Make the work smaller and yield between pieces for CPU loops you cannot move: await asyncio.sleep(0) every few thousand iterations gives other tasks a turn. It is a last resort.

What it means for an AI engineer. The OpenAI, Anthropic and Gemini SDKs each ship both a sync client and an async client; using the sync client inside a FastAPI async def handler is the classic way to turn a service that should handle hundreds of concurrent chats into one that handles one at a time. Parsing a large retrieved document, building a prompt from a 5 MB context, or running a tokenizer inside the handler does the same thing through CPU. Keep a loop-lag metric in every async service.


Part 5: Context switching#

Deep-dive

5.1 What a context switch is#

A CPU core executes one flow of instructions at a time. To make it look as if hundreds of programs run at once, the operating system time-slices: it lets one thread run for a short while, then stops it, remembers exactly where it was, and lets another thread run. That stop-and-resume is a context switch: saving the context (everything needed to resume) of the thread that is leaving, and loading the context of the thread that is arriving.

The kitchen version: the cook stops chopping, puts a bookmark in the recipe, wipes their hands, walks to the stove, remembers where the curry was, and carries on there. None of that is cooking. It is overhead, paid every time attention moves.

The same word is used at several levels, which is a source of endless confusion, so keep this ladder in mind from cheapest to most expensive:

Level What switches Who does it Rough cost class
Function call Return address and locals on the same stack The compiler / interpreter Nanoseconds or less
Generator / coroutine resume A saved Python frame (locals, instruction pointer) The Python interpreter, in user space Tens of nanoseconds (generator) to a few microseconds (through an event loop)
Thread switch (same process) Registers, stack pointer, thread-local state; the same address space The OS kernel Typically a few microseconds, plus cache effects
Process switch The same, plus the address space (page tables, TLB) The OS kernel Typically more than a thread switch, plus cache and TLB effects
VM / container / host switch A whole virtual machine's state Hypervisor Much more; out of scope

5.2 What is saved and restored#

sequenceDiagram
    participant A as Thread A
    participant K as Kernel scheduler
    participant B as Thread B
    A->>K: blocks (recv, sleep, lock) or timer interrupt fires
    K->>K: save A registers, program counter, stack pointer
    K->>K: pick next runnable thread
    K->>K: load B registers and stack pointer
    Note over K: process switch also changes address space (page tables, TLB)
    K->>B: resume where B stopped
    Note over B: B starts with cold CPU caches

When the kernel takes a thread off a core it saves its CPU state:

  • the registers, including the program counter (which instruction is next) and the stack pointer (where the thread's call stack is);
  • the floating-point and vector registers (these are large, so kernels use instructions such as XSAVE that save only the parts the thread has touched; older kernels did this lazily);
  • a few bits of scheduling and accounting state (priority, time used, which core).

Each thread has its own kernel stack and user stack, so "loading the new thread's stack pointer" is what makes it resume inside its own call chain. If the next thread belongs to a different process, the kernel also switches the address space: it points the CPU's memory-management hardware at a different set of page tables. The CPU caches recent address translations in the TLB (translation lookaside buffer); after an address-space switch, entries for the old process are useless, so the new process starts with a cold TLB (some CPUs tag entries with an address-space id to avoid a full flush, which reduces but does not remove the cost). Switching between threads of the same process keeps the same address space, so this part is skipped, one reason a thread switch is cheaper than a process switch.

5.3 Four kinds of switch, compared#

Generator resume Coroutine switch (await to another task) Thread switch Process switch
Triggered by next() / send() await of something not yet done; the loop then picks the next ready task A blocking call, a timer interrupt, or a higher-priority thread becoming runnable The same, across processes
Crosses into the kernel? No Not for the switch itself, but each loop iteration polls the selector (one syscall per iteration) Yes (the scheduler runs) Yes
What is saved One Python frame One Python frame, plus the loop's bookkeeping (a Handle, a task step) Registers, stack pointer Registers, stack pointer, address space
Can another task preempt in the middle of a Python statement? No No: only at await Yes (between any two bytecodes) Yes
Memory per unit The frame (~100-300 bytes) A task: around a kilobyte (see 5.7) Stack: megabytes reserved, tens of KiB resident A whole interpreter and heap

The last two rows of the table are why asyncio can hold tens of thousands of waits and threads cannot: the memory and the number of kernel objects. The "can another task preempt me" row is why asyncio programs have far fewer races than threaded ones (01C.3): code between two awaits runs without interruption.

5.4 What a switch costs#

There are two costs, and only one of them is easy to measure:

  • Direct cost: the instructions to save state, run the scheduler and restore state, plus the mode switch into and out of the kernel. Typically on the order of a few microseconds or less on current hardware.
  • Indirect cost: the new thread's cache, TLB and branch-predictor state is cold or polluted by the previous thread. It depends on the program's working set, can dwarf the direct cost, and is paid after the switch as slower memory accesses. Research measuring it, such as Li, Ding and Shen's Quantifying the cost of context switch (ExpCS 2007), reports a direct cost of about 3.4 microseconds on their test system and an indirect cost "from several microseconds to hundreds of microseconds" depending on the working set and access pattern.

So the honest summary is an order of magnitude and a caveat: a switch typically costs from a few microseconds up to hundreds of microseconds once cache effects are included, depending on hardware, kernel, virtualization and what the threads were doing. Anyone quoting a single number ("a context switch costs 5 µs") is simplifying.

Let us measure the direct hand-off between the four kinds, using ping-pong: two parties hand control back and forth many times, and we divide the total time by the number of hand-offs.

python
# switch_cost.py: what does one hand-off cost for a generator, a coroutine, a thread and a process?
import asyncio
import multiprocessing as mp
import threading
import time

N = 20_000


def generator_switches() -> float:
    def gen():
        while True:
            yield

    g = gen()
    t0 = time.perf_counter()
    for _ in range(N):
        next(g)  # one resume + one yield = two switches
    return (time.perf_counter() - t0) / (2 * N)


async def _coroutine_pingpong() -> float:
    # Two tasks hand control to each other through asyncio.sleep(0): the loop does the switching.
    count = 0

    async def worker():
        nonlocal count
        for _ in range(N // 2):
            await asyncio.sleep(0)  # yield to the loop; the loop picks the other task
            count += 1

    t0 = time.perf_counter()
    await asyncio.gather(worker(), worker())
    return (time.perf_counter() - t0) / count


def coroutine_switches() -> float:
    return asyncio.run(_coroutine_pingpong())


def thread_switches() -> float:
    # Ping-pong between two threads with two Events: every hand-off needs the OS scheduler.
    ping, pong = threading.Event(), threading.Event()
    rounds = 5_000

    def other():
        for _ in range(rounds):
            ping.wait()
            ping.clear()
            pong.set()

    t = threading.Thread(target=other)
    t.start()
    t0 = time.perf_counter()
    for _ in range(rounds):
        ping.set()
        pong.wait()
        pong.clear()
    elapsed = time.perf_counter() - t0
    t.join()
    return elapsed / (2 * rounds)


def _echo(conn, rounds):
    for _ in range(rounds):
        conn.send_bytes(conn.recv_bytes())


def process_switches() -> float:
    a, b = mp.Pipe()
    rounds = 5_000
    p = mp.Process(target=_echo, args=(b, rounds))
    p.start()
    t0 = time.perf_counter()
    for _ in range(rounds):
        a.send_bytes(b"x")
        a.recv_bytes()
    elapsed = time.perf_counter() - t0
    p.join()
    return elapsed / (2 * rounds)


if __name__ == "__main__":
    results = {
        "generator resume/yield": generator_switches(),
        "coroutine (task to task via the loop)": coroutine_switches(),
        "thread to thread (Event ping-pong)": thread_switches(),
        "process to process (pipe ping-pong)": process_switches(),
    }
    for name, secs in results.items():
        print(f"{name:40} ~ {secs * 1e6:8.2f} microseconds per switch")
Example output · illustrative4 lines
generator resume/yield                   ~     0.01 microseconds per switch
coroutine (task to task via the loop)    ~     6.76 microseconds per switch
thread to thread (Event ping-pong)       ~     3.32 microseconds per switch
process to process (pipe ping-pong)      ~     8.02 microseconds per switch

Measured on Python 3.14.6, macOS, Apple silicon with 10 cores. Read the result carefully, because it contradicts a popular slogan:

  • A bare generator resume is by far the cheapest (about 10 ns here): it is a function-call-sized operation inside the interpreter. No kernel, no scheduler.
  • A coroutine switch through asyncio is not nanoseconds. Here it measured slower than a thread hand-off. The reason: await asyncio.sleep(0) is a bare yield (CPython's tasks.py says it does so "instead of creating a Future object"), but the Task then re-queues itself with call_soon (allocating a Handle and entering a contextvars context), and every loop iteration also polls the selector, which is a system call even when it returns at once. Two tasks share one iteration here, so each hand-off carries about half a syscall plus a few microseconds of Python bytecode. The generator number is the floor; the event loop adds bookkeeping (alternative loops such as uvloop shave this, but that is awareness only).
  • A thread hand-off through an Event was a few microseconds. On this machine both threads can run on separate cores, so part of that is a cross-core wake-up rather than a same-core register swap, and the figure includes the GIL hand-off and Python-level Event overhead, so it is an upper bound on the kernel switch and not the same quantity as the 3.4 microsecond direct cost quoted from Li et al. above. That is also why this is a measurement of a hand-off, not of the pure cost the research papers isolate (which pin both processes to one core).
  • A process hand-off through a pipe adds two syscalls and a data copy per message on top of the scheduling: not dramatically worse than threads in this micro-test, but the indirect costs (separate address space, cold TLB, pickling for anything bigger than b"x") show up in real workloads, not in ping-pong.

So where does asyncio win, if not on the cost per switch? On how many units you can hold and how rarely you switch. A thread switches at every blocking point and at timer interrupts; a coroutine only switches when it has to wait. And 10,000 waiting coroutines cost about 10 MB of Python heap, where 10,000 threads cost 10,000 kernel objects and reserved stacks. The next sections quantify both.

5.5 Preemptive versus cooperative: who decides when to switch?#

Preemptive Cooperative
Who decides to switch An outside scheduler, which can interrupt a task at almost any moment (timer interrupt, higher-priority work) The task itself, by explicitly yielding at a known point (await, yield)
Python examples OS threads and processes asyncio, generators, greenlet/gevent
Fairness The scheduler can enforce it: a runaway task cannot hog the CPU for long None: one task that never yields starves all the others
Race conditions Possible at any instruction Possible only across yield points; code between two awaits is atomic with respect to other tasks
A tight CPU loop Gets interrupted; the others keep running Freezes everyone until it finishes

The OS is preemptive. A hardware timer interrupts the CPU every few milliseconds (the scheduler tick, typically 1-10 ms); the kernel's scheduler may then decide that the running thread has had its turn and pick another. A thread can also be preempted instantly when a higher-priority thread becomes runnable (for example, the thread whose network packet just arrived). In neither case does the thread get a say.

asyncio is cooperative. The event loop runs one task until it hits an await that cannot complete immediately, then picks another. It cannot interrupt a task in the middle of a computation. If a coroutine loops for two seconds without awaiting, nobody else runs for two seconds. 01C.2 shows the machinery.

CPython threads are preemptive twice. The OS preempts threads as above, and CPython has its own, second layer: the GIL. A thread running Python bytecode holds the GIL; another thread that wants to run asks it to be released. The interpreter's switch interval is how long the waiting thread waits before requesting the handoff, 5 milliseconds by default, readable with sys.getswitchinterval(). The documentation is explicit about what this controls: it "determines the ideal duration of the 'timeslices' allocated to concurrently running Python threads. Please note that the actual value can be higher… Also, which thread becomes scheduled at the end of the interval is the operating system's decision. The interpreter doesn't have its own scheduler." In other words the GIL decides whether a Python thread may run, and the OS still decides which one. 01C.5 opens that machinery.

A tiny experiment makes the switch interval visible. Two CPU-bound threads share one interpreter; we count how often the "current owner" changes under a long and a very short interval:

python
# switch_interval.py: the interpreter's own time slice, sys.getswitchinterval().
import sys
import threading

ITERATIONS = 2_000_000


def run(interval: float) -> int:
    sys.setswitchinterval(interval)
    owner = None
    changes = 0
    lock = threading.Lock()  # protects the counters (the list of owners is not what we study)

    def work(name: str) -> None:
        nonlocal owner, changes
        for _ in range(ITERATIONS):
            if owner != name:  # racy on purpose: we only want an approximate count
                with lock:
                    if owner != name:
                        owner = name
                        changes += 1

    threads = [threading.Thread(target=work, args=(n,)) for n in ("A", "B")]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    return changes


if __name__ == "__main__":
    default = sys.getswitchinterval()
    print("default switch interval:", default, "seconds")
    slow = run(0.05)  # 50 ms: a long slice
    fast = run(0.00001)  # 10 microseconds: a very short slice
    sys.setswitchinterval(default)
    print("shorter interval gives more hand-offs:", fast > slow)
Output2 lines
default switch interval: 0.005 seconds
shorter interval gives more hand-offs: True

(The absolute counts depend on the machine, so only the ordering is printed. The default is 5 ms (observed 0.005 on Python 3.14.6; it is the value set in CPython's Python/ceval_gil.c and described in the 3.2 What's New. The sys docs do not state the number.))

Shortening the interval makes threads feel more responsive but costs more switches; lengthening it favours throughput. You almost never change it in production. 01C.3 uses a tiny interval as a tool to make race conditions show up quickly in tests.

5.6 Voluntary versus involuntary switches#

The kernel counts why each switch happened:

  • A voluntary context switch: the thread gave up the CPU because it had to wait, for example it called sleep, did a blocking recv, waited on a lock. This is the normal, healthy signature of an I/O-bound thread.
  • An involuntary context switch: the scheduler took the CPU away because the thread's time slice ended or a higher-priority thread became runnable. This is the signature of CPU contention: more runnable threads than cores.

A thread with many voluntary and few involuntary switches is mostly waiting. A thread with many involuntary switches is competing with others for CPU, and might be slowed by oversubscription (5.7). Python exposes both counters for the process through resource.getrusage (Unix: macOS and Linux; the module is documented as "Unix, not WASI"): ru_nvcsw is voluntary, ru_nivcsw is involuntary.

python
# voluntary_involuntary.py: count the kernel's context switches with resource.getrusage.
# ru_nvcsw  = voluntary switches   (we gave up the CPU: sleep, blocking read, lock wait)
# ru_nivcsw = involuntary switches (the scheduler took the CPU away: time slice over, higher priority job)
import multiprocessing as mp
import os
import resource
import time


def switches() -> tuple[int, int]:
    ru = resource.getrusage(resource.RUSAGE_SELF)
    return ru.ru_nvcsw, ru.ru_nivcsw


def waiter() -> tuple[int, int]:
    v0, i0 = switches()
    for _ in range(50):
        time.sleep(0.01)  # 50 voluntary sleeps
    v1, i1 = switches()
    return v1 - v0, i1 - i0


def spinner(_: int) -> tuple[int, int]:
    v0, i0 = switches()
    end = time.perf_counter() + 1.0
    x = 0
    while time.perf_counter() < end:  # pure computation, never gives up the CPU voluntarily
        x += 1
    v1, i1 = switches()
    return v1 - v0, i1 - i0


if __name__ == "__main__":
    v, i = waiter()
    print(f"waiter  (50 sleeps): voluntary={v} involuntary={i}")

    # More CPU-bound processes than cores: the kernel must time-slice them.
    cores = os.cpu_count() or 1
    with mp.Pool(cores * 3) as pool:
        results = pool.map(spinner, range(cores * 3))
    total_inv = sum(i for _, i in results)
    avg_v = sum(v for v, _ in results) / len(results)
    avg_i = total_inv / len(results)
    print(f"spinners ({cores * 3} processes on {cores} cores, 1 s each): avg voluntary={avg_v:.0f} avg involuntary={avg_i:.0f}")

On Linux you should see the textbook split, described here in words because this lesson did not measure it on Linux: about one voluntary switch per sleep for the waiter (so roughly 50) and involuntary switches in the low single digits; and for the spinners a large involuntary count and almost no voluntary ones, because they only ever lose the CPU when the scheduler takes it. Run it in a Linux container or CI runner to see your own numbers.

This script run on macOS gave different numbers (a real platform difference, not an error) (this is a real platform difference, not an error). Example output (illustrative — your exact output will differ), macOS, Python 3.14.6:

text
waiter  (50 sleeps): voluntary=0 involuntary=58
spinners (30 processes on 10 cores, 1 s each): avg voluntary=0 avg involuntary=6464

macOS's getrusage reported zero voluntary switches in our runs and attributes every switch to the involuntary counter; its absolute values are therefore not comparable with Linux. The takeaway: the voluntary/involuntary split is a Linux-grade diagnostic. If you are on macOS, use Linux (a container or a CI runner) when you want to read these counters, and treat the macOS numbers as a rough "this process was switched a lot" indicator only. (The Linux description above is the expected shape, not a measurement from this lesson.)

On Linux there is a finer-grained source: /proc/<pid>/status lists voluntary_ctxt_switches and nonvoluntary_ctxt_switches for a process, and /proc/<pid>/task/<tid>/status lists the same per thread, so you can see which thread is being switched out:

python
# proc_status_linux.py: Linux only. /proc/self/status has per-process counters;
# /proc/self/task/<tid>/status has them per thread.
from pathlib import Path
import time


def counters(path: str = "/proc/self/status") -> dict[str, int]:
    out = {}
    for line in Path(path).read_text().splitlines():
        if "ctxt_switches" in line:
            key, value = line.split(":")
            out[key] = int(value)
    return out


if __name__ == "__main__":
    before = counters()
    for _ in range(50):
        time.sleep(0.01)
    after = counters()
    print({k: after[k] - before[k] for k in before})

The two counters appear under the keys voluntary_ctxt_switches and nonvoluntary_ctxt_switches: expect a voluntary count near 50 (one per sleep) and a small involuntary count. The exact numbers depend on the machine, so none are printed here.

pidstat -w -p <PID> 1 (from the sysstat package), vmstat 1 (the cs column) and perf stat -e context-switches show the system-wide and per-process rates; perf trace and strace -f show the syscalls behind them. Treat all of these as Linux tools: on macOS use Instruments or sample, and on Windows use Performance Monitor's "Context Switches/sec".

5.7 Oversubscription: more runnable threads than cores#

A runnable thread is one that wants a CPU right now. If there are more runnable threads than cores, the kernel must time-slice them, and each extra thread adds more switches and more cache pollution. This is oversubscription. With blocked threads there is no cost, because a blocked thread is not runnable; the problem is specifically with CPU-hungry threads.

Running 64 CPU jobs through thread pools of different sizes shows the CPU-bound, GIL-bound case, where the shape is flat, not even a gain from the first threads:

python
# oversubscription.py: more threads than cores does not help CPU-bound work.
# (With the GIL even one core's worth of threads does not help; we vary the pool size anyway.)
import hashlib
import time
from concurrent.futures import ThreadPoolExecutor

TOTAL_JOBS = 64
ROUNDS = 20_000


def burn(_: int) -> None:
    h = b"seed"
    for _ in range(ROUNDS):
        h = hashlib.sha256(h).digest()


if __name__ == "__main__":
    for workers in (1, 4, 16, 64):
        t0 = time.perf_counter()
        with ThreadPoolExecutor(max_workers=workers) as pool:
            list(pool.map(burn, range(TOTAL_JOBS)))
        print(f"{workers:3} threads: {time.perf_counter() - t0:5.2f} s")
Example output · illustrative4 lines
  1 threads:  0.24 s
  4 threads:  0.23 s
 16 threads:  0.23 s
 64 threads:  0.23 s

With the GIL, 4 threads or 64 threads do the same amount of CPU work in about the same time; the extra threads add no speed. Beyond that, extra runnable threads (or processes) each hold memory and compete for CPU time. In a native, parallel setting (a process pool, or a free-threaded build) the curve rises to about the number of cores, then goes flat and eventually slightly down, because the switching and cache costs start to eat the gain. The practical rule:

  • CPU-bound pools: about one worker per core (os.cpu_count(), which counts logical CPUs; in containers, check the quota: since Python 3.13 os.process_cpu_count() reports the CPUs the process may actually use, and it is what ProcessPoolExecutor now defaults to).
    • For pure-compute pools, physical cores (or an Apple silicon machine's performance cores) are often the sweet spot, because SMT siblings share execution units. os.process_cpu_count() and os.sched_getaffinity(0) honour CPU affinity and cgroup cpusets, but not CFS quotas: Kubernetes limits.cpu is a quota, so on a 2-CPU limit on a 64-core node they can still report 64. Reading the quota is not automatic: on cgroup v2 read /sys/fs/cgroup/cpu.max (max 100000 means unlimited; 200000 100000 means two CPUs).
  • I/O-bound pools: far more workers than cores is fine, because blocked threads cost memory but not CPU. How many? Little's law tells you.
  • Mixed pools: separate them. One pool sized for waiting, one for computing, so a burst of one cannot starve the other.

ThreadPoolExecutor's default size is documented as min(32, (os.process_cpu_count() or 1) + 4) since Python 3.13 (it was min(32, os.cpu_count() + 4) from 3.8). That default is tuned for I/O-bound work: it deliberately has more threads than cores and caps at 32 so that a many-core machine does not create hundreds of threads for waits.

The commonest AI version of oversubscription is hidden in native libraries. A process pool of 8 workers, each calling NumPy, PyTorch or ONNX Runtime, can make 8 x (cores) BLAS or OpenMP threads runnable on a machine with that many cores, and the whole thing slows down. Limit native threads per worker with OMP_NUM_THREADS, MKL_NUM_THREADS or torch.set_num_threads(1), and size the pool and the native threads together so their product is about the core count. Failure-gallery row 13 in Part 7 gives the symptoms.

Waiting units are cheap to hold, but not free. Compare holding 2,000 simultaneous 0.5-second waits as threads versus as asyncio tasks:

python
# thread_vs_task.py: cost of holding 2,000 simultaneous waits as threads vs as asyncio tasks.
import asyncio
import threading
import time

WAITS = 2_000


def with_threads() -> float:
    t0 = time.perf_counter()
    threads = [threading.Thread(target=time.sleep, args=(0.5,)) for _ in range(WAITS)]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    return time.perf_counter() - t0


async def with_tasks() -> float:
    t0 = time.perf_counter()
    await asyncio.gather(*(asyncio.sleep(0.5) for _ in range(WAITS)))
    return time.perf_counter() - t0


if __name__ == "__main__":
    print(f"{WAITS} concurrent 0.5 s waits")
    print(f"  threads : {with_threads():.2f} s total")
    print(f"  tasks   : {asyncio.run(with_tasks()):.2f} s total")
Example output · illustrative3 lines
2000 concurrent 0.5 s waits
  threads : 0.92 s total
  tasks   : 0.51 s total

The tasks finish in about the ideal 0.5 s; the threads need an extra ~0.4 s just to be created and scheduled, and the gap grows with the count. Memory is the other side. Using tracemalloc to count Python-heap memory held by 10,000 suspended tasks:

python
# task_memory.py: Python-heap memory held by 10,000 suspended coroutines/tasks (tracemalloc).
# This counts Python objects only; a thread also reserves an OS stack that tracemalloc cannot see.
import asyncio
import tracemalloc

N = 10_000


async def waiter(event: asyncio.Event) -> None:
    await event.wait()


async def main() -> None:
    event = asyncio.Event()
    tracemalloc.start()
    before, _ = tracemalloc.get_traced_memory()
    tasks = [asyncio.create_task(waiter(event)) for _ in range(N)]
    await asyncio.sleep(0)  # let every task run up to its first await
    after, _ = tracemalloc.get_traced_memory()
    print(f"{N} suspended tasks: about {(after - before) / N:.0f} bytes of Python heap each")
    event.set()
    await asyncio.gather(*tasks)


if __name__ == "__main__":
    asyncio.run(main())
Example output · illustrative1 line
10000 suspended tasks: about 1041 bytes of Python heap each

About 1 KB per task (a coroutine frame, a Task and a future). Threads cost far more in kernel and address-space terms: on the machine used here, 500 parked threads added about 36 KiB of peak resident memory each (script below), and each thread additionally reserves a stack in virtual memory (megabytes on typical systems; threading.stack_size() returns 0 when you have not changed the platform default). The resident figure is small only because the stacks are barely touched; the reservation and the kernel's per-thread structures are what you hit first when you create very many threads, together with OS limits on thread counts (ulimit -u, cgroup pids.max, and vm.max_map_count on Linux). The exact limits vary by system, so check yours before designing for thousands of threads.

The resident-memory measurement (ru_maxrss is bytes on macOS and KiB on Linux, so the script normalises it):

python
# thread_memory.py: resident memory added by N parked threads.
# ru_maxrss is bytes on macOS and KiB on Linux, so normalise first.
import resource
import sys
import threading

N = 500


def rss_kib() -> float:
    peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
    return peak / 1024 if sys.platform == "darwin" else peak


if __name__ == "__main__":
    stop = threading.Event()
    before = rss_kib()
    threads = [threading.Thread(target=stop.wait) for _ in range(N)]
    for t in threads:
        t.start()
    after = rss_kib()
    print(f"{N} parked threads: about {(after - before) / N:.0f} KiB of peak resident memory each")
    stop.set()
    for t in threads:
        t.join()
Output · Python 3.14.6, macOS; the figure varies by system1 line
500 parked threads: about 36 KiB of peak resident memory each

What it means for an AI engineer. Size your pools from the nature of the work, not from folklore: about one process per core for CPU-bound stages; Little's-law-sized concurrency for waits; and never a thread pool larger than the work needs. Keep an eye on the switch rate and on involuntary switches when a CPU stage seems slow, and remember that every added unit of concurrency (a thread, a worker, a task) moves a cost from your wall-clock to your memory and your scheduler.


Part 6: Choosing a model#

6.1 The decision flow#

flowchart TD
    start["A slow step in your service"] --> q1{"Is it mostly waiting?<br/>(cpu/wall below ~0.2)"}
    q1 -->|"yes: I/O-bound"| q2{"Does a native async client exist?"}
    q2 -->|yes| asyncio_["asyncio + bounded concurrency"]
    q2 -->|"no, sync SDK only"| threads["thread pool<br/>(or asyncio.to_thread)"]
    q1 -->|"no: CPU-bound"| q3{"Does a C/Rust extension do the heavy part<br/>and release the GIL?"}
    q3 -->|yes| threads2["threads can work<br/>(measure it)"]
    q3 -->|no| q4{"Is the data large to copy between processes?"}
    q4 -->|no| procs["process pool"]
    q4 -->|yes| shm["process pool + shared memory / memory-map<br/>(01C.7)"]
    q1 -->|"mixed"| mixed["split the pipeline:<br/>I/O stage on the loop or threads,<br/>CPU stage in a process pool"]

Start with the measurement from 3.2: the diamond at the top is a number, not a feeling. Then read the table below for common AI workloads. Every row is a starting point; confirm with a measurement on your data.

6.2 AI workloads at a glance#

Workload Nature Reach for Why / watch out
LLM fan-out (hundreds of provider calls) I/O-bound asyncio with a semaphore (01B.4 §1.3); threads if only a sync client exists The bound is the provider's rate limit, not your CPU. See 03.9 §1.1
Streaming chat to many users I/O-bound, long-lived asyncio (ASGI server) Thousands of open connections: tasks, not threads
Embedding via a provider API I/O-bound asyncio, batched requests Batch to cut round trips (06.2)
Embedding with a local model on CPU CPU-bound, maybe memory-bound A process pool, or a single process with a multi-threaded native library Torch/ONNX use their own native threads: do not also wrap them in a big thread pool
Embedding on a GPU GPU-bound One process owning the GPU, with batching Several processes fighting over one GPU make it slower
PDF text extraction CPU-bound Process pool (05.2) Pure-Python parsers hold the GIL; threads will not speed them up
Tokenization of a corpus CPU-bound; native tokenizers sometimes release the GIL Process pool, or threads if you have measured a gain Check your tokenizer library's documentation and measure (see 01C.5)
Reading and hashing many files Mixed (disk I/O + hashing) Threads (hashlib releases the GIL for large inputs) or a small process pool Disk concurrency saturates quickly: do not use 100 threads on one SSD
JSON / JSONL parsing (large) CPU-bound Process pool by file or shard; stream rather than load json holds the GIL; sharding the files parallelizes it cleanly
Regex / text cleaning CPU-bound Process pool; pre-compile patterns Watch for catastrophic backtracking, which is a CPU-bound bug
Vector DB queries I/O-bound asyncio or threads The work is on the server
Ingestion pipeline (download, parse, chunk, embed, upsert) Mixed Staged: async for the I/O stages, process pool for parsing, bounded queues between (05.9) 3.3
Calling a sync-only SDK from a web service Blocking asyncio.to_thread for light use, or a dedicated thread pool (the default executor is bounded and shared) Never call it directly in an async def

6.3 Four questions before you add concurrency#

  1. Where does the time go? Measure CPU time versus wall time and profile one run. Do not parallelize what you have not measured.
  2. Is the work independent? Independent tasks parallelize easily; tasks that share mutable state need locks, queues or message passing (01C.3).
  3. What is the real bottleneck? The provider's rate limit, the database's connection pool, memory, or disk. More concurrency in front of a hard limit adds queueing and cost, not speed (01B.4 Part 4).
  4. What new failure modes do I accept? Threads add races and deadlocks, asyncio adds blocked loops and cancellation, processes add serialization and memory. Pick the model whose failure modes you can test for.

Reference

These are the bugs the five ideas of this lesson cause in real services. Each row is something you can now diagnose with a number rather than a hunch.

# Symptom Cause How to confirm Fix
1 The whole async service freezes for a second; health checks fail; then recovers A blocking call (sync SDK, time.sleep, requests, a big json.loads) on the loop thread (4.5) Loop-lag metric spikes; debug mode logs "Executing ... took N seconds" to_thread for blocking I/O, process pool for CPU, async-native client
2 Adding threads to a CPU-heavy job changes nothing (or slows it) CPU-bound Python code under the GIL (2.2) cpu/wall near 1.0 and flat as threads grow Process pool, or a library that releases the GIL; measure first
3 asyncio code for a parsing job is no faster than the plain loop CPU-bound work in coroutines that never await classify() says CPU-bound Process pool via run_in_executor
4 Latency grows with load while CPU is at 100 % on one core CPU-bound stage on the one loop thread (per-call JSON, token counting, validation) top shows one core pinned Move that stage off the loop; scale to more processes
5 Latency grows with load while CPU is at 5 % I/O-bound and queued behind a limit: a semaphore, a connection pool, the provider's rate limit cpu/wall tiny; in-flight count at the cap (Little's law) Raise the right limit, or accept it; do not add CPU
6 Creating a process pool per request makes every request slow Process start-up (spawn/forkserver re-imports modules) paid per call (2.4) Time the pool creation One long-lived pool; heavy imports in the worker initializer
7 "Too many open files" or "can't start new thread" under load Thread or descriptor per waiting unit; OS limits ulimit -n / ulimit -u; thread count in top -H Tasks instead of threads; bounded pools; raise limits deliberately
8 A worker "hangs forever" A blocking call with no timeout (recv, queue.get(), HTTP without a timeout) (4.2) py-spy dump shows the thread parked in recv/get Timeouts on every external wait; supervise with a watchdog
9 16 threads on 4 cores are slower than 4 Oversubscription of CPU-hungry threads (5.7) High involuntary switch rate (Linux) Pool sized to cores for CPU work
10 Speed-up stops at 3x on 16 workers The serial fraction (3.4): a single DB writer, a lock, a final merge Amdahl estimate from the measured speed-up Parallelize or batch the serial step; stop adding workers
11 Benchmark shows a process pool 3x faster; production shows it slower Benchmark excluded pool start-up and pickling; real payloads are big Benchmark with production-sized data and start-up included Shared memory (01C.7), smaller messages, or threads
12 Same code, different numbers on laptop and cloud VM Different core counts, CPU quotas, steal time, fork vs spawn defaults os.process_cpu_count(), nproc, /proc/stat steal Measure on production-like hardware; size pools from the quota
13 A process pool of N workers is slower than fewer workers, or a forked worker hangs or warns about parallelism Native-thread oversubscription: each worker runs NumPy, PyTorch or ONNX with its own BLAS/OpenMP threads, so N workers make N x threads runnable; or a fork after Hugging Face tokenizers already used its thread pool ("The current process just got forked ... disabling parallelism to avoid deadlocks") Load average far above core count; high involuntary switches (5.6); top -H shows many threads per worker Cap native threads per worker: OMP_NUM_THREADS, MKL_NUM_THREADS, torch.set_num_threads(1); set TOKENIZERS_PARALLELISM=false or use spawn/forkserver; fewer, larger workers

A last note on method for every row above: concurrency bugs are intermittent. A heartbeat that is late once an hour, a pool that deadlocks under one traffic shape, a counter that is off by three. The cure is to make the invisible visible with numbers (lag, CPU time, queue depth, switch rates) rather than to stare at code. The following lessons add the tools for races (01C.3) and deadlocks (01C.4).


Common misconceptions#

Misconception Reality
"Concurrency and parallelism are the same thing" Concurrency is structure (many things in progress); parallelism is execution (many things running at the same instant). You can have concurrency without parallelism, and (in the trivial sense of 1.3) parallelism with almost no concurrency structure (1.3)
"More threads is always faster" Only for waiting work. For CPU work in standard CPython the GIL stops speed-ups, and extra runnable threads add switching cost (5.7)
"asyncio makes my code run in parallel" asyncio runs one thread; it overlaps waits, not computation. CPU work in a coroutine blocks everyone (4.5)
"Blocking means slow" Blocking means the call does not return until done and the thread is parked. time.sleep blocks and uses no CPU; a non-blocking CPU loop can still be slow (4.1)
"Non-blocking means fast" It means the call returns immediately, with a result or "not ready". You still need a selector or a loop to know when to try again (4.3)
"A context switch costs 5 microseconds" A switch has a direct cost (typically a few microseconds) and an indirect cache cost that can be much larger; it depends on hardware and workload. Quote an order of magnitude, never a constant (5.4)
"Coroutine switches are free" They are far cheaper than OS switches in memory and kernel crossings, but a switch through the event loop costs microseconds of Python bytecode (5.4)
"Processes are always the fix for CPU-bound code" They beat the GIL but cost start-up, memory and serialization. For small tasks or large data, they can lose (6.2)
"If my program is I/O-bound it will not use CPU" I/O paths still parse, validate, encrypt and compress. At scale that CPU becomes the bottleneck (3.6)
"A single-threaded program has no concurrency bugs" An asyncio program interleaves tasks at every await; races exist across await points (01C.3)
"100 % CPU in top means the CPU is the bottleneck of my service" It means one core is busy. It may be exactly the one thread (the event loop) that serializes everything, while other cores idle

Key takeaways#

  • Concurrency is dealing with many things at once (structure); parallelism is doing many things at once (execution). Choose the structure first; the hardware decides how much parallelism you get.
  • One test classifies a task: CPU time divided by wall time. Near 0 is I/O-bound, near 1 is CPU-bound, in between is mixed. Measure before you choose threads, asyncio or processes.
  • For waiting, asyncio, threads and processes all overlap the waits; asyncio does it cheapest per wait. For computing in standard CPython, only processes (or GIL-releasing native code, or a free-threaded build) give real speed-ups.
  • Real jobs are pipelines. Keep the waits on the cheap-to-wait model and move the compute stages to a process pool, joined by bounded queues.
  • Amdahl's law caps every speed-up by the serial fraction. The first workers help most; shrinking the serial part beats adding workers. Little's law sizes the in-flight count for I/O.
  • Blocking is a property of one call on one thread. It is harmless in a worker thread and fatal on the event-loop thread. Hidden blockers (sync SDKs, DNS, files, CPU work, slow loggers) are the top async production bug; detect them with a heartbeat, debug mode and a loop-lag metric.
  • A selector (epoll, kqueue, IOCP) lets one thread wait on thousands of sockets. Regular files and DNS are not selectable, so async libraries use threads for them.
  • A context switch saves registers and a stack pointer (and, between processes, the address space); the real cost is the cold caches afterwards. Typical cost is microseconds to hundreds of microseconds. Coroutine switches are cheapest in memory and kernel crossings, not magically free.
  • The OS is preemptive, asyncio is cooperative, CPython threads are both. Cooperative scheduling means no preemption between awaits but no fairness for a task that never yields.
  • Size pools from the work: about one worker per core for CPU-bound, Little's-law-sized for waits, separate pools for mixed stages. Create pools once; warm them.

Terms introduced in this lesson#

Term Meaning
Concurrency Structuring a program as independently progressing tasks so many can be in progress at once; a property of design
Parallelism Several computations executing at the same instant on different cores or machines; a property of execution
Data parallelism Running the same operation on different chunks of data in parallel, with no coordination
I/O-bound Limited by waiting for something outside the CPU (network, disk, another service)
CPU-bound Limited by how fast the CPU can execute instructions
CPU time / wall time The share of real elapsed time a process spent actually executing; the diagnosis for I/O- vs CPU-bound
Wall-clock time Real elapsed time, as measured by a stopwatch (time.perf_counter)
Amdahl's law The speed-up from N workers is limited by the fraction of the job that must stay serial
Blocking call A call that does not return until the awaited event happens; the calling thread is parked
Non-blocking call A call that returns immediately, with a result or a "not ready" error (EAGAIN/BlockingIOError)
System call (syscall) A request from a program to the operating-system kernel (read, recv, futex...)
O_NONBLOCK The file-descriptor flag that makes I/O calls non-blocking; socket.setblocking(False) sets it
I/O multiplexing Waiting on many descriptors with one call (select, poll, epoll, kqueue)
Readiness vs completion model The kernel says "ready to read" (select/epoll/kqueue) versus "operation finished" (IOCP, io_uring)
Selector An object (Python's selectors module) that wraps the best multiplexing mechanism on the platform
Context switch Stopping one thread or process and resuming another, saving and restoring the first one's CPU state
TLB The CPU cache of address translations; a process switch invalidates much of it
Preemptive scheduling An outside scheduler interrupts tasks at almost any moment (OS threads and processes)
Cooperative scheduling Tasks switch only where they explicitly yield (await, yield)
Switch interval CPython's request interval for handing over the GIL between threads (sys.getswitchinterval(), 5 ms by default)
Voluntary / involuntary context switch The thread gave up the CPU to wait, versus the scheduler took the CPU away
Oversubscription More runnable (CPU-hungry) threads than cores, causing extra switching
Event-loop lag How late a timer fires; measures how long the loop was unavailable

Exercises#

  1. Classify. Use classify from 3.2 on lambda: sum(range(10_000_000)). Which label do you get, and why would time.sleep(1) get the other one?
  2. Amdahl in numbers. A job is 80 % parallel. What speed-up do 8 workers give, and what is the ceiling with unlimited workers?
  3. How parallel does it need to be? You want a 6x speed-up on 8 workers. What parallel fraction do you need?
  4. Non-blocking. Create a socketpair, make one end non-blocking and call recv with nothing sent. What do you get?
  5. Little's law. A pipeline must complete 50 LLM calls per second and each call takes 2 seconds. How many calls must be in flight?
  6. Write the chooser. Write choose_model(cpu_share, has_async_client, heavy_part_releases_gil=False) implementing the decision flow of 6.1, and try five inputs.
  7. Does a thread rescue the loop? Measure the worst gap of a 20 ms heartbeat while a CPU-heavy function (about one second) runs inline in a coroutine, and while it runs through asyncio.to_thread. What do you conclude?
  8. The switch interval. Print the current switch interval, then change it to 1 ms for a moment and restore it. Why should you restore it?
  9. Thread-pool default. Compute ThreadPoolExecutor's documented default max_workers for your machine and check it against the real default.
  10. A weighted juggler. Extend the round_robin generator example so that job A gets two steps per turn and job B one. With 4 steps of A and 3 of B, what order do you print?
  11. Triage. Classify each, name the model you would start with, and say what you would measure first: (a) embedding 2 million chunks with a provider API, (b) running OCR on 5,000 scanned pages with a CPU library, (c) a FastAPI endpoint that calls a sync-only vendor SDK, (d) computing SHA-256 of 10,000 files of 50 MB each.
  12. Predict, then run. In four_ways.py change Job B to hash 1 MB blocks (use one pre-built 1 MB bytes block and hash it repeatedly) and predict whether threads now help. Explain using the hashlib documentation.
Solution

1. CPU-bound: the CPU was busy the whole time (cpu/wall close to 1). time.sleep(1) would be I/O-bound (waiting), with cpu/wall near 0. Run:

python
from classify import classify

label, _ = classify(lambda: sum(range(10_000_000)))
print(label)
Output1 line
CPU-bound (mostly computing)

2 and 3. 1 / ((1 - p) + p / n) with p = 0.8, n = 8 gives 3.33; the ceiling is 1 / (1 - 0.8) = 5.0. For question 3 solve S = 1 / ((1 - p) + p / n) for p: p = (1 - 1/S) / (1 - 1/n).

python
def amdahl(p: float, n: int) -> float:
    return 1.0 / ((1.0 - p) + p / n)


print("speed-up for p=0.8, 8 workers:", round(amdahl(0.8, 8), 2))
print("ceiling for p=0.8:", round(1 / (1 - 0.8), 1))
p = (1 - 1 / 6) / (1 - 1 / 8)
print("parallel fraction needed for 6x on 8 workers:", round(p, 3))
Output3 lines
speed-up for p=0.8, 8 workers: 3.33
ceiling for p=0.8: 5.0
parallel fraction needed for 6x on 8 workers: 0.952

So 6x on 8 workers needs the job to be about 95 % parallel: the serial part must stay under about 5 %.

4. BlockingIOError (the Python form of EAGAIN/EWOULDBLOCK):

python
import socket

a, b = socket.socketpair()
a.setblocking(False)
try:
    a.recv(10)
except BlockingIOError as exc:
    print(type(exc).__name__)
a.close()
b.close()
Output1 line
BlockingIOError

5. 50 calls/s x 2 s = 100 in flight (Little's law, 01B.4 §6.1). If the provider allows fewer concurrent requests than that, the rate cap wins and throughput is concurrency / latency.

6.

python
def choose_model(cpu_share: float, has_async_client: bool, heavy_part_releases_gil: bool = False) -> str:
    if cpu_share < 0.2:
        return "asyncio" if has_async_client else "threads"
    if cpu_share > 0.8:
        return "threads" if heavy_part_releases_gil else "processes"
    return "split the pipeline"


print(choose_model(0.02, True), "|", choose_model(0.02, False), "|", choose_model(0.98, False), "|",
      choose_model(0.98, False, True), "|", choose_model(0.5, True))
Output1 line
asyncio | threads | processes | threads | split the pipeline

7. Run the heartbeat from 4.5 with a 20 ms interval around a CPU function (burn(5_000_000), roughly one second on the machine used here; if your machine is much faster or slower, scale the number and the 0.3 s threshold):

python
import asyncio
import hashlib
import time


def burn(n: int) -> None:
    h = b"seed"
    for _ in range(n):
        h = hashlib.sha256(h).digest()


async def worst_gap(work) -> float:
    gaps: list[float] = []
    stop = asyncio.Event()

    async def beat() -> None:
        last = time.perf_counter()
        while not stop.is_set():
            await asyncio.sleep(0.02)
            now = time.perf_counter()
            gaps.append(now - last)
            last = now

    task = asyncio.create_task(beat())
    await asyncio.sleep(0.1)
    await work()
    await asyncio.sleep(0.1)
    stop.set()
    await task
    return max(gaps)


async def main() -> None:
    async def inline() -> None:
        burn(5_000_000)  # runs on the loop thread

    inline_gap = await worst_gap(inline)
    threaded_gap = await worst_gap(lambda: asyncio.to_thread(burn, 5_000_000))
    print("loop frozen > 0.3 s when CPU work runs inline:", inline_gap > 0.3)
    print("loop frozen > 0.3 s when CPU work runs in a thread:", threaded_gap > 0.3)


if __name__ == "__main__":
    asyncio.run(main())
Output2 lines
loop frozen > 0.3 s when CPU work runs inline: True
loop frozen > 0.3 s when CPU work runs in a thread: False

Moving CPU work to a thread keeps the loop responsive here, because the loop thread and the worker take turns on the GIL (every switch interval) and the hash is quick in small steps. But the thread has not made the computation any faster, and the loop's wake-ups are now delayed by up to one switch interval and compete with the worker: heavy CPU work in a thread still slows the loop's latency under GIL contention. For real isolation use a process pool (3.3).

8.

python
import sys

print(sys.getswitchinterval())
original = sys.getswitchinterval()
sys.setswitchinterval(0.001)
print(sys.getswitchinterval())
sys.setswitchinterval(original)
Output2 lines
0.005
0.001

Restore it because the setting is process-wide: it affects every thread in the interpreter and every library that uses threads, long after your experiment is over.

9.

python
import os
from concurrent.futures import ThreadPoolExecutor

documented = min(32, (os.process_cpu_count() or 1) + 4)  # 3.13+ formula
with ThreadPoolExecutor() as pool:
    print(pool._max_workers == documented)  # private attribute: for checking only

On the machine used here this printed True. On Python 3.11 or 3.12 os.process_cpu_count does not exist (the formula there is min(32, os.cpu_count() + 4)), so adapt the check. Never depend on _max_workers in application code.

10.

python
def weighted_round_robin(jobs: dict[str, int], steps: dict[str, int]) -> list[str]:
    # jobs: name -> turns per round; steps: name -> remaining steps
    log = []
    remaining = dict(steps)
    while any(remaining.values()):
        for name, turns in jobs.items():
            for _ in range(turns):
                if remaining[name]:
                    remaining[name] -= 1
                    log.append(name)
    return log


print("".join(weighted_round_robin({"A": 2, "B": 1}, {"A": 4, "B": 3})))
Output1 line
AABAABB

This is weighted cooperative scheduling. Real event loops are FIFO and give every ready task one turn; fairness policies are a scheduler concern (01C.4 covers starvation).

11. (a) I/O-bound: asyncio with batching and a bounded semaphore; measure the provider's rate limit and the in-flight count (Little's law). (b) CPU-bound: a process pool with about one worker per core; measure the seconds per page and the cpu/wall ratio on one page first; check whether the OCR library already uses multiple native threads (if it does, fewer processes). (c) Blocking-in-async trap: asyncio.to_thread or a bounded thread pool around the SDK; measure loop lag; prefer the vendor's async client if one exists. (d) Mixed but mostly disk and hash: threads work, because hashlib releases the GIL for large inputs; measure whether the disk saturates before the cores do.

12. Hashing large blocks releases the GIL: the hashlib documentation says the GIL is released "while computing a hash supplied more than 2047 bytes of data at once". So threads should now speed up Job B (up to about the number of cores), while the original small-input loop does not. The point of the exercise: what the thread does inside the C function decides whether threads help, not the word "CPU-bound". This exercise's code is intentionally left for you to run: the speed-up is machine-dependent, so the lesson does not print one.


Where you'll use this in the AI path#

This lesson Where it comes back
I/O-bound fan-out, asyncio, thread pools 01B.3, 01B.4 (bounded concurrency, queues, Little's law), 03.9 (async LLM clients, batch APIs)
Blocking calls in async code 01B.3 §8.1, 03.9 §2.6
CPU-bound parsing and the process pool 05.2 parsing PDFs, 05.9 ingestion pipelines
Embedding pipelines (batching, concurrency) 06.2 embedding pipelines
Event-loop lag, CPU time versus wall time in production 11A.2 metrics, SLOs and alerting, 11C.1 deployment
Bulkheads, load shedding and reliability under load 11C.3 fallbacks, gateways and reliability
The next lessons of this module 01C.2 the event loop, 01C.3 races, 01C.5 the GIL, 01C.7 shared memory

Check yourself#

  1. State the difference between concurrency and parallelism in one sentence each, and give a Python example of each that does not involve the other.
  2. Why does asyncio.gather over 8 one-second sleeps take about 1 second, but asyncio.gather over 4 functions that each compute for one second take about 4?
  3. Your service shows cpu_time / wall_time = 0.04 for a request handler. Which model would you reach for first, and what is the likely real bottleneck?
  4. With 16 workers, a job is 15 % serial. Roughly what speed-up can you expect at most, and what would raise it more: 32 workers, or halving the serial part?
  5. What does socket.setblocking(False) change? What exception does recv raise when there is no data?
  6. Why can select/epoll not make reading a regular file non-blocking, and what does asyncio do instead?
  7. List four things that commonly block an event loop without time.sleep appearing anywhere in the code.
  8. What are the three ways to detect a blocked event loop described in this lesson?
  9. What is saved and restored in a thread switch, what extra changes in a process switch, and what is the "indirect" cost?
  10. Which is preemptive and which is cooperative: OS threads, asyncio tasks? What practical consequence follows for a CPU loop in each?
  11. What does sys.getswitchinterval() control, and what does it not control?
  12. A thread sleeps in time.sleep(1) fifty times. Which context-switch counter increases on Linux, and what would a growing other counter on a CPU-bound process mean?
  13. Why is a thread pool of 200 threads fine for 200 waiting LLM calls but harmful for 200 CPU-bound jobs?
  14. Why can a "just calls an API" function become CPU-bound at high concurrency?
  15. Your benchmark says a process pool is 3x faster than sequential, yet production is slower. Name three things the benchmark might have left out.

Further resources#


← Module 01B: Python for AI Engineering | Module 01C overview | 01C.2: Synchronous vs Asynchronous Programming and the asyncio Event Loop →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close