KatInterview

Threads vs Processes in Python: Concurrency Trade-offs

System DesignModel answer
MediumModel answerSystem Designconcurrencypythongil

Last updated

Compare thread-based and process-based concurrency in Python, covering the GIL, memory isolation, and which model fits I/O-bound vs CPU-bound workloads.

Threads vs Processes in Python

Modern applications often need to do several things at once — serve many users simultaneously, preprocess data in parallel, or keep a UI responsive while work happens in the background. Python gives you two primary tools for this: the threading module and the multiprocessing module. Knowing when to reach for each one is a practical engineering skill.

What to address

Part 1 — Core concepts

Explain what distinguishes a thread from a process at the operating system level. Cover:

  • How each maps onto physical CPU cores
  • How memory is (or isn't) shared between concurrent units of execution
  • What the Global Interpreter Lock (GIL) is, why it exists in CPython, and what it actually prevents vs. what it doesn't

Part 2 — Applied scenarios

Walk through the right concurrency strategy for each situation and justify your choice:

  1. A backend service fielding a large number of simultaneous requests, each of which spends most of its time waiting on a database or external API.
  2. A data pipeline that applies heavy numerical transformations — say, matrix operations on large arrays using NumPy.

Part 3 — Trade-off analysis

Compare threads and processes across these dimensions:

  • Memory and startup overhead
  • Cost of context switching
  • How the two units communicate and share data
  • Fault isolation

Your answer should be concrete: give rough numbers where helpful, call out common mistakes (for example, oversubscribing CPU cores), and mention any modern Python features that change the picture.

Hints

Hint 1

The GIL doesn't affect all Python code equally — think about what happens when a thread is blocked on a network call vs. running a Python for-loop. That distinction drives most of the practical advice here.

Hint 2

NumPy's vectorized operations are a trap for the unwary: matmul and large ufuncs already spin up their own BLAS threads internally. What happens if you wrap that in a process pool with several workers?

Hint 3

Fork, spawn, and forkserver are the three process start methods on Linux/macOS. One of them has a subtle but nasty interaction with threads — consider what state gets copied and what doesn't.