Queues: producers and consumers

A queue connects code that makes work (producers) with code that does it (consumers). The producer puts items in, consumers get them out, and neither needs to know about the other. This shape shows up everywhere: job queues, web crawlers, log shippers.

asyncio.Queue is built for tasks. await queue.get() waits until an item arrives. Give it maxsize, and await queue.put(x) waits when the queue is full. That is backpressure: a fast producer is slowed to the consumers' pace instead of filling up memory.

To finish cleanly, each consumer calls queue.task_done() after each item, and await queue.join() waits until every item is done. Then cancel the consumers.

In system design interviews, "put a queue between them" is the standard answer to "the workers can't keep up with incoming requests".

Run it. Then change the number of workers to 1 and to 4.