Lesson · Async Python
Async Design & Pitfalls
90 min readAsync Design & Pitfalls
Good async design controls blocking work, cancellation, task lifetime, and backpressure. Unlimited task creation can move a bottleneck rather than solve it.
Learning goals
- Explain why a blocking call inside a coroutine freezes every other task on the loop.
- Say which work belongs in an event loop, a thread, or a process, and why.
- Point at the line in the queue example that enforces backpressure and describe the wait it creates.
- Describe how
task_doneand the sentinel cooperate so the consumer stops and the group exits. - Name the two ways acknowledgements go wrong and what each does to
queue.join().
Mental model
There is no flow to draw here, only a set of failure modes to avoid. Blocking calls hold the one thread the loop runs on; CPU-bound work cannot be overlapped by asyncio at all; unbounded task creation turns a slow consumer into rising memory and latency; and careless cancellation or acknowledgement leaves resources and queue bookkeeping unfinished. The worked example counters each one with a bounded queue, a shutdown sentinel, and a finally block around task_done.
The bound is what makes the producer wait
waiting instead of growing
Core idea
Async design is mostly about protecting one shared resource: the single thread that runs the loop. Keep blocking calls out of coroutines, move CPU-heavy work somewhere it cannot starve the loop, bound every producer, and make cancellation paths release what they hold. The queue example exercises all four: maxsize=3 supplies backpressure, the finally block survives interruption, and the sentinel gives the consumer a clean reason to stop.
Blocking the event loop
Blocking the event loop means doing work inside a coroutine that holds the thread, such as time.sleep, a synchronous HTTP call, or a long CPU loop, so no other task can run until it returns. The loop regains control only at an await that actually yields, and a blocking call never yields.
CPU work in async programs
CPU-bound work does not wait on I/O, so asyncio cannot overlap it on one thread and it starves every other task while it runs. The usual escapes are asyncio.to_thread for blocking functions and a process pool for pure computation, which moves the work off the loop entirely.
Cancellation safety
Cancellation safety is a control-flow event used to stop unfinished concurrent or asynchronous work. Code must release resources and decide whether to propagate, translate, or deliberately suppress the cancellation.
Structured cleanup
Structured cleanup keeps release logic inside the scope that acquired the resource: finally blocks, async with, and TaskGroup bodies. When cancellation arrives mid-operation, the cleanup still runs because one scope owns both halves of the lifetime.
Backpressure intuition
Backpressure limits how fast producers can enqueue or start work when consumers are slower. Without it, latency and memory usage can grow even while throughput stays unchanged.
Threads vs processes vs asyncio
These three tools divide by what the work spends its time doing: asyncio for many I/O waits coordinated on one thread, threads for blocking calls that release the GIL while they wait, and processes for CPU-bound work that needs a separate interpreter. The choice depends on the workload, not on which model sounds more modern.
Walkthrough
asyncio.Queue(maxsize=3)is bounded: once three items are waiting,await queue.put(value)suspends the producer instead of letting the buffer grow, which is backpressure.- The consumer takes the next item with
await queue.get(), plays the slow work withawait asyncio.sleep(0.05), and callsqueue.task_done()in afinallyso the acknowledgement happens even if the body is interrupted. - The
Nonesentinel is put after the ten values; the consumer returns when it sees it, and theTaskGroupexits once both sides have finished. - Predict before running: the number of "processed" lines, which side stays busy longer, and what
queue.qsize()does once the consumer becomes the slower side.
Experiments to try
- Remove
maxsize=3and printqueue.qsize()after each put; compare how far the producer runs ahead with and without the bound. - Change the consumer's sleep to 0.01 and the producer's range to 20; predict the total runtime from the consumer's pace and confirm the producer never waits.
- Replace
await queue.put(value)withqueue.put_nowait(value)on a full queue and read theQueueFullexception; explain what the await form exists for. - Wrap the group in
asyncio.timeout(0.3)and return early from the consumer after two items; explain from the full queue why the producer can never finish.
Playable lesson
Lab: Async backpressure lab
Control producer rate, consumer rate, queue capacity, and worker count. Plot queue depth and latency over time.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
Async backpressure
Queue contents
depth 0 / maxsize 3
producer
running
trying to put item 0
room in the queue, so put returns without waiting
consumer
idle
nothing to process yet
each item costs one unit of work, then `task_done()` releases the bookkeeping
Predict first
The producer is much faster than the consumer. What stops the queue from growing without limit?
The queue starts empty with room for three items. The producer runs freely because `put` returns immediately while there is space, and the consumer takes one item at a time.
Common mistakes
- Calling blocking code in a coroutine:
time.sleep, synchronous HTTP clients, and heavy computation hold the thread, so timers and I/O callbacks wait and every task behaves as if the loop were frozen. - Starting one task per item with no bound: each task still holds memory and a connection slot, so a fast producer floods whatever comes next; a semaphore, a queue bound, or a worker pool keeps the number of in-flight operations sustainable.
- Losing the shutdown signal: a consumer that waits on an empty queue with no sentinel and no cancellation keeps the
TaskGroupopen forever, turning a design gap into a hang. - Unbalanced
queue.task_done()calls: skipping it makesqueue.join()wait forever, calling it before the work is finished letsjoin()return too early, and calling it more times than items were put raisesValueError.
Practice: Easy
- Run the worked example unchanged and count the "processed" lines; confirm exactly one
task_donecall happens per item. - Set
maxsize=1, thenmaxsize=0, and record how the producer's pace changes; note that 0 means unbounded inasyncio.Queue, not "no buffer". - Print
queue.qsize()before eachgetand after eachtask_doneand label the moments where the producer had to wait.
Practice: Medium
- Add a second consumer to the group and compare total runtime with the single consumer; explain the change from the queue bound and the 0.05 second work.
- Make the consumer raise
ValueErroron the value 5; catch the group's exception outside and state whytask_donehad already run for item 5 when the failure surfaced. - Replace the consumer's
asyncio.sleep(0.05)withtime.sleep(0.05)and time the run; explain the stall from the blocked loop.
Practice: Hard
- Build a bounded worker pool: one producer, three consumers,
maxsize=10, and a results list; measure total time against the single consumer and identify the bottleneck when consumer work triples. - Create a deadlock setup where the consumer returns after two items while the producer keeps filling a full queue; wrap the group in
asyncio.timeout(0.5)and explain the hang and the cancellation from the queue state. - Move a blocking CPU function into
asyncio.to_threadinside the consumer and compare a heartbeat task's tick spacing before and after the move.
Lesson checklist
- I can point at the line where backpressure is enforced and say what happens when the queue is full.
- I can explain why a blocking call in one coroutine freezes every other task.
- I can describe who acknowledges an item and why
task_donesits in afinallyblock. - I can choose between threads, processes, and asyncio for a given workload.
Remember
Async design protects the one thread that runs the loop: keep blocking calls off it, move CPU-heavy work to threads or processes, and bound every producer so a slow consumer cannot be flooded. The queue example makes the contract concrete: a bound for backpressure, a sentinel for shutdown, and `task_done` in a `finally` so the accounting survives interruption.
Interview angles
What is the main purpose of **Blocking the event loop**?+
Blocking the event loop means doing work inside a coroutine that holds the thread, such as time.sleep, a synchronous HTTP call, or a long CPU loop, so no other task can run until it returns. The loop regains control only at an await that actually yields, and a blocking call never yields.
What should you pay attention to when using **CPU work in async programs**?+
CPU-bound work does not wait on I/O, so asyncio cannot overlap it on one thread and it starves every other task while it runs. The usual escapes are asyncio.to_thread for blocking functions and a process pool for pure computation, which moves the work off the loop entirely.
How does **Cancellation safety** fit into this lesson?+
Cancellation safety is a control-flow event used to stop unfinished concurrent or asynchronous work. Code must release resources and decide whether to propagate, translate, or deliberately suppress the cancellation.
Why does an unbounded `create_task` burst hurt a service even when every task is only waiting on I/O?+
Each task still occupies memory, a socket or file descriptor, and a slot at the downstream service, so a fast producer keeps opening work that a slower resource must absorb. Latency and memory grow while throughput stays capped; a semaphore or a bounded queue keeps the number of in-flight operations at a level the slowest part can sustain.