ConcurrencyPythonverifiedVerified

Producer-Consumer Pattern in Python

Decouple data production from data consumption using a shared buffer, allowing each side to operate at its own pace.

How to Implement the Producer-Consumer Pattern in Python

1Step 1: Implement the bounded async queue using asyncio.Queue

import asyncio

2Step 2: Create producer and consumer coroutines

async def producer(queue: asyncio.Queue[int]) -> None:
    for i in range(10):
        await queue.put(i)
        print(f"Produced: {i}")


async def consumer(queue: asyncio.Queue[int]) -> None:
    for _ in range(10):
        item = await queue.get()
        print(f"Consumed: {item}")
        queue.task_done()

3Step 3: Run producer and consumer concurrently

async def main() -> None:
    queue: asyncio.Queue[int] = asyncio.Queue(maxsize=3)
    await asyncio.gather(producer(queue), consumer(queue))


if __name__ == "__main__":
    asyncio.run(main())

Producer-Consumer Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Producer-Consumer Pattern in the Real World

Think of a bakery where bakers (producers) place fresh loaves on a display shelf (the queue) and customers (consumers) pick them up at their leisure. The shelf decouples the baking schedule from customer arrival times — bakers keep baking even when no customer is present, and customers keep shopping even when bakers are on break.