Producer-Consumer Pattern
Decouple production and consumption with a shared queue. Producers generate items at their own pace; consumers process them through a buffer.
Overview
When one part of a system produces data and another part consumes it, they rarely run at the same speed. A producer might generate 1,000 items per second while a consumer handles 100. Without a buffer between them, the producer either waits for the consumer (slow) or drops items (lossy). The Producer-Consumer pattern puts a queue in the middle: producers push items in, consumers pull them out, and each side runs at its own pace.
When to Use
- A producer and consumer run at different speeds and you need to smooth out the mismatch
- You want to decouple producer and consumer so neither knows the other exists
- You need to process items concurrently with multiple producers or consumers
- You want to absorb bursts without losing items
When not to use it:
- The work is trivially synchronous: a plain function call is simpler than a queue
- Latency matters more than decoupling: a queue adds at least one context switch per item
- You already have an external broker (Kafka, RabbitMQ) doing this job between processes
Solution
Python (queue.Queue with threads)
import threading
import queue
import time
import random
buffer = queue.Queue(maxsize=10) # Bounded buffer
def producer(name, count):
for i in range(count):
item = f"{name}-item-{i}"
buffer.put(item) # Blocks if buffer is full
print(f"[{name}] Produced {item}")
time.sleep(random.uniform(0.01, 0.05))
buffer.put(None) # Sentinel: signal completion
def consumer(name):
while True:
item = buffer.get() # Blocks if buffer is empty
if item is None:
buffer.put(None) # Pass sentinel to other consumers
break
print(f"[{name}] Consumed {item}")
time.sleep(random.uniform(0.05, 0.15)) # Consumer is slower
buffer.task_done()
# 2 producers, 3 consumers
producers = [
threading.Thread(target=producer, args=("P1", 20)),
threading.Thread(target=producer, args=("P2", 20)),
]
consumers = [
threading.Thread(target=consumer, args=("C1",)),
threading.Thread(target=consumer, args=("C2",)),
threading.Thread(target=consumer, args=("C3",)),
]
for p in producers: p.start()
for c in consumers: c.start()
for p in producers: p.join()
for c in consumers: c.join()
print("All done")
JavaScript (async queue with workers)
import { EventEmitter } from "events";
class AsyncQueue {
constructor(maxsize = Infinity) {
this.items = [];
this.maxsize = maxsize;
this.notFull = new EventEmitter();
this.notEmpty = new EventEmitter();
this.closed = false;
}
async put(item) {
while (this.items.length >= this.maxsize) {
await new Promise((resolve) => this.notFull.once("drain", resolve));
}
this.items.push(item);
this.notEmpty.emit("data");
}
async get() {
while (this.items.length === 0) {
if (this.closed) return null;
await new Promise((resolve) => this.notEmpty.once("data", resolve));
}
const item = this.items.shift();
this.notFull.emit("drain");
return item;
}
close() {
this.closed = true;
this.notEmpty.emit("data");
}
}
async function producer(queue, name, count) {
for (let i = 0; i < count; i++) {
const item = `${name}-item-${i}`;
await queue.put(item);
console.log(`[${name}] Produced ${item}`);
await new Promise((r) => setTimeout(r, Math.random() * 40));
}
}
async function consumer(queue, name) {
while (true) {
const item = await queue.get();
if (item === null) break;
console.log(`[${name}] Consumed ${item}`);
await new Promise((r) => setTimeout(r, 50 + Math.random() * 100));
}
}
async function main() {
const queue = new AsyncQueue(10);
const producers = [
producer(queue, "P1", 20),
producer(queue, "P2", 20),
];
const consumers = [
consumer(queue, "C1"),
consumer(queue, "C2"),
consumer(queue, "C3"),
];
await Promise.all(producers);
queue.close();
await Promise.all(consumers);
console.log("All done");
}
main();
Java (BlockingQueue)
import java.util.concurrent.*;
public class ProducerConsumerExample {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> buffer = new ArrayBlockingQueue<>(10);
// Producer
Runnable producer = () -> {
for (int i = 0; i < 20; i++) {
try {
String item = "item-" + i;
buffer.put(item); // Blocks if buffer is full
System.out.println("[Producer] Produced " + item);
Thread.sleep((long) (Math.random() * 40));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
try {
buffer.put("POISON"); // Sentinel
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
};
// Consumer
Runnable consumer = () -> {
while (true) {
try {
String item = buffer.take(); // Blocks if buffer is empty
if ("POISON".equals(item)) {
buffer.put("POISON"); // Pass to other consumers
break;
}
System.out.println("[Consumer] Consumed " + item);
Thread.sleep(50 + (long) (Math.random() * 100));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
};
ExecutorService pool = Executors.newFixedThreadPool(4);
pool.submit(producer);
pool.submit(producer);
pool.submit(consumer);
pool.submit(consumer);
pool.submit(consumer);
pool.shutdown();
pool.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("All done");
}
}
Explanation
The queue sits between producers and consumers so neither has to wait for the other. Producers add items without blocking (until the buffer fills). Consumers grab the next item as soon as they’re free to work on it. If the queue is bounded and full, put blocks until a consumer frees a slot. If it’s empty, the take call parks the consumer until an item shows up.
A bounded buffer gives you backpressure: once it fills, producers can’t outrun consumers, and memory stays capped. An unbounded buffer never blocks producers, but if they stay faster, memory grows until the process dies. In practice, the bound is your safety valve, so pick one unless you have a reason not to.
Multiple producers and consumers can share one queue safely because the implementation synchronizes internally (locks, or CAS in lock-free versions). Each item goes to exactly one consumer; nothing gets processed twice.
The trade-off you’re making is ordering and latency for decoupling. Items come out in roughly FIFO order, but with several consumers you lose any guarantee about which item finishes first. And every queued item pays a small price: it waits in the buffer until a consumer picks it up. For most workloads that’s a good deal: you get independent scaling and burst absorption in exchange for a few milliseconds of queue time.
Choosing a Buffer Size
There’s no universal number, but a few rules of thumb help:
- Steady-state difference: if producers average 20% faster than consumers, even a huge buffer only delays the overflow. Fix the rate mismatch instead.
- Burst absorption: size the buffer to hold your worst expected burst (say, 30 seconds of peak production) so producers never stall during a spike.
- Item memory cost: a queue of 10,000 small task IDs is cheap; 10,000 image buffers is not. Bound the queue by memory footprint, not just item count.
- Latency budget: a deep queue hides backpressure and adds queuing delay. If p99 latency matters, keep it shallow and scale consumers instead.
Graceful Shutdown
Stopping cleanly is the part most examples skip. A clean stop needs three pieces:
- Producers finish first: wait for all producers to complete before signaling consumers.
- A sentinel per consumer: one poison pill reaches exactly one consumer. Either push one pill per consumer, or have each consumer re-queue the pill before exiting (as in the examples above).
- Drain before exit: decide whether pending items should be processed or discarded, and make it explicit.
queue.join()in Python orawaitTerminationin Java wait for the queue to empty.
Failing to do this leaves threads blocked on get() forever or silently drops the last items.
Real-World Usage
You probably use this pattern every day without noticing:
- Java thread pools:
ThreadPoolExecutoris a bounded queue plus a pool of consumers, and rejected tasks are just backpressure wearing a different hat. - Kafka consumers: partitions act as the queue, consumer group members as consumers. The producer never waits for a specific consumer.
- Node.js: the event loop itself is a producer-consumer setup: I/O callbacks produce events, the loop consumes them one at a time.
- Logging frameworks: async appenders (Logback, Winston) queue log events so a slow disk doesn’t block request threads.
- Web servers: the accept queue parks incoming connections until a worker is free, which is why
backlogtuning shows up in every load-test postmortem.
Variants
| Variant | Buffer Type | Use Case | Tradeoff |
|---|---|---|---|
| Bounded Buffer | Fixed-size queue | Backpressure, memory-safe | Producers block when full |
| Unbounded Buffer | Growing queue | Maximum throughput | Memory can grow without limit |
| Priority Queue | Priority-based | Some items are urgent | Starvation of low-priority items |
| Ring Buffer | Circular array | Low-latency, fixed memory | Overwrites old data if not careful |
| Work Stealing | Per-consumer queues | Load balancing | More complex, overhead for stealing |
What Works
- Use a bounded buffer when memory is constrained or producers are consistently faster
- Use sentinels (poison pills) to signal consumers to stop gracefully
- Make consumers idempotent in case of redelivery after failures
- Monitor queue depth: a consistently growing queue means consumers are too slow
- Size the buffer to absorb expected bursts without blocking producers
- Use multiple consumers to scale processing throughput
- Name producer and consumer threads for debugging and thread dump analysis
Common Mistakes
- Unbounded buffer with a fast producer: memory grows until OOM. Set a bound unless you’ve proven producers can’t win the race.
- Single consumer bottleneck: one consumer falls behind against several producers. Scale out consumers instead of just making the buffer bigger.
- Not handling consumer failures: if a consumer crashes after taking an item, that item is gone. Use acknowledgments or transactions for critical work.
- Busy-waiting instead of blocking: polling the queue in a loop burns CPU for nothing. Use blocking
put/take/get. - Forgetting to stop consumers: without a sentinel or close signal, consumers wait on the queue forever and the process never exits.
- Locking the queue externally: the queue synchronizes internally already. Wrapping it in your own lock just adds contention, and in the worst case a deadlock.
Advanced Solutions
Work-stealing queue for load balancing
Every consumer gets its own local queue, and when that queue runs dry it starts stealing items from its neighbors’:
import queue
import random
import threading
class WorkStealingQueue:
def __init__(self, num_workers):
self.queues = [queue.Queue() for _ in range(num_workers)]
self.num_workers = num_workers
self.lock = threading.Lock()
self.random = random.Random()
def push(self, item):
"""Push to a random queue for load distribution."""
with self.lock:
idx = self.random.randint(0, self.num_workers - 1)
self.queues[idx].put(item)
def pop(self, worker_id):
"""Pop from local queue first, then steal from others."""
# Try local queue
try:
return self.queues[worker_id].get_nowait()
except queue.Empty:
pass
# Steal from other queues
for i in range(self.num_workers):
if i == worker_id:
continue
try:
return self.queues[i].get_nowait()
except queue.Empty:
continue
return None # All queues empty
Producer-consumer with acknowledgment and retry
Items shouldn’t vanish when a consumer dies mid-task. Track what’s in flight separately from the queue itself:
import queue
import threading
class ReliableQueue:
def __init__(self, maxsize=10):
self.pending = queue.Queue(maxsize)
self.in_flight = set()
self.lock = threading.Lock()
def put(self, item):
"""Put item into pending queue."""
self.pending.put(item)
def get(self):
"""Get item and mark it as in flight."""
item = self.pending.get()
with self.lock:
self.in_flight.add(item)
return item
def acknowledge(self, item):
"""Acknowledge successful processing."""
with self.lock:
self.in_flight.discard(item)
def get_unacked(self):
"""Return items that were taken but never acknowledged."""
with self.lock:
return list(self.in_flight)
def consumer(queue, name):
while True:
item = queue.get()
if item is None:
break
try:
process(item)
queue.acknowledge(item)
except Exception as e:
print(f"Consumer {name} failed on {item}: {e}")
# Item stays in in_flight for retry
A full retry loop also requeues items from get_unacked() after a timeout — this pattern mirrors how RabbitMQ redelivers unacked messages.
Priority queue for urgent items
Urgent items jump the line here. The pop has to stay inside the lock, right after the wait:
import heapq
import threading
class PriorityQueue:
def __init__(self):
self.heap = []
self.lock = threading.Lock()
self.not_empty = threading.Condition(self.lock)
def put(self, item, priority):
with self.lock:
heapq.heappush(self.heap, (priority, item))
self.not_empty.notify()
def get(self):
with self.lock:
while not self.heap:
self.not_empty.wait()
return heapq.heappop(self.heap)[1]
# Usage: lower priority value = processed first
queue.put("urgent_task", 0)
queue.put("regular_task", 10)
The risk is starvation: while urgent items keep coming, low-priority ones can wait forever. Aging — bumping an item’s priority the longer it sits — fixes that.
Further Reading
- Python
queuemodule: Queue, LifoQueue, and PriorityQueue reference java.util.concurrentBlockingQueue: the canonical Java implementation- Reactive Streams backpressure: the formalized version of bounded-buffer backpressure, see the Reactive Streams Pattern
- Go
syncand channels: how Go bakes producer-consumer into the language
Frequently Asked Questions
How is this different from a message queue like RabbitMQ?
The Producer-Consumer pattern is an in-process pattern — the shared queue lives in your program's memory. RabbitMQ, Kafka, or SQS are brokers that move messages between processes and machines, with persistence and delivery guarantees. Use this pattern for concurrency inside one process; use a broker when you cross process boundaries. The Message Queue Load Leveling Pattern covers the distributed version.
Should I use a bounded or unbounded buffer?
Start with bounded. It keeps memory bounded and slows producers automatically whenever they pull ahead. Go unbounded only if you've measured that producers can't outpace consumers for sustained periods — and even then, set a monitoring alert on queue depth.
How many consumers should I use?
For CPU-bound work, roughly one consumer per core — more just adds context switching. For I/O-bound work, you can go well beyond the core count because consumers spend most of their time waiting. Watch queue depth and consumer utilization to tune it; a Thread Pool makes adjusting the count cheap.
What is a poison pill?
A sentinel value (None, null, or a dedicated object) pushed into the queue to tell consumers to stop. Whichever consumer pulls it learns the stream is done and breaks out of its loop. With several consumers, either push one pill per consumer or have each consumer re-queue the pill so it propagates.
Can producers and consumers be on different machines?
Not with this pattern — the queue is in-process memory. For cross-machine producer-consumer, use a broker. The pattern's logic still applies: Kafka consumer groups are essentially multi-machine producer-consumer with partitioning.
Related Resources
Thread Pool Pattern
Reuse a fixed set of threads for short-lived tasks instead of creating a new thread per task. Reduces overhead and bounds resource usage under load.
PatternMessage Queue Load Leveling Pattern
Smooth traffic spikes by placing a queue between a producer and a consumer. The producer writes at any rate; the consumer processes at a steady pace.
PatternActor Model Pattern: Concurrency Without Shared State
Isolate state in actors that communicate only via messages. Each actor processes one message at a time, eliminating shared-state concurrency bugs by design.
PatternAsync Generator Pattern for Lazy Streaming
Stream data lazily with async generators. Yield values one at a time as they become available, enabling memory-efficient processing of large or infinite data sequences.
PatternLock-Free Queue Pattern
Build high-throughput queues using atomic operations instead of locks. Multiple threads can enqueue and dequeue concurrently without blocking or context-switching overhead.
PatternReactive Streams Pattern
Process asynchronous data streams with backpressure. Subscribers request N items at a time, preventing fast producers from overwhelming slow consumers.