Choosing Threads, asyncio, or Processes for Python Workloads
System DesignModel answerLast updated
Explain how to tell whether a job is limited by computation or by waiting, and how the GIL affects choosing threads, asyncio, or multiprocessing for crawling, parsing, and heavy number work.
You are reviewing a Python service that crawls pages, parses them, and runs some heavy numeric processing. A teammate asks how to speed it up and which concurrency tool to reach for.
Write the answer you would give. Cover the following:
- Definitions. What does it mean for a job to be limited by computation versus limited by waiting on external resources?
- Diagnosis. How would you tell which kind of job you have in a real system, using measurements rather than guesses?
- Comparison. How do threads,
asyncio, and multiprocessing each behave for both kinds of job in CPython? - The GIL. How does the Global Interpreter Lock shape the choice, and where is the simple "threads don't help CPU work" rule too blunt?
- Task mapping. Which model would you pick for (a) crawling many URLs, (b) parsing the downloaded documents, (c) heavy numeric computation, and (d) a pipeline that does the crawling and parsing together?
Use concrete examples and mention trade-offs and common pitfalls.
Hints
Hint 1
Compare CPU time with wall-clock time for the same run. If they are close, the process is busy computing; if wall time is much larger, it is mostly waiting.
Hint 2
Think about when CPython releases the GIL: around blocking system calls and inside some native extensions, but not while running ordinary Python bytecode.
Hint 3
asyncio runs on a single thread and switches only at await points, so one long computation freezes every other task. Consider how to push such work elsewhere.
Hint 4
For a crawl-then-parse pipeline, think about giving each stage the tool that suits its bottleneck, and about limiting concurrency so you do not overwhelm remote servers.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
A job is limited by whichever resource it spends most of its time on.
- CPU-bound: the processor is busy executing instructions. Examples: hashing, compression, image resizing, simulations, and parsing large documents in pure Python. More or faster cores help; a faster network does not.
- I/O-bound: the job spends most of its time waiting on something outside the CPU, such as HTTP responses, disk reads, database queries, or a rate limiter. A faster CPU barely matters; overlapping many waits matters a lot.
How to tell them apart
- CPU time vs wall time. Run
time python job.py. Ifuser + sysis close toreal, it is CPU-bound. Ifrealis far larger, it is waiting. In code, comparetime.process_time()withtime.perf_counter(). - Utilization. One core pinned at 100% in
topsuggests CPU-bound. Low CPU with many sleeping threads or heavy network activity suggests I/O-bound. - Profiling. With
cProfileorpy-spy, hot frames in your own functions point to CPU work. Time insiderecv,select, SSL reads, or database drivers points to waiting. - Experiment. Add workers. If threads speed it up, the work is I/O-bound or runs in GIL-releasing native code. If only processes help, it is CPU-bound Python.
The three models in CPython
| Model | CPU-bound | I/O-bound |
|---|---|---|
| Threads | Little or no speedup for pure Python, because of the GIL | Good for tens to hundreds of concurrent waits |
asyncio | Harmful: long computation blocks the event loop | Best for thousands of concurrent connections |
| Multiprocessing | Near-linear speedup up to the core count | Works, but heavy and wasteful |
How the GIL shapes the decision
The GIL lets only one thread execute Python bytecode at a time.
- CPU-bound pure Python with threads: threads take turns (the switch interval is about 5 ms), so four threads take roughly as long as one, sometimes longer due to contention.
- I/O-bound with threads: the GIL is released around blocking calls such as
recv,read, andsleep, so other threads run while one waits. Overlap works well. - Native extensions can release the GIL. NumPy,
zlib, andhashlibon large buffers do this, so threads can parallelize CPU work inside them. The precise rule is "CPU-bound Python bytecode does not scale with threads." - Multiprocessing avoids the GIL because each process has its own interpreter. Costs: startup time, more memory, and pickling of arguments and results. Tiny tasks or large payloads can lose the gain to IPC, so batch work (for example
chunksizeinmap). - asyncio is single-threaded, so the GIL is not its issue. Its weakness is that any long CPU stretch stalls every coroutine. Offload with
loop.run_in_executororasyncio.to_thread; note that threads only help if the work releases the GIL, otherwise use a process pool. - Python 3.13 offers an experimental free-threaded build (PEP 703) where threads can run Python code in parallel. Standard advice still assumes the GIL build.
Mapping tasks to models
- Crawling: I/O-bound. Use
asynciowithaiohttporhttpx, with a semaphore for global concurrency and per-host limits. AThreadPoolExecutorwithrequestsis a simpler option at moderate scale. - Parsing: usually CPU-bound. Pure-Python parsing of HTML, JSON, or logs at volume goes in a
ProcessPoolExecutor. C-backed parsers likelxmlare fast enough that small parses can stay inline. - Heavy computation: CPU-bound. First vectorize with NumPy (often 10-100x). Then spread across cores with processes. Threads help only if the hot loop is in GIL-releasing native code.
- Crawl-then-parse pipeline: fetch with asyncio, hand parsing to a process pool via
run_in_executor, so both network and cores stay busy. Use bounded queues to apply backpressure so fetching does not outrun parsing and exhaust memory.
Rough cost model
For N independent requests of latency L:
- Sequential: about N·L.
- Concurrency C: about ceil(N/C)·L, until bandwidth, server limits, or file descriptors become the bottleneck.
For CPU work W on P cores:
- Threads (standard CPython): about W.
- Processes: about W/P plus IPC cost.
Per-unit memory: a coroutine costs a few KB, a thread reserves a large stack (often 8 MB virtual on Linux, much less committed), and a process holds a whole interpreter (tens of MB). That is why asyncio reaches ~10k connections while threads top out around hundreds.
Illustrative code
import asyncio
from concurrent.futures import ProcessPoolExecutor
import httpx
def parse(html: str) -> int:
# stand-in for CPU-heavy parsing
return sum(1 for ch in html if ch == "<")
async def crawl(urls, workers=8, limit=50):
sem = asyncio.Semaphore(limit)
loop = asyncio.get_running_loop()
async with httpx.AsyncClient() as client, \
ProcessPoolExecutor(workers) as pool:
async def one(url):
async with sem:
resp = await client.get(url)
return await loop.run_in_executor(pool, parse, resp.text)
return await asyncio.gather(*(one(u) for u in urls))
if __name__ == "__main__":
print(asyncio.run(crawl(["https://example.com"] * 20)))
Common pitfalls
- Blocking calls in async code (
requests.get,time.sleep, long loops) freeze the event loop. Use async libraries or offload. - Oversubscription: a process pool larger than the core count, or multiprocessing combined with multithreaded BLAS, causes thrashing. Size pools to
os.cpu_count()and cap library threads (for exampleOMP_NUM_THREADS). - Multiprocessing requirements: under the
spawnstart method (default on macOS and Windows) you need anif __name__ == "__main__":guard, and worker functions must be picklable top-level functions, not lambdas. - Shared state:
x += 1is not atomic, so threads still need locks despite the GIL. Processes share nothing by default. - Unbounded concurrency can exhaust sockets and get you rate-limited or blocked. Always cap with a semaphore or fixed pool.
- Skipping measurement. Profile first; the bottleneck is often not where you expect.