Sub topic 12
Building pipelines with asyncio.Queue
This chapter assumes you can write coroutines, start them with asyncio.run, create tasks, and use TaskGroup (Python 3.11+). It also assumes you know what cancellation does to a task. Here you will connect tasks with asyncio.Queue, so that producers and consumers run at their own pace without sharing mutable state.
Why a queue
With gather or a TaskGroup, you start a fixed set of tasks. Many programs have a stream of work instead: URLs to fetch, lines to parse, messages to forward. You can't start one task per item without limit, because memory and connections run out.
A queue separates the code that creates work from the code that does it. Producers put items in. Consumers get items out. The queue sits between them and does three jobs:
- It buffers items while consumers are busy.
- It makes consumers wait when it is empty.
- It makes producers wait when it is full. This is called backpressure.
asyncio.Queue is not thread-safe and is meant for tasks on one event loop. To pass data between threads, use loop.call_soon_threadsafe or asyncio.run_coroutine_threadsafe. Do not call queue methods directly from another thread.
The core API
| Method | Behavior |
|---|---|
| `await q.put(item)` | Waits while the queue is full, then adds the item. |
| `await q.get()` | Waits while the queue is empty, then removes and returns an item. |
| `q.put_nowait(item)` | Adds the item or raises `asyncio.QueueFull`. |
| `q.get_nowait()` | Returns an item or raises `asyncio.QueueEmpty`. |
| `q.task_done()` | Marks one fetched item as fully processed. |
| `await q.join()` | Waits until every item that was put has been marked done. |
| `q.qsize()` | Current number of items. It is a snapshot and can be stale by the time you use it. |
Queue(maxsize=0) is unbounded, and put never waits. Prefer a bounded queue for any pipeline where the producer can outrun the consumers.
A minimal producer and consumer
import asyncio
async def producer(q):
for i in range(5):
await q.put(i)
async def consumer(q):
while True:
item = await q.get()
print("got", item)
q.task_done()
async def main():
q = asyncio.Queue(maxsize=2)
consumer_task = asyncio.create_task(consumer(q))
await producer(q)
await q.join()
consumer_task.cancel()
asyncio.run(main())With maxsize=2, the producer fills the queue and then suspends at put until the consumer frees a slot. The producer therefore never gets far ahead of the consumer.
q.join() returns when the count of unfinished items reaches zero. Each put raises that count, and each task_done lowers it. The consumer loops forever, so after join returns you cancel it. The while True loop is idle at that point, waiting in get.
Several consumers and a clean shutdown
Several consumers on one queue give you a worker pool. Each item goes to exactly one consumer. The queue is the work list, and no consumer needs to know about the others.
There are two common ways to stop the consumers.
- Join, then cancel. This is the pattern above. It is short, but the consumers end by cancellation, not by finishing their own loops.
- Sentinel values. The producer puts one marker per consumer, often
None. A consumer that receives the marker returns normally.
This example uses sentinels:
import asyncio
async def producer(q, n_consumers):
for i in range(6):
await q.put(i)
for _ in range(n_consumers):
await q.put(None)
async def consumer(name, q):
while True:
item = await q.get()
try:
if item is None:
return
await asyncio.sleep(0.1)
print(name, "processed", item)
finally:
q.task_done()
async def main():
q = asyncio.Queue(maxsize=3)
async with asyncio.TaskGroup() as tg:
for name in ("a", "b", "c"):
tg.create_task(consumer(name, q))
tg.create_task(producer(q, 3))
print("all finished")
asyncio.run(main())The TaskGroup block exits only when the producer and all three consumers have returned. The order in which a, b and c print is not fixed, but all six items are processed exactly once.
Always call task_done in a finally block
task_done must run for every item you fetched, including items that fail. If a consumer raises before calling it, the unfinished count never reaches zero, and q.join() waits forever. Wrap the processing in try and put task_done in finally, as the example does. Decide separately whether an error should kill the consumer or be logged so the loop can continue.
Chaining stages
A pipeline is a series of queues, with a stage between each pair. Every stage reads from one queue and writes to the next. A stage that finishes must forward the sentinel, so the next stage also learns that the input has ended.
import asyncio
async def source(out_q):
for i in range(1, 6):
await out_q.put(i)
await out_q.put(None)
async def square_stage(in_q, out_q):
while (item := await in_q.get()) is not None:
await out_q.put(item * item)
await out_q.put(None)
async def sink(in_q, results):
while (item := await in_q.get()) is not None:
results.append(item)
async def main():
a = asyncio.Queue(maxsize=2)
b = asyncio.Queue(maxsize=2)
results = []
async with asyncio.TaskGroup() as tg:
tg.create_task(source(a))
tg.create_task(square_stage(a, b))
tg.create_task(sink(b, results))
print(results)
asyncio.run(main())This prints [1, 4, 9, 16, 25]. Backpressure travels backward through the chain. A slow sink fills queue b, which blocks the square stage. That fills queue a and blocks the source. If a stage has several workers, send one sentinel per worker, and forward one sentinel downstream only after every worker has finished.
Here each stage uses sentinels and not join, because the stages end themselves. You can use either style, but do not mix them within one queue.
Other queue types
asyncio.PriorityQueuereturns the smallest item first. Items must be comparable, so use tuples like(priority, counter, payload). The counter breaks ties, so payloads are never compared.asyncio.LifoQueuereturns the most recently added item first, like a stack.
Both take maxsize and offer the same methods as Queue.
Closing a queue in Python 3.13+
Python 3.13 added Queue.shutdown(). After a shutdown, put raises asyncio.QueueShutDown. get keeps returning the remaining items, then raises the same exception once the queue is empty. This removes the need for sentinels.
import asyncio
async def consumer(q):
try:
while True:
item = await q.get()
print("got", item)
q.task_done()
except asyncio.QueueShutDown:
print("queue closed")
async def main():
q = asyncio.Queue()
task = asyncio.create_task(consumer(q))
for i in range(3):
await q.put(i)
await q.join()
q.shutdown()
await task
asyncio.run(main())q.shutdown(immediate=True) also discards the items still queued. This example fails with AttributeError on Python 3.12 and earlier, so use sentinels if you must support those versions.
Common errors
- Hanging on
join. Usually a missingtask_done, an exception that skipped it, or consumers that have already died. Puttask_doneinfinally. In long-running services, also watch the consumer tasks so that a crashed one is noticed. - Hanging in
getforever. The producer finished but sent no sentinel, or sent fewer sentinels than there are consumers. - Unbounded memory.
Queue()with nomaxsizeaccepts everything. A fast producer then grows the queue without limit. - Too many
task_donecalls. Calling it more often than items were fetched raisesValueError. - Forgotten tasks. Keep a reference to every consumer task, or put the tasks in a
TaskGroup. A task that nothing references can be garbage-collected before it finishes. - Blocking calls in a stage. A
time.sleepor a synchronous HTTP call inside a consumer stalls the whole loop. Useasyncio.to_threadfor such work.
Exercise
A consumer does item = await q.get(), then await process(item), then q.task_done(). Sometimes process raises an exception that the consumer catches outside its loop, ending the consumer. The main task awaits q.join() and then hangs. Why does it hang, and how do you fix it?
Show answer
The failing item was fetched, but task_done() was never called for it, so the unfinished count never reaches zero, and join() waits forever. Remaining items also stay unprocessed if no other consumer is alive. Fix it by calling q.task_done() in a finally block around the processing, so it runs for every fetched item. Then decide whether to catch and log the error inside the loop, so the consumer keeps running, or let it end while other consumers continue.
Exercise
A pipeline has one producer and four consumers sharing a queue, and it uses sentinels to stop. How many sentinels must the producer put, and why?
Show answer
Four, one per consumer. Each consumer takes exactly one sentinel from the queue and then returns. With fewer sentinels, some consumers stay blocked in get() forever. Extra sentinels are harmless in this setup but remain unread in the queue.