01B.4 Concurrency Patterns for I/O-Heavy Work
Lesson 01B.3 taught you async/await: how to write a coroutine that pauses instead of blocking, and how asyncio schedules many of them on one thread. That lesson ended with the obvious next question: now that I can run many things at once, how do I run the right number of things, in the right pattern, without the whole thing falling over? This lesson answers it. You will learn the production patterns for I/O-heavy concurrency — bounded fan-out, worker pools, producer/consumer queues, pipelines, rate limiting, batching, backpressure, graceful shutdown and in-flight deduplication — each one with runnable standard-library code, plus the thread and process tools for the cases where asyncio is not the answer, and the arithmetic (Little's law) that tells you what concurrency limit to pick. Everything here is provider-neutral; the last part shows the same patterns aimed at an LLM backend and links to where Module 03 applies them for real.
What you'll learn
- Why unbounded concurrency fails on real services: rate limits, connection limits, memory, provider concurrency caps and the thundering herd — and why bounded concurrency is the core pattern
- Fan-out primitives:
asyncio.gatherwith a semaphore,asyncio.TaskGroupwith limits, per-task and per-batch timeouts, preserving order, collecting partial results in aResulttype, and choosing between cancel-on-first-failure and continue-on-error - Worker pools and pipelines on
asyncio.Queue: producer/consumer,task_done()/join(), sentinel values andQueue.shutdown()(Python 3.13+), bounded queues as backpressure, multi-stage pipelines, progress reporting and graceful shutdown - Rate limiting written from scratch: the token bucket and the sliding window, with a fake clock so the demos are deterministic
- Batching: accumulating N items or T seconds, whichever comes first, and how that differs from a provider's Batch API
- Little's law (
concurrency = throughput × latency), a worked sizing calculation, and how to measure whether more concurrency is actually helping - Coordination primitives:
asyncio.Lock,asyncio.Condition,asyncio.Event, and single-flight deduplication of in-flight work - Threads and processes: the GIL and what it does and doesn't block,
threadingwith locks,concurrent.futuresexecutors,asyncio.to_thread,multiprocessingfor CPU-bound work, free-threaded Python (officially supported since 3.14), and a decision table for which tool to reach for - Running async pipelines from synchronous code, and the library landscape (
anyio,aiolimiter,asyncio-throttle,tenacity's async support) - The
aitoolkit/concurrency.pydeliverable:bounded_gather,RateLimiter,run_pipelineandResult, in full
What you don't need
- Anything from Module 02 onwards. Every example calls a fake slow service written in this lesson — no API key, no network, no third-party packages.
- Deep asyncio knowledge. Lesson 01B.3 covers coroutines, the event loop,
gather,TaskGroup,Semaphoreand cancellation; this lesson assumes you know them and builds the patterns on top. - Operating-system or distributed-systems theory. Where a concept has a famous name (Little's law, thundering herd, backpressure), you get the plain-English version and the link for the deep version.
Setup
No API key needed. Every runnable example uses the Python standard library only (asyncio, threading, concurrent.futures, multiprocessing, signal, time, json, contextlib), so there is nothing to install. You need Python 3.11 or newer; a few examples use asyncio.Queue.shutdown(), which arrived in 3.13, and the lesson marks those. If you work inside the module's aitoolkit project from 01B.1, run the snippets with uv run python file.py; otherwise a plain python3 file.py works.
# optional: check your interpreter version (3.11+ required, 3.13+ for Queue.shutdown demos)
python3 --versionWhat you must be able to do after this lesson#
- Explain why unbounded concurrency fails on real services
- Limit concurrency with a semaphore around gather or a TaskGroup
- Build a worker pool with asyncio.Queue and shut it down cleanly
- Write a token bucket rate limiter with a fake clock
- Choose a concurrency limit using Little's law
- Use bounded_gather, RateLimiter and run_pipeline from aitoolkit
Why this matters for an AI engineer#
Almost everything an AI engineer writes is a pile of slow calls. Embedding 40,000 chunks, classifying 20,000 tickets, running an eval suite, enriching a crawl — each item is one network round-trip measured in hundreds of milliseconds to tens of seconds, and the provider will stop you long before your laptop runs out of ideas. The difference between a prototype and a production data job is almost entirely the concurrency design: how many calls are in flight, who decides, what happens to the failures, and how the job behaves when it is killed halfway.
| You'll hear... | You'll understand it after... |
|---|---|
"Just asyncio.gather everything." |
1.2 What actually breaks, 2.1 gather plus a semaphore |
| "We got 429s and then the provider banned us for an hour." | 1.2, 4.2 The token bucket |
| "How many workers should the ingestion job use?" | 6.1 Little's law, 6.3 Choosing the limit |
| "The job died at item 38,000 — do we start over?" | 3.6 Graceful shutdown, Part 5 batching |
| "Some chunks failed; the run reported success anyway." | 2.4 The Result type |
| "A thousand users asked for the same report at once." | 7.1 Single-flight |
| "The SDK is sync-only — do we rewrite it in async?" | 8.4 When threads are the right tool |
| "Why is the CPU at 100% while everything waits on the network?" | 8.1 The GIL, 8.4 |
| "Batch API or just more concurrency?" | 5.5, 03.9 Part 6 |
Part 1: Why unbounded concurrency fails#
1.1 A pile of slow calls#
Picture the canonical AI-engineering job: you have N items (documents to embed, tickets to classify, eval questions to answer) and each item needs one slow call to a service. One call takes L seconds. Almost all of L is spent waiting for the other side; your CPU is idle.
If you process items one at a time, total time is N × L. If you run C calls concurrently — meaning C calls are in flight at the same moment — the same work finishes in roughly N × L / C, as long as the service keeps up. That is the entire promise of concurrency, and it is why lesson 01B.3 exists.
The catch, and the subject of this lesson, is that C is not free. Every in-flight call costs something: a socket, some memory, some CPU for TLS (the encryption layer inside HTTPS) and JSON, a slot in the provider's rate-limit budget, and a share of whatever the other in-flight calls get. Push C high enough and the system does not get faster — it gets sicker.
1.2 What actually breaks#
Run N = 10,000 items with C = 10,000 — every call in flight at once — against a real provider and you will meet most of these, usually in this order:
| Failure | What it looks like | Why it happens |
|---|---|---|
| Rate limiting (HTTP 429) | Calls start failing with "rate limit exceeded" | Providers cap requests per minute (RPM) and tokens per minute (TPM). Your account has a quota; you just spent it all in one second |
| Connection limits | ConnectError, timeouts, "too many open files" |
Each in-flight HTTP call holds a TCP connection (and with HTTP/2, a stream). OS socket limits and the provider's per-connection caps are finite — typically a few hundred to a few thousand |
| Memory growth | RSS (resident set size — the memory the process actually holds) climbs until the OS kills it for out-of-memory (OOM) | Every pending request holds its payload, its response buffer, its task object and its stack. Ten thousand pending calls is ten thousand copies of everything |
| Provider concurrency caps | 429s or 5xx even under the RPM limit | Some providers (and gateways) cap simultaneous requests, not just requests per minute — a second, independent limit |
| Queueing collapse | Everything slows down; latency spikes | The provider's own queues fill. Your 1-second calls become 30-second calls because they waited in line. More concurrency made each call slower |
| Thundering herd | A synchronized wave of retries hits a recovering service | When many calls fail together, retrying them all at once re-creates the spike that caused the failure (jittered backoff in 01B.9 exists partly to prevent this) |
| Your own bottleneck | The event loop itself falls behind | Each completed call still needs Python code to run: parsing JSON, updating state, writing results. At extreme fan-out the loop can't keep up and everything queues anyway |
1.3 Bounded concurrency is the fix#
The fix is almost embarrassingly simple: never have more than C_max calls in flight, where C_max is chosen deliberately. A semaphore — a counter of free slots — is the standard mechanism (lesson 01B.3 introduced asyncio.Semaphore; 03.9 uses exactly this against real LLM APIs). Everything else in this lesson is about what to do around that bound: how to keep results ordered, how to handle partial failure, how to pace requests so you never hit the rate limit in the first place, and how to drain cleanly when the job is interrupted.
flowchart LR
subgraph unbounded ["Unbounded: gather(everything)"]
U1["10,000 tasks"] --> U2["10,000 sockets<br/>10,000 pending responses"]
U2 --> U3["429s, timeouts,<br/>OOM, ban"]
end
subgraph bounded ["Bounded: semaphore + workers"]
B1["10,000 items"] --> B2["Queue"]
B2 --> B3["C_max workers<br/>(e.g. 20)"]
B3 --> B4["Results + failures<br/>collected as they land"]
end1.4 Try it: sequential vs unbounded vs bounded#
Here is the whole lesson in miniature. slow_call stands in for any I/O-bound call — an embedding request, an LLM completion, a database read — by sleeping for a fixed time. The fake latency is 0.3 s per call and there are 6 items, chosen so the three strategies produce clearly different wall times.
# fanout_demo.py — three ways to run 6 slow calls
import asyncio
import time
CALLS = 6
LATENCY = 0.3 # seconds; stands in for a network round-trip
async def slow_call(item: int) -> str:
await asyncio.sleep(LATENCY)
return f"result-{item}"
async def sequential() -> None:
for i in range(CALLS):
await slow_call(i)
async def unbounded() -> None:
await asyncio.gather(*(slow_call(i) for i in range(CALLS)))
async def bounded(limit: int) -> None:
sem = asyncio.Semaphore(limit)
async def guarded(i: int) -> str:
async with sem:
return await slow_call(i)
await asyncio.gather(*(guarded(i) for i in range(CALLS)))
async def main() -> None:
for name, coro in [("sequential", sequential()),
("unbounded ", unbounded()),
("bounded = 3", bounded(3))]:
t0 = time.perf_counter()
await coro
print(f"{name}: {time.perf_counter() - t0:.1f}s")
asyncio.run(main())Run it:
python3 fanout_demo.pysequential: 1.8s
unbounded : 0.3s
bounded = 3: 0.6sThe remainder of this lesson builds the machinery that gets you the "bounded" row and keeps the results, the failures and the shutdown behaviour under control.
Part 2: Fan-out primitives#
"Fan-out" means taking a collection of items and running the same operation on many of them at once. It is the most common concurrency shape in AI work, and asyncio gives you three ways to do it. They differ in exactly two ways that matter: how failures propagate and how you bound the concurrency.
2.1 gather plus a semaphore: bounded fan-out#
asyncio.gather (lesson 01B.3) runs coroutines concurrently and returns their results in the order you passed them, not the order they finish. Wrap each coroutine in a semaphore and you have bounded fan-out in six lines:
# bounded_gather.py — the canonical bounded fan-out
import asyncio
async def bounded_gather(coros, limit: int):
"""Run awaitables with at most `limit` in flight; results keep input order."""
sem = asyncio.Semaphore(limit)
async def guarded(coro):
async with sem:
return await coro
return await asyncio.gather(*(guarded(c) for c in coros))Two details deserve a second look:
- The semaphore wraps the await, not the task creation. All
Ncoroutines are still created (cheap — a coroutine object is just a suspended computation), but onlylimitof them are ever insideslow_callat once. The rest are parked onsem.acquire(). Memory for in-flight calls stays bounded bylimit, not byN— but theNparked tasks themselves still cost memory (a task object, a coroutine frame and a semaphore waiter each), which is why Part 3's worker pool exists for very large inputs. gatherwithoutreturn_exceptions=Truefails fast. The first exception propagates out ofgatherimmediately, and the remaining coroutines are not cancelled — they keep running in the background, detached, until the loop ends or they finish. For a data job that is a leak: you think the run failed, but 400 calls are still burning quota. Lesson 01B.3 covered the fix; this lesson builds the whole result-collection pattern around it (2.4, 2.5).
2.2 TaskGroup fan-out with limits#
asyncio.TaskGroup (Python 3.11+, lesson 01B.3) is the structured-concurrency alternative to gather: tasks live and die together, and the first failure cancels all the others and raises an ExceptionGroup. To bound it, use the worker pattern: spawn exactly limit worker tasks, each pulling items from a shared asyncio.Queue. The number of live tasks is limit, not N — which matters when N is a million-row file, because creating a million coroutine objects still costs memory:
# taskgroup_workers.py — TaskGroup + bounded workers over a queue
import asyncio
STOP = object() # sentinel: tells a worker the input is finished
async def process(item: int) -> str:
await asyncio.sleep(0.02) # stands in for a network call
if item % 7 == 0:
raise ValueError(f"bad item {item}")
return f"done-{item}"
async def worker(queue: asyncio.Queue, sink: list, errors: list) -> None:
while True:
item = await queue.get()
try:
if item is STOP:
return
try:
sink.append(await process(item))
except Exception as exc:
errors.append((item, exc))
finally:
queue.task_done()
async def run_all(items: list[int], n_workers: int) -> tuple[list, list]:
queue: asyncio.Queue = asyncio.Queue()
for item in items:
queue.put_nowait(item)
for _ in range(n_workers): # one sentinel per worker
queue.put_nowait(STOP)
sink: list = []
errors: list = []
async with asyncio.TaskGroup() as tg:
for _ in range(n_workers):
tg.create_task(worker(queue, sink, errors))
return sink, errors
async def main() -> None:
results, errors = await run_all(list(range(10)), 3)
print("results:", sorted(results))
print("errors :", [(i, type(e).__name__) for i, e in sorted(errors)])
asyncio.run(main())results: ['done-1', 'done-2', 'done-3', 'done-4', 'done-5', 'done-6', 'done-8', 'done-9']
errors : [(0, 'ValueError'), (7, 'ValueError')]Three things to notice:
- Items are handed out in FIFO order —
queue.get()returns them in the order they were put — but they finish out of order, sosinkis not sorted. If downstream code needs input order, carry the index with the item (Part 3 shows the canonical version). - Every exit path calls
queue.task_done()in afinally, even the sentinel path and the error path. Forgetting it is the classic way to hangqueue.join()— 3.2 and the failure gallery cover it. - The sentinel is an object, not a value. Using
Noneworks only ifNonecan never be a legitimate item; a dedicatedSTOP = object()cannot collide with anything.
2.3 Timeouts per task and per batch#
Lesson 01B.3 covered asyncio.timeout(); here is how it composes with fan-out. There are two different timeouts and confusing them is a classic production bug:
| Timeout | Question it answers | Mechanism |
|---|---|---|
| Per-task | "This one call is taking too long — give up on it" | asyncio.timeout(N) around the single await |
| Per-batch / whole-job | "The entire run has a deadline — stop everything" | asyncio.timeout(N) around the gather/TaskGroup, or a deadline timestamp passed down and checked per item |
# timeouts_demo.py — per-task timeout inside bounded fan-out
import asyncio
async def slow_call(item: int, delay: float) -> str:
await asyncio.sleep(delay)
return f"ok-{item}"
async def call_with_timeout(item: int, delay: float, timeout_s: float) -> str:
try:
async with asyncio.timeout(timeout_s):
return await slow_call(item, delay)
except TimeoutError:
return f"timeout-{item}"
async def main() -> None:
# items 0..4 get delays 0.1..0.5; timeout is 0.25s
out = await asyncio.gather(*(
call_with_timeout(i, 0.1 * (i + 1), 0.25) for i in range(5)
))
print(out)
asyncio.run(main())['ok-0', 'ok-1', 'timeout-2', 'timeout-3', 'timeout-4']For the whole-job deadline, compute one timestamp up front and give every task only the time that remains:
async def run_job(items, process, limit=20, deadline_s=60.0):
"""Bounded fan-out where the WHOLE job shares one deadline."""
sem = asyncio.Semaphore(limit)
loop = asyncio.get_running_loop()
end = loop.time() + deadline_s # one deadline for everyone
async def one(item):
async with sem:
remaining = end - loop.time()
if remaining <= 0:
raise TimeoutError("job deadline exceeded")
async with asyncio.timeout(remaining):
return await process(item)
return await asyncio.gather(*(one(i) for i in items),
return_exceptions=True)The second version is the pattern 03.9 calls a job deadline: one timestamp computed once, and every task gets only the time that remains. Prefer it over per-task timeouts when the requirement is "finish the batch within the hour", not "each call may take an hour".
2.4 Preserving order and collecting partial results#
Two requirements show up in every real data job:
- Order preservation. Results must line up with inputs — result
ibelongs to itemi— because you'll join them back by position or ID.gathergives you this for free; worker pools do not (workers finish out of order). The fix is to carry the index with the item and write into a preallocated list, exactly as the queue version below does. - Partial results. In a 10,000-item job, some items will fail. You want the successes, the failures with their errors, and a count — not an exception that throws away everything.
The clean way to express "value or error" is a tiny result type — a tagged union of "we got a value" and "we got an exception", so callers pattern-match instead of try/excepting around every item:
# result_type.py — Ok/Err, the smallest useful result type
from dataclasses import dataclass
from typing import Generic, TypeVar, Union
T = TypeVar("T")
E = TypeVar("E", bound=BaseException)
@dataclass(frozen=True)
class Ok(Generic[T]):
value: T
@dataclass(frozen=True)
class Err(Generic[E]):
error: E
Result = Union[Ok[T], Err[E]] # annotate as Result[str, RuntimeError], etc.Result[str, RuntimeError] then reads as "either Ok wrapping a str, or Err wrapping a RuntimeError". This exact Result type is what aitoolkit/concurrency.py ships in Part 10, and 03.9 uses the same idea (ItemResult) for LLM calls.
Now the fan-out that produces ordered Results — this is the workhorse pattern of the whole lesson:
# ordered_results.py — bounded fan-out that keeps order and never raises per-item
import asyncio
from dataclasses import dataclass
@dataclass(frozen=True)
class Ok:
value: object
@dataclass(frozen=True)
class Err:
error: BaseException
index: int
async def worker(queue: asyncio.Queue, out: list, stats: dict) -> None:
while True:
try:
index, item = queue.get_nowait()
except asyncio.QueueEmpty:
return
try:
out[index] = Ok(await process(item))
stats["ok"] += 1
except Exception as exc:
out[index] = Err(exc, index)
stats["err"] += 1
finally:
queue.task_done()
async def process(item: int) -> str:
await asyncio.sleep(0.02)
if item % 5 == 0:
raise RuntimeError(f"item {item} failed")
return f"result-{item}"
async def run_bounded(items: list[int], limit: int) -> tuple[list, dict]:
queue: asyncio.Queue = asyncio.Queue()
for i, item in enumerate(items):
queue.put_nowait((i, item))
out: list = [None] * len(items)
stats = {"ok": 0, "err": 0}
async with asyncio.TaskGroup() as tg:
for _ in range(min(limit, len(items))):
tg.create_task(worker(queue, out, stats))
return out, stats
async def main() -> None:
results, stats = await run_bounded(list(range(10)), 3)
for i, r in enumerate(results):
print(i, type(r).__name__, getattr(r, "value", getattr(r, "error", "")))
print(stats)
asyncio.run(main())0 Err item 0 failed
1 Ok result-1
2 Ok result-2
3 Ok result-3
4 Ok result-4
5 Err item 5 failed
6 Ok result-6
7 Ok result-7
8 Ok result-8
9 Ok result-9
{'ok': 8, 'err': 2}This is the shape to remember: index travels with the item; results land in a preallocated list; every item's outcome is captured; task_done() is in a finally. Part 10's run_pipeline generalises exactly this.
2.5 Cancel-on-first-failure vs continue-on-error#
The last design choice in fan-out is what should happen when something fails. There are three honest policies:
| Policy | Mechanism | When it's right |
|---|---|---|
| Fail fast | TaskGroup default: first exception cancels siblings, raises ExceptionGroup |
The batch is worthless if incomplete (a single atomic transaction, a "all-or-nothing" import) |
| Continue on error | Catch per item, collect Errs (the 2.4 pattern) |
Data jobs: 9,980 good embeddings beat 0 because 20 failed |
| Fail fast with cleanup | try/finally or async with around the fan-out so resources close |
Anything holding connections, files or temp state |
# fail_fast.py — TaskGroup cancels siblings on first failure
import asyncio
async def work(item: int) -> str:
await asyncio.sleep(0.05 * (item + 1))
if item == 2:
raise RuntimeError("boom")
return f"ok-{item}"
async def main() -> None:
tasks = []
try:
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(work(i)) for i in range(5)]
except* RuntimeError as eg:
print("caught:", [str(e) for e in eg.exceptions])
print("cancelled:", [t.cancelled() for t in tasks])
asyncio.run(main())caught: ['boom']
cancelled: [False, False, False, True, True]Read the second line carefully: tasks 0, 1 and 2 had already finished (or were finishing) before the failure at item 2 propagated; tasks 3 and 4 were still waiting and got cancelled. TaskGroup gives you "the first failure cancels everything still running" for free — exactly what you want for atomic work, and exactly wrong for a 10,000-item data job where one bad row would kill 9,999 good ones. That is why 2.4 exists. Choose the policy per job, and write the choice down.
Part 3: Worker pools, queues and pipelines#
The gather-based fan-out in Part 2 creates one coroutine per item. For 10,000 items that is fine; for 10 million it is not — each pending coroutine costs memory and scheduler attention. The worker pool fixes this: create limit long-lived worker tasks once, feed them items through a queue, and let them drain it. The number of live tasks stays at limit no matter how big the input is. This is also the shape that gives you backpressure and pipelines almost for free.
3.1 Producer/consumer with asyncio.Queue#
asyncio.Queue is an async FIFO: producers put() items, consumers get() them. When the queue is empty, get() suspends the consumer until an item arrives; when it is full (maxsize reached), put() suspends the producer until a consumer frees a slot. That suspension is the coordination — no locks needed for the hand-off itself.
flowchart LR
P["Producer(s)<br/>put items"] --> Q[("asyncio.Queue<br/>maxsize=N")]
Q --> W1["worker 1"]
Q --> W2["worker 2"]
Q --> W3["worker ... limit"]
W1 --> R[("results / sink")]
W2 --> R
W3 --> R# pool.py — the canonical bounded worker pool
import asyncio
STOP = object()
async def worker(queue: asyncio.Queue, process, sink: list, errors: list) -> None:
"""One consumer: pull items until the sentinel, process, report."""
while True:
item = await queue.get()
try:
if item is STOP:
return
try:
sink.append(await process(item))
except Exception as exc: # per-item failure
errors.append((item, exc))
finally:
queue.task_done() # ALWAYS, every path
async def run_pool(items, process, limit: int = 4, queue_size: int = 0):
"""Run `process` over `items` with `limit` workers.
queue_size=0 means an unbounded queue; queue_size>0 applies
backpressure so producers can't run ahead of consumers.
"""
queue: asyncio.Queue = asyncio.Queue(maxsize=queue_size)
sink: list = []
errors: list = []
workers = [worker(queue, process, sink, errors) for _ in range(limit)]
async with asyncio.TaskGroup() as tg:
for w in workers:
tg.create_task(w)
for item in items: # producer role, inline here
await queue.put(item) # suspends when queue is full
for _ in workers: # one sentinel per worker
await queue.put(STOP)
await queue.join() # until task_done() x N
return sink, errorsThe await queue.join() at the end is the key line: join() blocks until task_done() has been called as many times as items were put() — i.e. until every item has been fully processed. The sentinels queued after all items make each worker exit once the real work is drained. (Each sentinel's task_done() in the worker's finally is harmless: join() only waits for the unfinished count to reach zero, and by the time sentinels are processed, all real items already are.)
3.2 task_done(), join() and telling workers to stop#
Three queue methods carry the whole protocol, and getting them wrong produces the two classic hangs:
| Method | Contract | What breaks if you forget it |
|---|---|---|
queue.task_done() |
Call once per get(), after the item is fully handled |
queue.join() never returns → the run hangs forever at the end |
queue.join() |
Waits until task_done() count == put() count |
Skipping it means you return before work finishes → lost results |
| A stop signal | Sentinel value, or Queue.shutdown() (3.13+) |
Workers block on get() forever → TaskGroup never exits → hang |
Python 3.13 added a cleaner stop mechanism: queue.shutdown() puts the queue into a shutdown mode where put() and get() raise QueueShutDown, and a graceful shutdown() lets consumers drain remaining items before exiting. On 3.13+ the worker's exit check becomes:
# worker for Python 3.13+ — no sentinel needed
async def worker(queue: asyncio.Queue, process, sink: list) -> None:
while True:
try:
item = await queue.get()
except asyncio.QueueShutDown:
return
try:
sink.append(await process(item))
except Exception:
pass # same per-item handling as the sentinel version
finally:
queue.task_done()
# producer side:
for item in items:
await queue.put(item)
queue.shutdown() # no more puts; workers drain, then exit
await queue.join()3.3 Backpressure: bounded queues#
Set maxsize on the queue and the producer's await queue.put(item) starts suspending once the queue is full. The producer can no longer run ahead of the consumers, so memory stays bounded by queue_size, not by len(items). This is the whole point of the pattern for big inputs: you can stream a 10-million-row CSV through a pool with maxsize=1000 and the process never holds more than ~1000 queued items plus limit in-flight ones.
# backpressure_demo.py — watch the queue stay bounded
import asyncio
async def slow(item: int) -> str:
await asyncio.sleep(0.05)
return f"done-{item}"
async def main() -> None:
queue: asyncio.Queue = asyncio.Queue(maxsize=4)
peak = 0
async def producer():
nonlocal peak
for i in range(50):
await queue.put(i) # suspends when full
peak = max(peak, queue.qsize())
await queue.put(None) # sentinel AFTER all items
async def consumer():
while True:
item = await queue.get()
if item is None:
queue.task_done()
return
await slow(item)
queue.task_done()
async with asyncio.TaskGroup() as tg:
tg.create_task(producer())
tg.create_task(consumer())
# leaving the block waits for both tasks: the consumer only returns
# after it has taken the sentinel, so every item has been handled.
print(f"peak queue depth seen by producer: {peak} (maxsize=4)")
asyncio.run(main())peak queue depth seen by producer: 4 (maxsize=4)The producer wanted to dump 50 items instantly; the queue cap of 4 forced it to trickle them out at the consumer's pace. Without maxsize, put_nowait never blocks and all 50 items sit in memory at once — fine at 50, fatal at 10 million.
3.4 Multi-stage pipelines#
Once you have queues, chaining stages is just connecting them: stage A's output queue is stage B's input queue. Each stage is an independent worker pool, so a slow stage automatically slows its upstream neighbour through backpressure — the whole line self-balances:
flowchart LR
subgraph pipe ["Three-stage pipeline"]
S1["fetch stage<br/>(limit=8)"] --> Q1[("queue A<br/>maxsize=32")]
Q1 --> S2["parse stage<br/>(limit=4)"]
S2 --> Q2[("queue B<br/>maxsize=32")]
Q2 --> S3["embed stage<br/>(limit=2)"]
S3 --> OUT[("results")]
endThe mental model: each → in the diagram is an asyncio.Queue; each box is a TaskGroup of workers; maxsize on each queue is the buffer between stages. When the embed stage is slowest, its input queue fills, the parse workers block on put, their input queue fills, and fetch slows down — backpressure propagates upstream automatically, and the fetch stage never races ahead allocating memory. Wiring three stages with correct sentinel counts (one per worker, forwarded stage by stage) is fiddly, which is why Part 10 ships run_pipeline as tested library code instead of asking you to hand-roll it.
3.5 Progress reporting#
Long jobs need a heartbeat: "37,412 of 50,000 done, 3 errors". A shared counter incremented from the consumer side is the cheap mechanism:
# progress.py — report every K completions without slowing the workers
class Progress:
def __init__(self, total: int, every: int = 1000):
self.total = total
self.every = every
self.done = 0
self.errors = 0
def tick(self, ok: bool) -> None:
self.done += 1
self.errors += 0 if ok else 1
if self.done % self.every == 0 or self.done == self.total:
print(f"{self.done}/{self.total} "
f"({self.done / self.total:.0%}), errors={self.errors}")
# inside the worker, after each item:
# progress.tick(ok=(result is not Err))Incrementing self.done from 20 asyncio workers is safe because tick contains no await — it runs atomically on the event loop. From threads the same code needs a threading.Lock (8.2). For a live progress bar rather than log lines, tqdm has an asyncio mode — but the counter pattern adds zero dependencies and is what the deliverable uses. The rule: report progress on the consumer side, once per completed item, not once per task.
3.6 Graceful shutdown#
A production job will be killed: Ctrl-C, a deploy, a SIGTERM from the orchestrator. Graceful shutdown means: stop accepting new work, let in-flight items finish (or cancel them deliberately), flush results, exit cleanly. In asyncio the pieces are:
# shutdown_demo.py — SIGINT stops intake, drains, exits
import asyncio
import signal
async def worker(queue: asyncio.Queue, sink: list) -> None:
while True:
item = await queue.get()
try:
if item is None:
return
await asyncio.sleep(0.05) # stands in for work
sink.append(item)
finally:
queue.task_done()
async def feed(queue: asyncio.Queue, stop: asyncio.Event, n_workers: int) -> None:
i = 0
while not stop.is_set():
await queue.put(i)
i += 1
await asyncio.sleep(0.01)
for _ in range(n_workers): # one sentinel per worker
await queue.put(None)
async def main() -> None:
queue: asyncio.Queue = asyncio.Queue()
sink: list = []
stop = asyncio.Event()
n_workers = 3
loop = asyncio.get_running_loop()
for sig in (signal.SIGINT, signal.SIGTERM):
loop.add_signal_handler(sig, stop.set) # Unix only; see note below
async with asyncio.TaskGroup() as tg:
for _ in range(n_workers):
tg.create_task(worker(queue, sink))
tg.create_task(feed(queue, stop, n_workers))
# no queue.join() here: the queue is empty when this block starts, so
# join() would return at once. Leaving the block waits for the feeder
# and for every worker, and a worker only exits after taking a sentinel.
print(f"processed {len(sink)} items before shutdown")
asyncio.run(main())Run it and press Ctrl-C after a second or two — the stop event ends the feed, one sentinel per worker lets them drain and exit, the TaskGroup waits until the last worker has returned, and the script prints the count instead of hanging. (Output is machine-dependent on when you interrupt, so treat the number as illustrative; the mechanism is the lesson.)
Three rules for graceful shutdown:
- Catch
KeyboardInterrupt/CancelledErrorat the top level, not inside workers. Workers should finish theirfinallyblocks; the orchestrator decides to stop feeding. CancelledErroris not anException.except Exceptiondoes not catch it (Python 3.8+), which is deliberate — your per-item error handler won't swallow cancellations. Butfinallyblocks still run, sotask_done()and cleanup are safe.- Windows has no
add_signal_handler. Usesignal.signal(signal.SIGINT, handler)there, or better: drive shutdown from anasyncio.Eventthat any source can set — Ctrl-C handler, HTTP endpoint, watchdog — so the mechanism is platform-independent.asyncio.Runner(3.11+) and frameworks like FastAPI/uvicorn handle most of this for you; you mostly need the pattern.
Part 4: Rate limiting#
A semaphore bounds how many calls are in flight. It says nothing about how fast new calls start. A service can allow only 60 requests per minute — with a 4-second latency, 60/minute means roughly 4 in flight on average, but a burst of 60 at once is still 60 requests started in one second, and providers count starts, not completions. Rate limiting is the second dial: it spaces out call starts so you stay under requests-per-minute (RPM) and tokens-per-minute (TPM) budgets.
4.1 Concurrency is not rate#
| Dial | Limits | Mechanism | Failure it prevents |
|---|---|---|---|
| Concurrency | Simultaneous in-flight calls | Semaphore, worker count |
Connection exhaustion, memory, provider concurrency caps |
| Rate | Calls started per unit time | Token bucket, sliding window | 429s, quota burn, thundering herd |
You almost always need both: the semaphore keeps C calls in flight; the limiter ensures those C slots are refilled no faster than the provider allows. 03.9 calls this "two limits, two tools" and uses exactly this pairing against real LLM APIs; 03.8 builds a token bucket for the same purpose. Here is the algorithm from scratch.
4.2 The token bucket, from scratch#
The token bucket is the standard rate limiter. Imagine a bucket that holds at most capacity tokens and refills continuously at rate tokens per second. Every call takes one token; if the bucket is empty, the call waits until enough tokens accumulate. It allows bursts up to capacity but caps the long-run rate at rate.
# token_bucket.py — deterministic token-bucket simulation (plain math)
def token_bucket_stamps(rate: float, capacity: float, n: int) -> list[float]:
"""Simulate n acquires; return the fake-time each call may start.
tokens refill continuously at `rate`/sec up to `capacity`; each call
spends 1 token and waits when the bucket is empty.
"""
tokens = capacity
now = 0.0
stamps = []
for _ in range(n):
if tokens < 1.0: # empty: wait for one token
wait = (1.0 - tokens) / rate
now += wait
tokens = min(capacity, tokens + wait * rate)
tokens -= 1.0
stamps.append(round(now, 2))
return stamps
print(token_bucket_stamps(rate=10.0, capacity=10.0, n=25))[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5]Read it: the first 10 calls start at t=0 (the bucket's initial burst capacity), then each subsequent call waits ~0.1 s for one token to refill. Twenty-five calls at 10/second finish starting at t=1.5 — the arithmetic checks out: 25 tokens at 10/s = 2.5 s of refill, minus the 10 pre-filled = 1.5 s of waiting.
For the deliverable, RateLimiter in aitoolkit/concurrency.py is this same algorithm with time.monotonic and asyncio.sleep as injectable dependencies, so tests can use a FakeClock (01B.8) and run instantly.
4.3 The sliding window#
The token bucket smooths starts but doesn't track when each call happened. A sliding window limiter does: it keeps a timestamp of the last N call starts and only allows a new call if the oldest of those N is more than window seconds ago. It's stricter — it enforces "no more than N starts in any rolling window" rather than an average rate — at the cost of storing N timestamps.
# sliding_window.py — deterministic sliding-window simulation (plain math)
def sliding_window_stamps(max_calls: int, window: float, n: int) -> list[float]:
"""Simulate n call starts under 'at most max_calls in any `window`."""
calls: list[float] = [] # timestamps inside the window
now = 0.0
stamps = []
for _ in range(n):
calls = [t for t in calls if t > now - window] # age out old ones
if len(calls) >= max_calls:
now += window - (now - calls[0]) # wait for oldest to age out
calls = [t for t in calls if t > now - window]
calls.append(now)
stamps.append(round(now, 2))
return stamps
print(sliding_window_stamps(max_calls=3, window=1.0, n=8))[0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0]Three calls start instantly, the next three wait until t=1.0 (when the first batch ages out of the 1-second window), and the last two at t=2.0. This is the "fixed window done right" — a naive fixed-window limiter (reset every second) lets 6 calls through at t=0.9 and t=1.1, a burst the sliding window prevents.
4.4 When the provider pushes back: Retry-After and adaptive limits#
Your limiter is a guess about the provider's budget. The provider knows the real number and tells you in two ways: 429 responses with a Retry-After header, and x-ratelimit-* response headers reporting remaining quota and reset time (03.8 decodes them). A production limiter should adapt: on a 429, back off and lower the effective rate; on healthy responses with high remaining quota, cautiously raise it. That is 03.9's "429 adaptation" and 11C.3's shared rate limiter at scale. This lesson teaches the static mechanism; the adaptive layer is a preview of those lessons and of 01B.9.
Part 5: Batching#
Deep-dive
Batching means accumulating several items and processing them together in one call, rather than one call per item. It is the third dial after concurrency and rate: fewer, bigger calls. 06.2 calls it "the first optimisation" for embeddings because providers charge and rate-limit per request, and an embeddings endpoint accepts an array of texts in one call. This lesson is about the accumulator pattern — how to gather items into batches — not about whether batching helps a given API (that's the provider's business).
5.1 What batching buys#
| Benefit | Why |
|---|---|
| Fewer requests | RPM/TPM budgets count requests; 10 items in 1 call costs 1 request, not 10 |
| Shared overhead | TLS handshake, auth, prompt prefix amortised over N items |
| Sometimes required | Some APIs only accept arrays (embeddings, bulk endpoints) |
The cost: one batch call is slower than one item call (the provider processes N items), a failure can take down N items at once, and ordering/partial-failure handling is more complex. Batching trades per-item latency for throughput and cost.
5.2 Count-based batching#
The simplest accumulator: collect items until you have N, then flush.
# batcher_count.py — flush every N items
import asyncio
class CountBatcher:
"""Accumulate items; flush a batch every `size` items."""
def __init__(self, size: int, flush):
self.size = size
self.flush = flush # async callable taking a list
self.buf: list = []
async def add(self, item) -> None:
self.buf.append(item)
if len(self.buf) >= self.size:
batch, self.buf = self.buf, []
await self.flush(batch)
async def close(self) -> None:
if self.buf:
batch, self.buf = self.buf, []
await self.flush(batch)
async def main() -> None:
sent = []
async def flush(batch): sent.append(list(batch))
b = CountBatcher(3, flush)
for i in range(8):
await b.add(i)
await b.close() # flush the remainder (2 items)
print(sent)
asyncio.run(main())[[0, 1, 2], [3, 4, 5], [6, 7]]close() matters: without it the last partial batch (items 6, 7) is silently dropped. Every accumulator needs an explicit flush-at-end.
5.3 Time-window batching#
Count-based batching has a tail problem: the last few items of a stream may sit in the buffer indefinitely waiting for N more that never come. A time-window batcher flushes whatever it has every T seconds, so latency is bounded:
# batcher_time.py — flush every T seconds OR every N items, whichever first
import asyncio
from collections.abc import Awaitable, Callable
class WindowBatcher:
"""Flush when `size` items accumulate OR `window` seconds elapse."""
def __init__(self, size: int, window: float, flush,
*, sleep: Callable[[float], Awaitable[None]] = asyncio.sleep):
self.size = size
self.window = window
self.flush = flush
self.buf: list = []
self._sleep = sleep # injectable, like RateLimiter's
self._timer: asyncio.Task | None = None
async def add(self, item) -> None:
self.buf.append(item)
if len(self.buf) >= self.size:
await self._flush_now()
elif self._timer is None:
self._timer = asyncio.create_task(self._flush_later())
async def _flush_later(self) -> None:
await self._sleep(self.window)
self._timer = None
if self.buf:
await self._flush_now()
async def _flush_now(self) -> None:
if self._timer is not None:
self._timer.cancel()
self._timer = None
batch, self.buf = self.buf, []
if batch:
await self.flush(batch)
async def close(self) -> None:
if self._timer is not None:
self._timer.cancel()
await self._flush_now()This is the "N items or T seconds, whichever comes first" pattern. The timer resets on each flush; close() cancels a pending timer and flushes the remainder. sleep is injectable for the same reason RateLimiter's is (10.1): a fake sleep that advances a virtual clock — the FakeClock pattern from 01B.8 — lets a test make the window "elapse" instantly. Note the constructor touches no event-loop API, so building the batcher is safe anywhere; it's add() that needs a running loop (asyncio.create_task does). Resist the urge to grab a clock with asyncio.get_event_loop() in __init__ — outside a running loop that raises RuntimeError on Python 3.14 and warns on earlier versions.
5.4 Partial failure inside a batch#
A batch call that fails affects N items. The recovery options:
| Strategy | When |
|---|---|
| Retry the whole batch | Transient error, batch is idempotent |
| Split and retry halves | One poison item is killing the batch (bisect) |
| Fall back to per-item calls | Batch endpoint flaky but single calls work |
| Record all N as failed | Cheap, but loses N-1 good items |
The poison-item bisect is worth knowing: if a batch of 100 fails and you suspect one bad item, split into two batches of 50, retry each, and recurse on the failing half — O(log N) extra calls to isolate the culprit instead of N per-item retries. 06.2 covers this for embeddings specifically.
5.5 Batching vs provider Batch APIs#
Don't confuse client-side batching (this section) with a provider's Batch API — a job interface where you submit thousands of complete requests, the provider runs them at its leisure (often ~half price, up to 24 h), and you collect results later. Client-side batching packs items into one API call; a Batch API submits many calls as a deferred job. They solve different problems and stack: you can batch items into calls and submit those calls through a Batch API. 03.9 Part 6 owns the Batch API side completely — read it before designing a bulk LLM job.
Part 6: Little's law and choosing a limit#
6.1 Little's law in plain words#
Little's law is the most useful piece of queueing theory an engineer will ever use, and it is one sentence: the number of things in a system equals the rate at which they arrive times how long each one stays. In our notation:
concurrency (in flight) = throughput (calls/sec) × latency (sec/call)Or rearranged: throughput = concurrency / latency. It holds for any stable system — a call centre, a web server, an LLM pipeline — regardless of how complicated the internals are. The intuition: if calls take 4 seconds each and you want 2.5 calls finishing per second, you must have 2.5 × 4 = 10 calls in flight at any moment. Fewer and you can't sustain the throughput; more and you're just queueing.
6.2 A worked calculation#
A worked example: a provider allows 600 requests per minute and each call takes 4 seconds. How many calls must be in flight to sustain the full rate?
rate = 600 req/min = 10 req/s
latency = 4 s/call
in flight = 10 req/s × 4 s = 40 callsSo C ≈ 40 is the minimum concurrency to use the whole quota. Set C = 10 and you only reach 150 req/min (10/4s) — you're leaving 75% of the budget unused. Set C = 400 and you're not 10× faster; you're 400 calls deep in the provider's queue, each now taking longer than 4 s, and you may trip a concurrency cap or start getting 429s. The sweet spot is C slightly above the Little's-law minimum — enough to keep the pipe full despite jitter, not so much that you queue.
A second constraint often binds first: the provider's concurrency cap (max simultaneous requests) may be lower than what RPM × latency implies. Check both, take the smaller.
6.3 Choosing the limit: a decision table#
| Situation | Starting C |
Why |
|---|---|---|
| Unknown latency, unknown limits | 5–10 | Small enough to be safe, big enough to see behaviour |
| Known RPM limit, measured latency | ceil(RPM/60 × latency_s) × 1.2 |
Little's-law minimum plus 20% headroom for jitter |
| Provider documents a concurrency cap | The cap (or cap − small margin) | Never exceed the hard limit |
| Latency varies wildly (1–30 s) | Lower C, rely on rate limiter |
A few slow calls can occupy all slots; rate limiter paces starts |
| Interactive/user-facing | Low C (5–20) |
You want each call fast, not maximum throughput |
| Overnight batch job | Higher C, bounded by rate limit |
Maximise throughput within quota |
The × 1.2 headroom matters because latency is never constant: if one call takes 8 s instead of 4 s, your in-flight count doubles for the same throughput, and a C set exactly at the minimum will under-utilise during slow patches. Measure the real latency distribution — the median (p50) and 95th-percentile (p95) latencies — before tuning — 11A.2 covers the metrics side.
6.4 Measuring: is more concurrency helping?#
The only honest way to know if C is right is to measure. Track three numbers over a representative run:
| Metric | Healthy sign | Bad sign |
|---|---|---|
| Throughput (items/sec) | Rises with C then plateaus |
Plateaus early → limit too low or provider throttling |
| Latency p95 | Roughly constant as C rises |
Rises steeply → provider queueing; C too high |
| Error rate / 429s | Near zero | Climbs → over a rate or concurrency limit |
Plot throughput vs C: it rises linearly (Little's law region), then bends over as queueing dominates, then falls if the provider starts rejecting. The knee of that curve is your C. Log in_flight, queue_depth, rate_limited_count per run — 03.9 does exactly this tuning against real providers, and 11C.3 turns it into autoscaling signals.
Part 7: Coordination primitives#
Deep-dive
Queues and semaphores cover most needs, but three more asyncio primitives solve specific coordination problems. You will meet all three in production code; know what each is for.
7.1 Single-flight: deduplicating in-flight work#
Single-flight (also called request coalescing) solves the thundering-herd-at-the-source problem: when N callers ask for the same expensive thing at the same time — the same cache key, the same "compute today's report", the same embedding of a popular document — run the work once and share the result with all N callers, instead of N identical calls stampeding the provider. 11B.3 calls this a cache-stampede defence; here is the stdlib mechanism:
# singleflight.py — collapse concurrent identical calls into one
import asyncio
class SingleFlight:
"""At most one in-flight call per key; others await the same result."""
def __init__(self):
self._inflight: dict = {} # key -> asyncio.Task
async def do(self, key, factory):
"""factory() is an async callable producing the value."""
task = self._inflight.get(key)
if task is None:
task = asyncio.ensure_future(factory())
self._inflight[key] = task
task.add_done_callback(lambda t: self._inflight.pop(key, None))
# shield: if THIS caller is cancelled (say its own timeout fires),
# the shared task must keep running for the other callers.
return await asyncio.shield(task)
async def expensive(key: str) -> str:
await asyncio.sleep(0.05)
return f"computed-{key}"
async def main() -> None:
sf = SingleFlight()
# 10 concurrent callers for the same key -> ONE underlying call
out = await asyncio.gather(*(sf.do("report", lambda: expensive("report"))
for _ in range(10)))
print(len(set(out)), "unique result(s); all callers shared one call")
# a different key runs separately
print(await sf.do("other", lambda: expensive("other")))
asyncio.run(main())1 unique result(s); all callers shared one call
computed-otherThe trick is storing the Task, not the result: the first caller creates the task and registers it; concurrent callers find the same task and await it — await on an already-running task is legal and all awaiters get the same result (or the same exception). The add_done_callback removes the entry when the task finishes, so the next wave of callers starts a fresh call (this dedups in-flight work, not results — for caching the result, that's 11B.3's job). Two failure modes to watch. If factory() raises, every awaiter gets the exception — usually what you want, but one poison key fails all its waiters together. And cancellation: awaiting a task directly would pass a caller's cancellation (for example its own asyncio.timeout) down into the shared task and cancel the work for everyone, which is why do() awaits asyncio.shield(task) — one impatient caller gives up its wait without killing the call the other nine are waiting on. (The trade-off: if every caller leaves, the task still runs to completion, so give factory() its own timeout.)
7.2 asyncio.Lock#
A lock allows only one task inside a protected section at a time — the async equivalent of threading.Lock. Use it for read-modify-write on shared state that must be atomic:
# lock_demo.py — a counter that must not lose updates
import asyncio
async def main() -> None:
locked = 0
unlocked = 0
lock = asyncio.Lock()
async def bump_locked(n: int) -> None:
nonlocal locked
for _ in range(n):
# the yield sits INSIDE the critical section: while this
# task sleeps, the others queue on `lock` instead of
# interleaving between the read and the write.
async with lock:
old = locked
await asyncio.sleep(0)
locked = old + 1
async def bump_unlocked(n: int) -> None:
nonlocal unlocked
for _ in range(n):
# same read-modify-write with no lock: the other tasks run
# between the read and the write, and their increments
# are silently lost.
old = unlocked
await asyncio.sleep(0)
unlocked = old + 1
await asyncio.gather(
*(bump_locked(1000) for _ in range(4)),
*(bump_unlocked(1000) for _ in range(4)),
)
print("locked: ", locked) # 4000 — every increment lands
print("unlocked:", unlocked) # ~1000 — three in four are lost
asyncio.run(main())locked: 4000
unlocked: 1000A lock is not a queue and not a semaphore: it has no fairness ordering guarantees worth relying on, it can't limit how many run (only that one does), and holding it across a slow await (like a network call) serialises your whole program — the cardinal sin of async. Keep the protected section tiny: update the counter, release, then do slow work.
7.3 asyncio.Condition#
A condition variable is a lock plus a "wait until a predicate is true" mechanism — the async threading.Condition. Use it when workers must wait for a state ("buffer has space", "item available") rather than for a slot (semaphore) or a turn (lock):
# condition_demo.py — consumers wait for producers to fill a buffer
import asyncio
async def main() -> None:
cond = asyncio.Condition()
buffer: list = []
async def consumer() -> None:
async with cond:
while not buffer: # wait while empty
await cond.wait()
item = buffer.pop(0)
print("consumed", item)
async def producer() -> None:
await asyncio.sleep(0.01)
async with cond:
buffer.append("data")
cond.notify() # wake ONE waiter
async with asyncio.TaskGroup() as tg:
c = tg.create_task(consumer())
tg.create_task(producer())
# consumer waited on cond.wait() until producer appended + notified
asyncio.run(main())consumed datacond.wait() releases the lock and suspends until notify()/notify_all(); notify_all() wakes every waiter (they re-check the predicate in a loop — always while, never if, because of spurious wakeups and because one notify may not satisfy everyone). You will meet Condition-style wait-and-predicate logic inside queue.Queue's own internals — the queue module coordinates producers and consumers with threading.Conditions — and in bounded-buffer implementations you write yourself. asyncio.Queue solves the same problem differently, with deques of futures instead of conditions. Most app code uses Queue/Semaphore/Event instead because they're harder to get wrong.
7.4 asyncio.Event#
An event is a one-bit flag with async waiting: set() wakes all current and future waiters; clear() resets it; wait() suspends until set. It is the shutdown signal from 3.6, a "cache warmed up" flag, a "leader elected" signal — anywhere you need "tell all waiters something changed". Unlike Condition it carries no predicate and no lock; unlike Semaphore it is not consumed (every waiter sees it). You used it as stop in the shutdown demo.
Part 8: Threads and processes#
Deep-dive
asyncio is not always the answer. Three other concurrency tools exist, and knowing when not to use async is half the skill.
8.1 The GIL in plain words#
The GIL (Global Interpreter Lock) is a mutex inside CPython that allows only one thread to execute Python bytecode at a time, even on a 32-core machine. It exists because CPython's memory management isn't thread-safe without it. Consequences:
| Workload | Do threads help? | Why |
|---|---|---|
I/O-bound (network, disk, sleep) |
✅ Yes | A thread blocked on I/O releases the GIL, so other threads run while it waits |
| CPU-bound (maths, parsing, compression) | ❌ No | Each thread holds the GIL while computing; they timeshare, not parallelise — often slower than one thread due to context-switch overhead |
This is why asyncio (one thread, cooperative) and threads (many threads, GIL-switched) both work for I/O: neither needs true parallelism, they just need to overlap the waiting. For CPU-bound work you need processes (each with its own interpreter and GIL) or a C extension that releases the GIL (NumPy does, for large array ops — that's why NumPy "threads" scale).
8.2 threading and locks#
For I/O-bound work that can't use async — a legacy sync SDK, a library with only blocking calls — threading gives you OS-level concurrency. Each thread is a real OS thread; the GIL switches between them at bytecode boundaries and releases it during blocking calls.
# threads_demo.py — threads overlap I/O waits
import threading
import time
def slow_io(name: str, seconds: float) -> None:
time.sleep(seconds) # releases the GIL while sleeping
print(f"{name} done")
def main() -> None:
threads = [threading.Thread(target=slow_io, args=(f"t{i}", 0.2))
for i in range(4)]
t0 = time.perf_counter()
for t in threads: t.start()
for t in threads: t.join()
print(f"4 x 0.2s I/O calls finished in {time.perf_counter() - t0:.1f}s (sequential would be 0.8s)")
if __name__ == "__main__":
main()t0 done
t1 done
t2 done
t3 done
4 x 0.2s I/O calls finished in 0.2s (sequential would be 0.8s)Shared state needs threading.Lock — and here's the deterministic proof that races are real, using Events to force the interleaving:
# race_demo.py — a lost update, forced deterministically
import threading
counter = 0
a_read = threading.Event()
b_read = threading.Event()
def worker_a():
global counter
old = counter # A reads 0
a_read.set() # tell B to go
b_read.wait() # wait until B has read too
counter = old + 1 # A writes 1 — but B already read 0!
def worker_b():
global counter
a_read.wait() # wait until A has read
old = counter # B reads 0 (same value!)
b_read.set()
counter = old + 1 # B writes 1 — A's update is LOST
ta = threading.Thread(target=worker_a)
tb = threading.Thread(target=worker_b)
ta.start(); tb.start(); ta.join(); tb.join()
print("counter:", counter) # 1, not 2 — one increment vanishedcounter: 1Two threads each read 0, each wrote 1 — one update was silently lost. This is why counter += 1 under threads needs a threading.Lock, and why the asyncio version in 7.2 needs asyncio.Lock. The hazard is identical; only the coordination primitive differs.
The other half of threaded coordination is the hand-off itself. When workers are threads rather than coroutines, the counterpart to asyncio.Queue is queue.Queue (or its leaner sibling queue.SimpleQueue): a thread-safe FIFO with blocking put()/get(), maxsize for the same backpressure, and task_done()/join() for the same completion protocol. Internally it coordinates with threading.Conditions — the primitive from 7.3, in its thread-safe form. If your fan-out runs on ThreadPoolExecutor workers or raw threading.Threads, queue.Queue is what you reach for instead of asyncio.Queue, which requires a running event loop and is not thread-safe.
8.3 concurrent.futures executors#
concurrent.futures is the higher-level thread/process API: submit callables, get futures back, collect results — the thread-level gather.
# executors_demo.py — ThreadPoolExecutor and ProcessPoolExecutor
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import time
def io_task(n: int) -> int:
time.sleep(0.05) # I/O-ish: releases the GIL
return n * n
def cpu_task(n: int) -> int:
total = 0
for i in range(n * 300_000):
total += i * i # CPU-bound: holds the GIL
return total
def main() -> None:
# threads: good for the I/O-ish task
with ThreadPoolExecutor(max_workers=4) as ex:
print("threads:", sorted(ex.map(io_task, range(6))))
# processes: each has its own GIL, real parallelism for CPU work
with ProcessPoolExecutor(max_workers=4) as ex:
print("processes:", sorted(ex.map(cpu_task, range(1, 4))))
if __name__ == "__main__":
main()threads: [0, 1, 4, 9, 16, 25]
processes: [8999955000050000, 71999820000100000, 242999595000150000]Key API points:
executor.map(fn, items)returns results in input order (likegather), lazily.executor.submit(fn, *args)returns aFuture;future.result()blocks for it,concurrent.futures.as_completed(futs)yields futures as they finish (out of order — pair with the index if you need order).- Exceptions propagate when you call
.result()— a failed task doesn't kill the pool. ProcessPoolExecutorrequires the function to be picklable (top-level, importable) and the script to guard withif __name__ == "__main__":— on macOS/Windows the default start method re-imports your__main__module in each child, and without the guard you get infinite process spawning. This is the #1 multiprocessing bug.
8.4 When threads are the right tool#
Threads are correct when the bottleneck is a blocking call you cannot make async, and rewriting isn't worth it:
| Situation | Tool | Why |
|---|---|---|
| Async-native library (httpx, most SDKs) | asyncio |
One thread, no GIL contention, cheapest |
| Sync-only SDK / legacy lib | ThreadPoolExecutor or asyncio.to_thread |
Overlap the blocking waits without rewriting |
| CPU-bound pure Python | ProcessPoolExecutor |
True parallelism across cores |
| CPU-bound with NumPy/C ext | Threads often fine | C extensions release the GIL for big ops |
| One-off script, few calls | Sequential | Concurrency has a cost; don't pay it for nothing |
The decision rule: I/O-bound → async if you can, threads if you must; CPU-bound → processes (or a faster library). 03.9 applies this to SDKs that only ship sync clients.
8.5 asyncio.to_thread vs executors#
asyncio.to_thread(fn, *args) (3.9+) runs a sync function in the default thread pool and awaits it — the bridge for "one blocking call inside async code". It's the right tool for an occasional blocking call (a sync SDK method, a file read, time.sleep in a pinch). For many blocking calls, loop.run_in_executor(executor, fn, ...) with your own ThreadPoolExecutor gives you control over pool size — to_thread uses the shared default executor, whose size you can't tune per call (loop.set_default_executor() can swap in your own pool process-wide, but a dedicated executor is the usual answer).
# to_thread_demo.py — run a blocking call from async code
import asyncio
import time
def blocking_io(seconds: float) -> str:
time.sleep(seconds) # would freeze the loop if called directly
return "done"
async def main() -> None:
# WRONG inside async: time.sleep(1) blocks the whole loop
# RIGHT: offload to a thread
t0 = time.perf_counter()
r = await asyncio.to_thread(blocking_io, 0.2)
print(r, f"in {time.perf_counter() - t0:.1f}s — loop stayed responsive")
asyncio.run(main())done in 0.2s — loop stayed responsive8.6 CPU-bound work and multiprocessing#
For genuinely CPU-bound Python (no NumPy to release the GIL), ProcessPoolExecutor is the answer — each process is a full interpreter with its own GIL, so N workers use N cores. The costs: pickling inputs/outputs across process boundaries (data must be serializable), process startup overhead (~50–100 ms each on spawn), no shared memory (use multiprocessing.Manager, shared_memory, or just return results), and the __main__ guard. For AI work this matters for local embedding models, tokenisation at scale, and data preprocessing — 06.2 discusses the GPU analogue.
8.7 The decision table#
| Workload | Best tool | Avoid |
|---|---|---|
| Many concurrent network/API calls | asyncio + semaphore/queue |
Threads (GIL fine but asyncio is cheaper per connection) |
| Occasional blocking call in async code | asyncio.to_thread |
time.sleep/sync call inline (blocks loop) |
| Many blocking calls, sync-only lib | ThreadPoolExecutor |
Rewriting the lib in async for marginal gain |
| CPU-bound pure Python | ProcessPoolExecutor |
Threads (GIL → no speedup) |
| CPU-bound NumPy/pandas | Threads or just NumPy | Processes unless data is huge (pickle cost) |
| Handing work between thread workers | queue.Queue / queue.SimpleQueue |
asyncio.Queue (needs a running loop) or a shared list + your own locking |
| Need shared mutable state | Whichever + a lock | Assuming the GIL makes += atomic (it doesn't) |
Part 9: Sync wrappers and library choices#
Reference
9.1 Calling async pipelines from synchronous code#
Not every caller is async. A CLI main(), a Celery task, a Jupyter cell top-level — these are synchronous, but your pipeline is async def. The bridge is asyncio.run():
# cli_entry.py — run an async pipeline from a sync CLI
import asyncio
import sys
async def run_pipeline_async(items: list[str]) -> list[str]:
# ... your bounded fan-out / worker pool from earlier parts ...
return [f"processed:{i}" for i in items]
def main() -> None:
items = sys.argv[1:] or ["a", "b", "c"]
results = asyncio.run(run_pipeline_async(items)) # sync -> async bridge
for r in results:
print(r)
if __name__ == "__main__":
main()Rules:
asyncio.run()creates a fresh event loop, runs the coroutine, closes the loop. Call it once per "batch of work", not once per item — the loop startup is cheap but not free, and you can't nest it.- Never call
asyncio.run()inside a running loop (insideasync def, inside Jupyter's top-levelawaitcell, inside FastAPI). Useawaitdirectly there, orasyncio.run_coroutine_threadsafefrom a different thread. - One
asyncio.run()per process is the clean pattern for scripts; for repeated calls in one process (a worker consuming many jobs), keep one loop alive and submit coroutines to it. - For a library that must offer both sync and async APIs (like
httpxdoes), the usual shape is a sync wrapper that internally doesasyncio.run(self._async_op(...))— see 01B.5 for howhttpx.ClientvsAsyncClientis built.
9.2 The library landscape#
You can write every pattern in this lesson from the stdlib — that is deliberate, so you understand what the libraries do. When you don't want to maintain it yourself:
| Library | What it gives you | Version (Nov 2026) | Notes |
|---|---|---|---|
anyio |
Task groups, semaphores, cancel scopes that run on asyncio or Trio | 4.16.0 | The backend-agnostic layer; FastAPI/Starlette/httpx use it. Learn it if you want portability |
aiolimiter |
Leaky-bucket rate limiter as an async context manager | 1.3.0 | async with limiter: — drop-in for the Part 4 token bucket |
asyncio-throttle |
Simple Throttler(rate_limit=N, period=S) |
1.0.2 | Dormant since 2021; works but unmaintained — prefer aiolimiter for new code |
trio |
An alternative async runtime (nurseries, checkpoints) | — | Different philosophy (structured concurrency native, no asyncio.run); awareness only |
tenacity |
Retry decorators, async support (@retry on async def, AsyncRetrying) |
9.1.4 | 01B.9 owns it; here: it wraps your bounded call, not the other way round |
The composition rule for all of them: rate limiter wraps the call, semaphore bounds in-flight, retry wraps the whole attempt, timeout wraps each attempt. Order matters — a retry inside the rate limiter can multiply your effective rate (each retry is a new call start); a timeout outside the retry can cancel mid-backoff. 01B.9 draws the full composition diagram.
9.3 tenacity async support (preview)#
tenacity 9.1.4's @retry decorator works unchanged on async def functions — it detects the coroutine and awaits properly, and AsyncRetrying is the explicit form. You will use it in 01B.9 to wrap each item inside your bounded fan-out: the semaphore bounds concurrency, the limiter paces starts, and tenacity retries the transient failures — three orthogonal layers, each doing one job. Do not put the retry outside the bounded gather (you'd retry the whole batch) or the limiter inside the retry (each retry re-acquires, which is correct but easy to get wrong).
Part 10: The aitoolkit deliverable and the LLM preview#
10.1 aitoolkit/concurrency.py#
This is the module's running deliverable — the four names every later lesson uses: Result/Ok/Err, bounded_gather, RateLimiter, and run_pipeline. It consolidates Parts 2–5 into tested library code (the tests live in 01B.8's listing). Keep the file in your aitoolkit project from 01B.1.
# src/aitoolkit/concurrency.py — bounded concurrency toolkit (stdlib only)
"""Concurrency patterns for I/O-bound work: bounded fan-out, rate limiting,
worker-pool pipelines, and a Result type for partial-failure collection.
Everything here is provider-neutral. Lesson 01B.4 teaches the patterns;
lesson 03.9 applies them to real LLM calls.
"""
from __future__ import annotations
import asyncio
import time
from collections.abc import Awaitable, Callable, Iterable
from dataclasses import dataclass
from typing import Generic, TypeVar, Union
T = TypeVar("T")
E = TypeVar("E", bound=BaseException)
# ---------------------------------------------------------------------------
# Result type: Ok(value) | Err(error) — partial-failure collection
# ---------------------------------------------------------------------------
@dataclass(frozen=True)
class Ok(Generic[T]):
value: T
@dataclass(frozen=True)
class Err(Generic[E]):
error: E
Result = Union[Ok[T], Err[E]]
# ---------------------------------------------------------------------------
# bounded_gather: gather with a concurrency limit, order preserved
# ---------------------------------------------------------------------------
async def bounded_gather(
coros: Iterable[Awaitable[T]],
limit: int,
) -> list[T]:
"""Run awaitables with at most `limit` in flight.
Results come back in input order (like asyncio.gather). The first
exception propagates immediately; remaining coroutines are NOT
cancelled — for continue-on-error semantics use run_pipeline or wrap
each coro to return a Result.
"""
sem = asyncio.Semaphore(limit)
async def guarded(coro: Awaitable[T]) -> T:
async with sem:
return await coro
return list(await asyncio.gather(*(guarded(c) for c in coros)))
# ---------------------------------------------------------------------------
# RateLimiter: token bucket, injectable clock/sleep for deterministic tests
# ---------------------------------------------------------------------------
class RateLimiter:
"""Token-bucket rate limiter: `rate` calls/sec sustained, `burst` max
instantaneous. Async-safe: concurrent acquires queue fairly enough for
I/O work.
`sleep` and `now` are injectable so tests can use a fake clock and run
instantly; production uses asyncio.sleep / time.monotonic.
"""
def __init__(
self,
rate: float,
burst: float | None = None,
*,
sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
now: Callable[[], float] = time.monotonic,
) -> None:
if rate <= 0:
raise ValueError("rate must be positive")
self.rate = rate
self.capacity = float(burst if burst is not None else rate)
self._tokens = self.capacity
self._last = now()
self._sleep = sleep
self._now = now
self._lock = asyncio.Lock()
async def acquire(self, tokens: float = 1.0) -> None:
if tokens > self.capacity:
# the bucket can never hold this many tokens: waiting would loop forever
raise ValueError(f"cannot acquire {tokens} tokens from a bucket of {self.capacity}")
async with self._lock:
while True:
now = self._now()
self._tokens = min(
self.capacity,
self._tokens + (now - self._last) * self.rate,
)
self._last = now
if self._tokens >= tokens:
self._tokens -= tokens
return
deficit = tokens - self._tokens
await self._sleep(deficit / self.rate)
# ---------------------------------------------------------------------------
# run_pipeline: worker pool over asyncio.Queue, ordered Results, graceful stop
# ---------------------------------------------------------------------------
async def run_pipeline(
items: Iterable[T],
process: Callable[[T], Awaitable[object]],
*,
limit: int = 8,
queue_size: int = 0,
on_progress: Callable[[int, int, int], None] | None = None,
) -> list[Result]:
"""Process `items` through `process` with `limit` workers.
Returns a list of Result aligned with input order: Ok(value) or
Err(exception). `queue_size` bounds the buffer (backpressure);
`on_progress(done, total, errors)` is called after each item.
"""
item_list = list(items)
total = len(item_list)
n_workers = max(1, min(limit, total))
queue: asyncio.Queue = asyncio.Queue(maxsize=queue_size)
out: list[Result] = [None] * total # type: ignore[list-item]
stats = {"done": 0, "errors": 0}
STOP = object()
async def worker() -> None:
while True:
payload = await queue.get()
try:
if payload is STOP:
return
index, item = payload
try:
out[index] = Ok(await process(item))
except Exception as exc:
out[index] = Err(exc)
stats["errors"] += 1
stats["done"] += 1
if on_progress is not None:
on_progress(stats["done"], total, stats["errors"])
finally:
queue.task_done()
async with asyncio.TaskGroup() as tg:
for _ in range(n_workers):
tg.create_task(worker())
for i, item in enumerate(item_list):
await queue.put((i, item))
for _ in range(n_workers):
await queue.put(STOP)
await queue.join()
return outDesign notes worth keeping:
run_pipelinenever raises per-item. Every item's outcome is anOkorErr; the only thing that propagates is a bug in the worker itself (for example theon_progresscallback raising):task_done()still runs in thefinally, and theTaskGroupcancels the other workers and raises anExceptionGroup. This is the continue-on-error policy from 2.5 made the default, because data jobs want it.- Order is preserved by carrying
(index, item)through the queue and writing into a preallocatedoutlist — the 2.4 rule. queue_sizeis the backpressure dial from 3.3;0means unbounded (fine for small inputs, dangerous for huge ones).RateLimitertakessleep/nowas parameters so 01B.8 can inject aFakeClockand test timing without real sleeps — the same trick as the Part 4 demos.- For fail-fast semantics, use
bounded_gatherinside aTaskGroup, or wraprun_pipeline'sprocessto re-raise a sentinel you check afterwards.
10.2 The LLM preview: same patterns, fake backend#
Everything above is provider-neutral. Here is the same bounded fan-out aimed at an LLM-shaped call — a FakeLLM that sleeps a fake latency and occasionally raises a fake RateLimitError — so you can see the pattern without a key. This is deliberately tiny, and FakeLLM is a minimal stand-in, not the aitoolkit.backend.ScriptedBackend from 01B.3 (which returns Completion objects and records structured calls) — don't copy it into the project under that name. 03.9 owns async LLM clients, per-provider budgets and batch APIs in full.
# llm_preview.py — bounded fan-out over a fake LLM backend (no key needed)
import asyncio
import random
class RateLimitError(Exception):
pass
class FakeLLM:
"""Fake LLM: canned latency, canned failures. Stands in for an SDK client."""
def __init__(self, latency: float = 0.2, fail_rate: float = 0.0):
self.latency = latency
self.fail_rate = fail_rate
self.calls = 0
async def complete(self, prompt: str) -> str:
self.calls += 1
await asyncio.sleep(self.latency)
if random.random() < self.fail_rate:
raise RateLimitError("429 too many requests")
return f"answer to: {prompt[:30]}"
async def classify_all(backend: FakeLLM, prompts: list[str],
limit: int = 5) -> list:
"""Bounded fan-out: at most `limit` LLM calls in flight."""
sem = asyncio.Semaphore(limit)
async def one(prompt: str):
async with sem:
try:
return await backend.complete(prompt)
except RateLimitError as e:
return f"FAILED: {e}"
return await asyncio.gather(*(one(p) for p in prompts))
async def main() -> None:
random.seed(42)
backend = FakeLLM(latency=0.2, fail_rate=0.2)
prompts = [f"ticket {i}: refund request" for i in range(20)]
results = await classify_all(backend, prompts, limit=5)
ok = sum(1 for r in results if not r.startswith("FAILED"))
print(f"{ok}/{len(results)} succeeded, backend.calls={backend.calls}")
# bounded at 5: ~4 waves x 0.2s ≈ 0.8s total vs 4s sequential
asyncio.run(main())14/20 succeeded, backend.calls=20The count is fully deterministic — random.seed(42) fixes which of the 20 complete() calls "fail", and every call consumes exactly one random.random(), so the result is the same on every machine (only wall-time would vary, and nothing here prints it).
The point: backend.calls is exactly 20 (no duplicates, no retries — retries are 01B.9's job), the semaphore held concurrency at 5, and failures came back as values, not crashes. In production this is where you'd add the RateLimiter from Part 4 inside the semaphore, per-provider budgets from 03.9 §4.7, and retry-with-backoff from 01B.9.
Failure gallery#
The bugs below are the ones that actually reach production. Each is a hang, a silent wrong answer, or an outage — recognise the symptom.
| Symptom | Cause | Fix |
|---|---|---|
| Run finishes items then hangs forever | Worker loop has no stop signal; queue.get() blocks on empty queue |
Sentinel per worker, or Queue.shutdown() (3.13+), or drain with get_nowait (3.2) |
queue.join() never returns though all work done |
task_done() missing on an exit path (error path, sentinel path) |
task_done() in finally, once per get() (3.2) |
| Results returned but last few items missing | Producer finished but batcher/accumulator never flushed | Always close()/flush() the tail (5.2) |
| Process RSS climbs until OOM on a huge input | Unbounded gather (one coroutine per item) or unbounded queue |
Worker pool + maxsize queue (3.1, 3.3) |
| 429s / provider ban after a big run | Concurrency set but rate unlimited — bursts of call starts | Add a RateLimiter inside the semaphore (Part 4) |
| One bad item kills 9,999 good ones | TaskGroup/gather fail-fast on a data job |
Per-item Err collection — run_pipeline's default (2.5) |
RuntimeError: asyncio.run() cannot be called |
asyncio.run inside a running loop (Jupyter, FastAPI, another async def) |
await directly, or run_coroutine_threadsafe from another thread (9.1) |
| Counter/total wrong under concurrency | += on shared state across await/threads without a lock |
asyncio.Lock / threading.Lock (7.2, 8.2) |
ProcessPoolExecutor spawns forever / pickling error |
Missing if __name__ == "__main__": guard, or unpicklable function |
Guard the entry point; top-level importable functions only (8.3) |
| Threads made it slower | CPU-bound work under the GIL | ProcessPoolExecutor or a GIL-releasing library (8.1) |
| 10 identical calls hit the provider for the same key | No in-flight dedup — thundering herd at the source | SingleFlight task-coalescing (7.1) |
| Whole job lost on Ctrl-C/deploy | No graceful shutdown; in-flight work and buffered results discarded | stop event + drain + flush (3.6) |
| Everything stops; CPU idle; no error ever printed | Deadlock: two asyncio.Locks acquired in opposite order, or a lock held across an await that waits on itself |
Acquire locks in one fixed global order; keep critical sections tiny; prefer a queue over hand-rolled locking (7.2, 7.3) |
Task was destroyed but it is pending! warnings; the "finished" run keeps billing the provider |
Detached tasks: create_task results dropped, or gather siblings left running after an exception |
TaskGroup (structured concurrency) or keep task references and cancel explicitly on shutdown (2.2, 3.6) |
| Whole pipeline stalls; progress heartbeat stops; sibling workers freeze too | A blocking call (time.sleep, a sync SDK) inside an async def worker |
await asyncio.to_thread(...) or run_in_executor (8.5) — the single most common async production bug |
QueueShutDown raised inside a worker (3.13+) |
get()/put() after queue.shutdown() |
Catch asyncio.QueueShutDown in the worker loop to exit cleanly (3.2) |
Four of them as the errors actually surface — reconstructed from the stdlib exception types and messages, since the deadlock and the blocking call produce no error at all, which is the point:
Deadlock — no traceback, just a hang. Two tasks each hold one asyncio.Lock and await the other; both park forever inside lock.acquire() while the loop idles. The only output is where the tasks were parked when you finally interrupted them:
Traceback (most recent call last):
...
File "pipeline.py", line 14, in task_a
async with locks["ingest"]: # holds "fetch", wants "ingest"
File ".../asyncio/locks.py", line 110, in acquire
await fut
asyncio.exceptions.CancelledError
...
KeyboardInterruptQueueShutDown — a worker outliving its queue's shutdown (3.13+):
Traceback (most recent call last):
File "worker.py", line 9, in worker
item = await queue.get()
File ".../asyncio/queues.py", line 182, in get
raise QueueShutDown
asyncio.queues.QueueShutDownasyncio.run() nested — the sync/async boundary crossed the wrong way:
Traceback (most recent call last):
File "job.py", line 20, in <module>
asyncio.run(main())
~~~~~~~~~~~^^^^^^^^
File ".../asyncio/runners.py", line 201, in run
raise RuntimeError(
"asyncio.run() cannot be called from a running event loop")
RuntimeError: asyncio.run() cannot be called from a running event loopAnd the quietest one — blocking inside a worker — never raises anything. The tell is behavioural: the heartbeat task stops printing, queue.join() stops making progress, and CPU sits at ~0% while everything waits on one thread that is busy inside time.sleep. Profile with PYTHONASYNCIODEBUG=1 or look for to_thread-able calls in the stack.
Common misconceptions#
| Misconception | Reality |
|---|---|
| "Async makes calls faster." | It makes waiting overlap. One call's latency is unchanged; throughput rises because many waits share one thread. |
| "More concurrency is always better." | Past the Little's-law minimum you queue at the provider, latency inflates, and 429s/bans follow. There is an optimum, not a maximum. |
| "The GIL means threads are useless." | The GIL blocks parallel CPU work, but threads overlap I/O waits perfectly well — and asyncio is just a cheaper way to do the same overlap. |
"gather cleans up after itself on error." |
Without return_exceptions=True the first exception propagates but siblings keep running detached. For data jobs, collect Errs per item. |
| "A semaphore limits rate." | It limits simultaneous in-flight calls. Rate (calls started per second) needs a token bucket or sliding window — a different mechanism. |
| "Timeouts cancel the server-side work." | They cancel your await; the provider may still finish and bill. Pair timeouts with retry policy and idempotency (01B.9, 03.8). |
| "Batching and a Batch API are the same thing." | Client-side batching packs items into one call; a provider Batch API submits many calls as a deferred job. Different tools, they stack. |
"task_done()/join() is optional bookkeeping." |
It's the completion protocol: skip task_done and join hangs; skip join and you return before work finishes. |
| "Free-threaded Python means rewrite everything with threads." | It's officially supported since 3.14 but most C extensions still assume the GIL; the default build is unchanged. Watch it, don't rewrite for it yet. |
| "Retries are just more concurrency." | A retry storm is unbounded concurrency in disguise — same 429s, same ban, plus duplicate side effects. Cap attempts and jitter (01B.9). |
Key takeaways#
- Bounded concurrency is the core pattern. Never run more calls in flight than your budget allows; choose
Cfrom Little's law (in_flight = throughput × latency), not by trial and error until it breaks. - Three dials, three mechanisms: semaphore/worker-count bounds in-flight, token bucket/sliding window paces starts, batching reduces request count. You usually need all three.
asyncio.Queue+TaskGroupworkers is the scalable shape: fixed task count, FIFO hand-off,task_done()/join()completion, sentinel orshutdown()stop,maxsizefor backpressure.- Collect partial results. A
Result/Ok/Errtype with index-carrying gives you ordered successes and failures — the difference between a job that reports 9,980 good items and one that crashes on item 20. - Timeouts are per-task and per-job. A shared deadline timestamp beats N independent timeouts when the requirement is "finish the batch by T".
- Rate limit before you need to. A token bucket inside the semaphore keeps you under RPM/TPM budgets; adapt it on 429s and
x-ratelimit-*headers. - Single-flight dedups in-flight work by key — collapse N identical concurrent calls into one shared task.
- asyncio for I/O, threads for blocking sync code, processes for CPU. The GIL blocks parallel Python threads on CPU work but not I/O waits; free-threaded builds (3.14+) are coming but not yet a rewrite trigger.
- Graceful shutdown is a feature: stop-event, drain the queue, flush results, exit — before the orchestrator kills you mid-write.
Where you'll use this in the AI path#
- 03.9 Async, Concurrency and Batch Processing — the same bounded fan-out applied to real provider SDKs: semaphores,
ItemResult, per-provider budgets, worker pools for huge inputs, and the Batch APIs this lesson's batching previews. - 05.9 Ingestion Pipelines — backpressure, resumability and safe parallelism for parse/embed stages at corpus scale.
- 06.2 Embedding Pipelines — async embedding with bounded concurrency, TPM/RPM budgeting and batch embedding APIs — Part 3/4/5 patterns in production.
- 07.11 Production RAG — capacity planning: concurrency caps, rate limits and cost ceilings in a live service.
- 10A.8 Regression Testing — bounded parallelism for eval runs: cheap-judge-first, provider uptime, budget caps.
- 11B.3 Caching Strategies — single-flight/coalescing as a cache-stampede defence, the production version of 7.1.
- 11C.3 Fallbacks and Reliability — bulkheads (per-tenant concurrency pools), shared rate limiters and load shedding at scale.
- 08A.2 The Tool Loop — bounded parallel tool calls inside an agent loop, the same semaphore pattern one level up.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Fan-out | Running the same operation over many items concurrently |
| Bounded concurrency | Capping simultaneous in-flight calls (semaphore/worker count) |
| Worker pool | Fixed set of long-lived tasks pulling items from a queue |
| Producer/consumer | Pattern where producers put and workers get via a queue |
| Sentinel | A marker value (e.g. STOP = object()) telling workers to exit |
task_done() / join() |
Queue completion protocol: mark each get done; join waits for all |
Queue.shutdown() |
Python 3.13+ queue stop: get/put raise QueueShutDown, consumers drain |
| Backpressure | Bounding upstream rate to downstream capacity via bounded queues |
| Pipeline | Stages connected by queues; slowest stage throttles the rest |
| Token bucket | Rate limiter: capacity refills at rate/sec, calls spend tokens |
| Sliding window | Rate limiter: at most N starts in any rolling window |
| Little's law | in_flight = throughput × latency; sizes concurrency from rate and latency |
| Thundering herd | Many clients retrying/arriving at once, overloading a recovering service |
| Single-flight / coalescing | Collapsing N concurrent identical calls into one shared task |
asyncio.Lock / Condition / Event |
Async mutual exclusion / wait-for-predicate / one-bit signal |
| GIL | CPython mutex allowing one thread to run Python bytecode at a time |
| Free-threaded Python | GIL-disabled CPython build; experimental 3.13, supported 3.14 |
ThreadPoolExecutor / ProcessPoolExecutor |
concurrent.futures pools for threads / separate interpreters |
asyncio.to_thread |
Run a sync callable in the default thread pool from async code |
| Poison-item bisect | Isolating a bad item by splitting a failing batch in halves |
All terms are also collected in the glossary.
Exercises#
- Bounded fan-out (2.1): Using
bounded_gatherfromaitoolkit/concurrency.py, run 50 items through a fakeprocessthat sleeps 0.05 s withlimit=5. Predict the wall time, then verify it's roughlyceil(50/5) × 0.05 = 0.5 s. - Partial results (2.4): Make
processraise on every 4th item. Confirmrun_pipelinereturns 50Results with ~12Errs and ~38Oks, in input order. - Token bucket (4.2): Change
token_bucket_stampstorate=5, capacity=2, n=12. Predict the stamps, run it, and explain the burst of 2. - Sliding window vs bucket (4.3): For
max_calls=3, window=1.0, what's the maximum calls allowed in any 0.5 s sub-window? Compare with a token bucketrate=3, capacity=3— which is stricter and why? - Worker pool (3.1): In
run_pool, setqueue_size=8and feed 10,000 items through a 0.001 sprocess. Watch memory stay flat — explain whymaxsizematters here but not for 100 items. - Backpressure (3.3): Remove
maxsizefrombackpressure_demo.py. What doespeakbecome, and at what input size would it matter? - Little's law (6.2): A provider allows 1,200 req/min and calls take 2 s. Compute the minimum in-flight
C. Then suppose p95 latency is 8 s — recompute and explain which latency you should use. - Single-flight (7.1): Fire 50 concurrent
sf.do("same", factory)calls wherefactorycounts invocations. How many times doesfactoryrun? Then makefactoryraise — what do the 50 awaiters see? - GIL (8.1): Write a CPU-bound function (e.g. sum of squares to 10⁷) and run it in 4
ThreadPoolExecutorworkers vs sequentially. Predict, run, and explain the result using the GIL. - Graceful shutdown (3.6): Run
shutdown_demo.py, send SIGINT mid-run, and confirm it prints a processed count and exits rather than hanging. - Batching (5.2–5.3): Feed items into
WindowBatcherat irregular intervals (some bursts, some gaps). Verify no batch exceedssizeand no item waits longer thanwindow. - Ordering (2.4/3.1): Prove worker-pool results are unordered by completion but ordered by index — feed items with random delays and check
out[i]still matches itemi.
Solutions
ceil(50/5)=10waves × 0.05 s ≈ 0.5 s (plus small scheduling overhead).bounded_gatherholds at most 5 in flight.- 50
Results;Errs at indices 3,7,11,...,47 → 12Err, 38Ok, order preserved. rate=5, capacity=2: first 2 at t=0, then one every 0.2 s → stamps[0,0,0.2,0.4,...,2.0]— burst of 2 then steady 5/s.- The sliding window allows at most 3 starts in any 0.5 s sub-window (indeed in any 1 s span), but all 3 may land at the same instant: it caps the count per window, not the spacing. The token bucket (
rate=3, capacity=3) can start 3 at once and then refills a token every 0.33 s, so it can start 4 within 0.5 s and 5 or 6 within a 1-second span. The sliding window is therefore the stricter one: it never exceeds 3 per rolling second, whereas the bucket only guarantees the long-run average (3/s) plus its burst allowance. maxsize=8caps buffered items at 8 + 8 in-flight; without it the producer could enqueue all 10,000 before consumers start → memory spike. At 100 items it wouldn't matter.peakbecomes up to 50 (all items buffered) —qsize()can reachlen(items). Matters whenlen(items)is large enough to threaten memory.1200/60 = 20 req/s, so20 × 2 s = 40calls in flight. Little's law uses the average time a call spends in flight, so the p95 of 8 s is not the right input:20 × 8 = 160would over-provision about four times over and push you into the provider's queue. Use p95 to decide headroom instead (a few slow calls hold slots for a long time, so 40 × 1.2 to 1.5 is a sensible start), and measure the mean over a realistic run (6.4).factoryruns once; all 50 awaiters get the same result. If it raises, all 50 get the same exception instance — one poison key fails every waiter.- Threads give ~no speedup (GIL serialises the Python bytecode);
ProcessPoolExecutorwith 4 workers ≈ 4× faster. This is the GIL in action. - It should print
processed N items before shutdownand exit 0 — no hang, no traceback. - Batches flush at
sizeitems orwindowseconds;close()flushes the tail. No item waits > window (beyond scheduling jitter). - Completion order varies (random delays);
out[i]still holds itemi's result because the index travels with the item.
Check yourself#
- What's the difference between concurrency and rate limiting?Concurrency bounds simultaneous in-flight calls; rate limiting bounds call starts per unit time. You need both.
- Why does unbounded
asyncio.gatherover 10,000 items fail on a real provider?Rate limits (429), connection/socket exhaustion, memory growth, provider concurrency caps, queueing collapse, thundering-herd retries. - Name three things a bounded queue's
maxsizebuys you.Bounded memory (producer can't run ahead), backpressure to upstream, a natural buffer between uneven stages. task_done()andjoin()— what does each do, and what hangs if you skip them?task_done()marks eachget()handled;join()waits until done-count == put-count. Skiptask_done→joinhangs; skipjoin→ return before work finishes.- How do you tell
limitworkers to stop consuming from anasyncio.Queue?A sentinel value per worker,Queue.shutdown()(3.13+), or draining withget_nowait. - What's the difference between a token bucket and a sliding-window limiter?Bucket: continuous refill, O(1), allows bursts to
capacity. Window: hard "N per rolling window", O(N) timestamps, stricter per-window caps. - State Little's law and use it to find the in-flight count for 600 req/min at 4 s latency.
in_flight = throughput × latency = 10 req/s × 4 s = 40. - Why is
Result/Ok/Errbetter than letting the first exception kill a data job?It preserves all successes and records each failure with its error, in input order — vs losing everything to one exception. - What does single-flight deduplicate, and what's the difference from caching the result?It collapses N concurrent identical in-flight calls into one shared task (per key). Caching stores the result for reuse across time; single-flight dedups simultaneous work only.
- When is
threading/ThreadPoolExecutorthe right choice overasyncio?When the bottleneck is a blocking call you can't make async (sync-only SDK, legacy lib) — threads overlap the I/O waits. - Why doesn't the GIL help CPU-bound thread pools — and when do threads still help?The GIL lets only one thread run Python bytecode at once, so CPU work timeshares not parallelises. Threads still help I/O-bound work because blocking releases the GIL.
- What's the
__main__guard for inProcessPoolExecutorscripts?On spawn-start platforms each child re-imports__main__; without the guard, pool creation recurses into spawning more processes. - How does backpressure propagate through a multi-stage pipeline?A full downstream queue blocks the stage's
put, which fills its input queue, which blocks the stage before it — the throttle travels upstream automatically. - What's the composition order of rate limiter, semaphore, retry and timeout — and why does it matter?Timeout wraps each attempt; retry wraps the attempt(s); rate limiter paces call starts; semaphore bounds in-flight. Order matters because a retry inside the limiter multiplies effective rate, and a timeout outside retry can cancel mid-backoff.
Further resources#
- Python docs:
asyncio— queues and coroutines and tasks: the authoritative API reference forQueue,Semaphore,TaskGroup,timeout. - Python docs:
concurrent.futures:ThreadPoolExecutor/ProcessPoolExecutorsemantics,map/submit/as_completed. - PEP 703 — Making the Global Interpreter Lock Optional and Python support for free threading: the GIL-removal design and current free-threaded status.
- Python What's New in 3.14: free-threaded Python officially supported (PEP 779), ~5–10% single-thread penalty.
- Little's law — Wikipedia: the original statement and proof sketch; factory physics origin (John Little, 1961).
aiolimiteron PyPI (pypi.org/project/aiolimiter): a maintained leaky-bucket async limiter to compare with the hand-rolled one.- AWS Architecture Blog, "Exponential Backoff And Jitter": the canonical analysis of why jittered backoff prevents thundering herds (used in 01B.9).
- 03.9 Async, Concurrency and Batch Processing and 03.8 Errors and Retries: where every pattern here meets real provider APIs.
← 01B.3 — Async Python: async/await and the Event Loop | Module 01B overview | 01B.5 — HTTP Clients with httpx →