KatInterview

Choosing Threads, asyncio, or Processes for Python Workloads

System DesignModel answer
MediumModel answerSystem Designpythonconcurrencygil

Last 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:

  1. Definitions. What does it mean for a job to be limited by computation versus limited by waiting on external resources?
  2. Diagnosis. How would you tell which kind of job you have in a real system, using measurements rather than guesses?
  3. Comparison. How do threads, asyncio, and multiprocessing each behave for both kinds of job in CPython?
  4. 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?
  5. 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.