Producer-Consumer and Worker Pools in Python
Concurrency bugs do not announce themselves. A pipeline that drops one message in every ten thousand runs, or a worker pool that exhausts memory only on Mondays when the backlog is largest, looks perfectly fine in a demo. The patterns in this lesson exist to make those failures structural impossibilities rather than probabilistic annoyances: a producer-consumer pair with an explicit contract, a queue that is bounded so back-pressure propagates instead of memory growing, and a shutdown sequence that guarantees every item is either processed or reported.
Everything here rests on one decision made first â whether your bottleneck is waiting or computing â because that choice determines whether threads, processes, or coroutines are the right primitive, and no amount of pattern work fixes a mismatched one.
Waiting versus computing decides the primitive
The global interpreter lock means Python threads cannot execute bytecode in parallel, so
for pure calculation a thread pool buys you almost nothing beyond the loop you already
had. Threads remain excellent when the work is spent waiting â network reads, disk
latency, database round trips â because the lock is released during I/O and the kernel
does the multiplexing. Processes are the opposite: real parallelism across cores for CPU
work, paid for with serialization of arguments and results. Coroutines give you massive
concurrency with tiny overhead when the workload is thousands of small I/O operations,
but they require every dependency in the chain to be async-aware.
| Bottleneck | Tool | Why | Cost |
|---|---|---|---|
| Network or disk waits | ThreadPoolExecutor | Lock releases during I/O | Shared state needs care |
| Pure computation | ProcessPoolExecutor | Real multi-core parallelism | Pickling and memory copies |
| Thousands of small I/Os | asyncio tasks | Tiny per-task overhead | Entire stack must be async |
| Mixed waiting and parsing | Threads plus a process pool | Each stage gets the right tool | More moving parts |
| Ordering must be preserved | Single consumer after a pool | Determinism beats throughput | Consumer becomes the limit |
Producer-consumer with an explicit contract
The pattern has two roles and one channel between them. The producer generates or fetches work and enqueues it; the consumer dequeues and processes. The channel â a queue â is where the contract lives: what a message looks like, how many may be in flight, and what signals the end of the stream.
import asyncio
import random
async def producer(queue, count):
for i in range(count):
item = {"id": i, "payload": f"job-{i}"}
await queue.put(item)
print(f"produced {item['id']}")
await asyncio.sleep(random.uniform(0.01, 0.05))
await queue.put(None) # sentinel: no more work is coming
async def consumer(queue, sink):
processed = 0
while True:
item = await queue.get()
try:
if item is None:
return processed
await sink.write(item)
processed += 1
finally:
queue.task_done()
async def run(count=25):
queue = asyncio.Queue()
sink = MySink()
prod = asyncio.create_task(producer(queue, count))
cons = asyncio.create_task(consumer(queue, sink))
await asyncio.gather(prod, cons)
return await cons # consumer returns its processed count
print(asyncio.run(run()))
Note that run awaits both tasks together: awaiting the producer first and the consumer
second would deadlock, because the consumer's sentinel can only be consumed while the
loop is still running other tasks. Gathering is what keeps both halves live.
Two details make this version correct. The sentinel is a message like any other, so the
consumer's loop stays linear and the shutdown path is visible in the code rather than
being an exception unwinding the stack. And queue.task_done() sits in a finally, so an
item that raises on processing is still marked done â otherwise await queue.join()
hangs forever waiting on a task that will never be reported.
Bounding the queue so back-pressure propagates
An unbounded queue is a memory leak with good manners. If the producer outpaces the
consumer even slightly, the queue absorbs the difference until the process dies â and it
does so gradually, so the failure appears far from its cause. A bounded queue converts
that into back-pressure: the producer's put blocks (or awaits) until the consumer
catches up, which keeps memory flat and makes the true throughput limit obvious.
import queue
import threading
def producer(q, jobs, stop):
try:
for job in jobs:
q.put(job, timeout=1.0)
except queue.Full:
logging.error("queue stayed full â consumer is not keeping up")
finally:
q.put(None)
def consumer(q, results):
while True:
job = q.get()
try:
if job is None:
return
results.append(handle(job))
except Exception:
logging.exception("job %r failed", job)
finally:
q.task_done()
Pick the bound from a budget, not from intuition: multiply the largest acceptable memory footprint of one item by the depth you can afford, and you have the number. When the queue sits permanently full, that is a capacity signal you want to see â it is far better than discovering the same limit as an out-of-memory kill.
Shutting down without losing work
The difference between a professional pipeline and a demo is what happens on the way out. A graceful shutdown stops accepting new work, drains what is already queued, flushes sinks, and exits with a status that reflects reality. Ctrl-C should not strand a half-written file.
import signal
def install_signal_handlers(stop_event):
def handler(signum, frame):
logging.warning("signal %s received â draining", signum)
stop_event.set()
signal.signal(signal.SIGINT, handler)
signal.signal(signal.SIGTERM, handler)
def main():
stop = threading.Event()
install_signal_handlers(stop)
q = queue.Queue(maxsize=500)
results = []
workers = [threading.Thread(target=consumer, args=(q, results), daemon=True)
for _ in range(8)]
for w in workers:
w.start()
try:
produce_until(stop, q)
q.put(None) # one sentinel per worker
for extra in workers[1:]:
q.put(None)
finally:
for w in workers:
w.join(timeout=30)
if any(w.is_alive() for w in workers):
logging.error("workers did not exit in time â %d items unprocessed",
q.qsize())
Note the sentinel-per-worker rule: one None stops one consumer, so a pool of eight
needs eight, or the remaining seven block forever on get. And the final join with a
timeout plus a log line turns a hang into a diagnosable message.
CPU-bound pools and the pickle boundary
When the work is computation, processes are the tool, and they introduce a boundary you must design around: arguments and return values are pickled. That rules out closures, database connections, and open file handles as payloads, and it makes the cost of crossing the boundary visible for large arrays. Keep items coarse â send a batch, not a row â and let the pool do the fan-out.
from concurrent.futures import ProcessPoolExecutor, as_completed
import os
def score_batch(batch):
return [(row["id"], expensive_score(row)) for row in batch]
def score_all(batches):
workers = min(os.cpu_count() or 4, len(batches))
scored = []
with ProcessPoolExecutor(max_workers=workers) as pool:
futures = {pool.submit(score_batch, b): b[0] for b in batches}
for future in as_completed(futures):
try:
scored.extend(future.result())
except Exception:
logging.exception("batch %s failed", futures[future])
return scored
as_completed rather than executor.map matters when batches fail: map raises on the
first exception and abandons the remaining results, while as_completed lets you collect
the successful batches and decide deliberately how to handle the failed one.
Debugging races and deadlocks
Concurrency failures share a short list of causes, and knowing them shortens diagnosis
enormously. A deadlock usually means two locks acquired in different orders, or a get
waiting on a queue that no one will ever fill â add timeouts to both and the wait becomes
an error. A lost item usually means an exception path that skipped task_done or skipped
enqueuing the sentinel. Non-deterministic results usually mean shared mutable state
written by workers without a lock, or an assumption that as_completed preserves input
order.
The cheapest fix for most of these is instrumentation: log enqueue and dequeue with an item id, count items at every boundary, and assert that produced equals consumed equals written at shutdown. An invariant checked at the end of the run catches a class of bug that no amount of staring at the happy-path trace will ever reveal.
One last practice shortens the feedback loop dramatically: build the pipeline so the same code can run single-threaded with a configuration flag. When a bug reproduces in sequential mode, it is a logic bug and you can debug it with a normal debugger; when it disappears, you have learned that the fault lives in the concurrency layer â a much narrower search space than the whole program.
Common Mistakes
Using an unbounded queue so the producer can outrun the consumer
Fix: Bound the queue and let back-pressure slow the producer down
Feeding one sentinel into a pool of several workers
Fix: Push one sentinel per worker, or use a shared stop event alongside it
Calling pool.submit for every row of a large dataset
Fix: Batch rows so pickling overhead is paid once per chunk instead of once per item
Skipping task_done or join in exception paths
Fix: Put task_done in a finally block so poison items cannot hang the pipeline
Expecting threads to speed up pure Python computation
Fix: Use a process pool for CPU work and reserve threads for I/O-bound stages
Best Practices
- Decide between threads, processes, and coroutines from the bottleneck before writing code
- Log and count items at every boundary; assert produced equals consumed at shutdown
- Give every blocking wait a timeout so a hang turns into a diagnosable exception
- Handle worker failures per item so one poison message does not stop the fleet
- Measure queue depth over time â a permanently full queue is a capacity alarm
Key Takeaways
- Threads suit waiting, processes suit computing, coroutines suit massive small-I/O concurrency
- The queue is the contract: bound it, define the message shape, and define the end signal
- Sentinels stop one worker each; pools need one per worker
- Graceful shutdown drains the queue, flushes sinks, and reports anything unprocessed
- Assert produced equals consumed â the cheapest concurrency test you can write