Apply Backpressure with Async Queues
Core idea
An asyncio.Queue(maxsize=n) with positive capacity pauses a producer at await put when full. Consumers await get; after processing each retrieved item they call task_done exactly once. join waits until all enqueued items have been acknowledged, not just removed. This is backpressure: the producer cannot grow the buffer indefinitely.
import asyncio
async def main(): q = asyncio.Queue(maxsize=1) await q.put('A') entered = asyncio.Event() async def producer(): entered.set() await q.put('B') t=asyncio.create_task(producer()) await entered.wait() print(q.full(), t.done()) print(await q.get()) q.task_done() await t print(await q.get()) q.task_done() await q.join()
asyncio.run(main())The first removal frees capacity; the second put completes.
Expected output:
True FalseABAcknowledge processing
import asyncio
async def main(): q=asyncio.Queue() for x in (2,3): await q.put(x) async def consumer(): total=0 for _ in range(2): x=await q.get() try: total+=x finally: q.task_done() return total t=asyncio.create_task(consumer()) await q.join() print(await t, q.empty())
asyncio.run(main())This bounded batch acknowledges each item even if processing raises. Production code must define failure and shutdown policies.
Expected output:
5 TrueCommon mistake
An empty queue does not mean all items have been processed. Missing task_done can hang join; extra calls raise ValueError. These queues are not thread-safe.
Practice
Change capacity to two and use three fixed items; trace when the producer must wait and when join can finish.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Async queues
Check your understanding of async queues.
What is printed?
import asyncio
async def main(): q=asyncio.Queue(1) q.put_nowait(3) print(q.full(), q.qsize())
asyncio.run(main())What is printed?
import asyncio
async def main(): q=asyncio.Queue() await q.put(9) print(await q.get()) q.task_done() await q.join()
asyncio.run(main())What waits for all enqueued work to be acknowledged?
What happens to await put on a full bounded queue?