A semaphore stops you doing too much at once. It doesn't stop you producing faster than anything downstream can consume — and when the producer is a fast network and the consumer is a slow database, that difference is measured in gigabytes.
A bounded queue is not enough on its own
asyncio.Queue(maxsize=n) makes put wait once there are n items waiting,
and that wait is backpressure. But it only bounds what the queue has
accepted. It does nothing about work that has been produced and is waiting
to be put — and that is where the memory actually goes.
The trap is spawning one task per input:
async with asyncio.TaskGroup() as group:
for name in names:
group.create_task(produce(name)) # one task per input — the leakEvery task reads its source (bounded three at a time by the semaphore), then
lines up at queue.put. A task blocked on put has already finished reading
and is holding its result. So with ten thousand inputs you get a bounded
queue and ten thousand results sitting in blocked tasks. Counting only what
the queue accepted hides it completely.
The fix is a fixed pool of workers that pull inputs lazily from a shared
iterator. A worker reads the next input only after it has handed off the current
one, so it can't run ahead of the consumer — and the total in flight is bounded
by workers + queue_size + 1, whatever the input count. (The + 1 is the value
the consumer is holding.) Because the workers advance the iterator only as they
become free, a generator or other lazy stream is never drained up front.
import asyncio
async def naive(queue_size, items, consume_delay=0.02):
queue = asyncio.Queue(maxsize=queue_size)
outstanding = peak = 0
async def produce(index):
nonlocal outstanding, peak
await asyncio.sleep(0.001) # a fast read
outstanding += 1 # the value exists now, before the hand-off
peak = max(peak, outstanding)
await queue.put(index) # ...and the task keeps holding it here
async def consume():
nonlocal outstanding
while True:
await queue.get()
await asyncio.sleep(consume_delay)
outstanding -= 1
consumer = asyncio.create_task(consume())
async with asyncio.TaskGroup() as group:
for index in range(items):
group.create_task(produce(index))
consumer.cancel()
return peak
async def pooled(workers, queue_size, items, consume_delay=0.02):
sources = iter(range(items)) # pulled lazily, one at a time
queue = asyncio.Queue(maxsize=queue_size)
outstanding = peak = 0
async def produce():
nonlocal outstanding, peak
while True:
try:
index = next(sources) # no await between asking and owning it
except StopIteration:
return
await asyncio.sleep(0.001)
outstanding += 1
peak = max(peak, outstanding)
await queue.put(index) # blocks until taken: no reading ahead
async def consume():
nonlocal outstanding
taken = 0
while taken < items:
await queue.get()
await asyncio.sleep(consume_delay)
outstanding -= 1
taken += 1
async with asyncio.TaskGroup() as group:
for _ in range(workers):
group.create_task(produce())
group.create_task(consume())
return peak
async def main():
for items in (10, 40):
n = await naive(queue_size=2, items=items)
p = await pooled(workers=3, queue_size=2, items=items)
print(f"{items:3} inputs: one task each -> peak {n:3} worker pool -> peak {p}")
asyncio.run(main())outstanding is counted the moment a value exists — before the hand-off — so
it measures the real backlog, not just what the queue holds. The per-task
version's peak tracks the input count: 10, then 40. The worker pool stays flat
at workers + queue_size + 1 — six here — whatever you throw at it. And because
next(sources) is synchronous, no two workers ever grab the same input, and a
generator is advanced only as far as the workers have reached.
Backpressure is a system property
The queue only pushes back if the producer awaits the put. put_nowait
raises QueueFull instead of waiting, which turns backpressure into an error
you have to handle — sometimes the right choice (dropping frames in a video
pipeline), usually not. And a producer that reads from another unbounded source
just moves the pile-up one step upstream. The bound has to reach all the way
back to where the work enters your system — which is exactly what "a worker
reads the next input only after handing off" enforces.
Shutting down, and supervising the consumer
The demo's consumer stopped after counting items values. A library can't do
that: its input is an iterator of unknown length, possibly a generator nobody
has finished yet. So the consumer loops until it is told to stop, by a
sentinel value, _STOP, that only the code supervising the workers may send,
and only once every worker is done. Send it one moment too early and the
consumer leaves while a worker is still holding a value, which then has no one
to take it.
run_pipeline runs the consumer and that supervising coordinator inside one
TaskGroup:
async with asyncio.TaskGroup() as group:
group.create_task(coordinate())
group.create_task(consume()) # a failure here cancels the producersNo task can outlive the call, and a failure anywhere cancels the rest. Putting
the consumer in the group is what supervises it. If the consumer
raises — a bad row, a closed socket — the group cancels the producers instead of
leaving them blocked on a full queue forever. The earlier design, with the
consumer created outside the group and a queue.join() waiting on it, would
simply hang if the consumer died. A hang is the worst failure mode there is: no
error, no exit, nothing to see.
The checkpoint
Day 5 checkpoint: read everything, a few at a time
pipeline.py has read_one, the Meter, and run_pipeline's setup and
outer group written. Five pieces are yours, in this order:
- Warm-up:
read_all, where a failing source must not lose the others, andread_all_strict, where a failure ends everything. TheBounded,StrictandCancellationtests check them. - The pipeline: inside
run_pipeline, the workerproduce, thecoordinatetask that runs the workers and sends_STOP, and the slowconsume. Each has a docstring stating its contract: what it must guarantee, not how. TheBackpressuretests check the bounded backlog, the laziness, that every value arrives, and that a dying consumer doesn't hang.
Seventeen tests in all. Done is all seventeen passing.
When the supplied tests pass, add one test of your own to test_pipeline.py, at the end of the Bounded class: with limit=1, check that every source is read and that Source.peak_in_flight is exactly 1. The supplied tests only use limits of 2 and 3. It should pass. Then ignore the limit, check that your test fails, and undo the change. A sample test is at the end of the solution.
Hint 1: the idea
The two read_alls are this morning's gather_results with Day 5's limit
added. The only difference between them is where a SourceError may go:
caught inside each worker, so the others survive, or left to reach the
TaskGroup, which cancels the rest and raises an ExceptionGroup on its own.
The pipeline keeps the worker pool's rule from Per-input tasks versus a worker pool: a worker owns one input at a time and can't fetch the next until the queue has taken the last. What's new is stopping. "Every worker has finished" is something only a structure that waits for all of them can know, and the sentinel must come after that point, never before it.
Hint 2: a first step
Write read_all first. Make one asyncio.Semaphore(limit) and pass it to every
read_one, which acquires a slot itself. Inside an inner worker, store each
value, with the try/except SourceError around the call. read_all_strict
is then the same code without the try.
For the pipeline, write consume first: a loop whose first step is
await results.get(), which returns on _STOP. Then coordinate: ask
yourself which construct you already use that waits for a set of tasks to
finish, and where in the function the put of _STOP must therefore go.
Show one solution
async def read_all(names, *, limit=3, delay=0.01, failing=frozenset()):
results: dict[str, str] = {}
async def worker(name: str) -> None:
try:
results[name] = await read_one(name, limit_slots, delay=delay,
fail=name in failing)
except SourceError:
pass # a missing source is not fatal here
limit_slots = asyncio.Semaphore(limit)
async with asyncio.TaskGroup() as group:
for name in names:
group.create_task(worker(name))
return results
async def read_all_strict(names, *, limit=3, delay=0.01, failing=frozenset()):
results: dict[str, str] = {}
limit_slots = asyncio.Semaphore(limit)
async def worker(name: str) -> None:
results[name] = await read_one(name, limit_slots, delay=delay,
fail=name in failing)
async with asyncio.TaskGroup() as group:
for name in names:
group.create_task(worker(name))
return resultsThe two differ by one try, and that's the lesson: where you catch decides
whether a failure is local or fatal. Inside the worker, the group never learns
anything went wrong. Outside, the group cancels the siblings and raises an
ExceptionGroup.
Both create the semaphore inside the async function, so it binds to the loop
that's actually running — a module-level one would break the second time a test
calls asyncio.run.
Neither needs a lock around results[name] = ...: the assignment contains no
await, so no other task can run in the middle of it.
The three pipeline pieces, inside run_pipeline:
async def produce() -> None:
while True:
try:
name = next(sources) # sync: no await between asking and owning it
except StopIteration:
return
value = await read_one(name, slots)
meter.produced() # counted before the hand-off
await results.put(value) # a full queue blocks here, so we stop reading
async def coordinate() -> None:
async with asyncio.TaskGroup() as producers:
for _ in range(workers):
producers.create_task(produce())
await results.put(_STOP) # producers done: release the consumer
async def consume() -> None:
while True:
item = await results.get()
if item is _STOP:
return
await asyncio.sleep(consume_delay) # a slow consumer
meter.took(item)await results.put(value) is the backpressure: while the queue is full, the
worker waits there holding one value, and doesn't call next again. That's
why the backlog stays at workers + queue_size + 1 however many inputs there
are, and why a generator of inputs is only advanced as fast as the consumer
keeps up. meter.produced() comes before the put so the value a blocked
worker is holding counts too.
coordinate gets its ordering from the inner TaskGroup: leaving the async with block means every worker has returned, so the put(_STOP) after it can't
overtake a value still in flight. Put the sentinel first, or create the workers
without a group to wait on, and the consumer stops early: values are left on
the queue, and the Backpressure tests that check what was consumed fail. The
inner group also means a
failing worker cancels its siblings and the error reaches the outer group.
consume returns only on _STOP. If consume raises instead, the outer
TaskGroup cancels the coordinator and with it the workers, which are blocked
on a full queue. Without that, the dying-consumer test would hang.
A test of your own. One that does the job, inside Bounded:
def test_a_limit_of_one_reads_one_at_a_time(self) -> None:
names = ["a", "b", "c", "d"]
results = asyncio.run(read_all(names, limit=1))
self.assertEqual(sorted(results), names)
self.assertEqual(Source.peak_in_flight, 1)A limit of one is the edge case: anything that lets a second read start early shows up as a peak of 2.
Bug hunt: the cleanup that skips cancellations
Someone rewrote read_one without the async with, "to make the close
explicit".
Find it, pin it, fix it
Find the cause yourself before you open the hints: read the failure, then add a print or two to narrow it down. Fix it in the playground until every test passes. Then add one regression test of your own to test_pipeline.py, in the Cancellation class: start one pipeline.read_one as a task, cancel it while it reads, and check that Source.open_sources is back to 0. Put the bug back for a moment and check that your test fails.
Reproduce. Three failures, and the clearest message is:
AssertionError: 4 != 0 : a cancelled read left a source openAll the ordinary tests pass. Reads work, failures work, the limit holds. Only the cancellation tests fail.
Hint 1: the idea
Inspect. The new code:
source = await Source(name, delay=delay, fail=fail).__aenter__()
try:
value = await source.read()
except Exception:
await source.close()
raise
await source.close()
return valueHint 2: a first step
Narrow. There are three ways out of await source.read(): a value, a
SourceError, or a CancelledError from the timeout. The first two close the
source. The third doesn't, because CancelledError inherits from
BaseException — so except Exception doesn't see it, and the close() after
the try is skipped by the exception on its way up.
Each cancelled read leaks one source. In a real library that's a connection, a file handle, or a lock somebody else is waiting for.
Show one solution
Pin. test_a_timeout_closes_every_source and
test_cancelling_a_task_still_cleans_up are the regression tests, and between
them they cover both ways a cancellation arrives: a deadline and an explicit
task.cancel().
Fix. Let the context manager do it:
async with limit:
async with Source(name, delay=delay, fail=fail) as source:
return await source.read()async with compiles to a try/finally, so every exit closes the source —
including the one nobody tests for.
Your regression test. One that fails with the bug and passes after the fix, inside Cancellation:
def test_cancelling_one_read_closes_its_source(self) -> None:
async def main() -> None:
task = asyncio.create_task(
pipeline.read_one("slow", asyncio.Semaphore(1), delay=10))
await asyncio.sleep(0.01)
task.cancel()
with contextlib.suppress(asyncio.CancelledError):
await task
asyncio.run(main())
self.assertEqual(Source.open_sources, 0)The tests that only fail under cancellation
This bug is invisible to fourteen of the seventeen tests. Any library doing I/O needs cancellation tests by name: cancel it mid-flight, time it out, and then assert that the resource counter is back to zero. Without them, this code ships.
Where Day 5 leaves you
Working on your own machine? Download the Day 5 files.
Two details in there are worth copying into your own work.
Source.open_sources is a counter on the class, incremented on enter and
decremented on exit, and the tests assert it's zero afterwards. Instrumenting a
resource like that costs four lines and turns "I think we close everything"
into an assertion.
And every test drives asyncio.run from a plain TestCase rather than using
IsolatedAsyncioTestCase, because the browser runtime this course uses can't
run the latter. On your own machine either works.
Threads, the GIL and free-threading
Everything today ran on one event loop in one thread. If your work is
CPU-bound, none of it helps: asyncio.to_thread moves a blocking call off the
loop, and ProcessPoolExecutor gets you real parallelism. The "no lock needed,
there's no await in between" reasoning today holds because a single event loop
only switches tasks at await — it is about coroutines sharing one loop, not
about the GIL. The moment the same state is touched from more than one thread
you need a lock, GIL or not; free-threaded builds (PEP 703, 3.13+) just make
that sharing genuinely parallel and the missing lock genuinely visible. That's
optional reading for now; the structured-concurrency habits transfer either way.
What you learned
- A bounded queue alone doesn't bound memory: a fixed pool of workers pulling
lazily from a shared iterator keeps the backlog to
workers + queue_size + 1and never materialises the input stream, whatever the input count. - Measure the backlog before the hand-off, or the number flatters you.
- Supervise the consumer inside the same TaskGroup, so its failure cancels the producers instead of hanging them.
- Where you put the
trydecides whether a failure is local or fatal. - Cleanup must survive cancellation, and only a cancellation test proves it.
Tomorrow: back to the ORM, with a profiler. The identity map from Day 1 has been quietly growing all week, and Day 6 measures it.