LearnQuestion bank

A single-process script that handles a huge dataset of independent records is too slow. How would you parallelise it, and what changes if the records depend on one another?

ResearchTechnicalMedium

Answer it yourself first, out loud or on paper, then compare.

Answer

Model answer, written in a candidate's voice

In short

  • Profile first: CPU, IO, or accelerator bound?
  • Shard independent records; use process pools or map-reduce/distributed frameworks
  • Python GIL: processes for CPU-bound, threads/async for IO-bound
  • Dependencies: partition by key/dependency group, add reduce stage, message passing
  • Make work idempotent with retries, checkpoints, and dedupe
  • Use Amdahl’s law to estimate speed-up and watch coordination overhead

In full

I would start by profiling rather than assuming: if the script is CPU-bound, I would shard the records and use a process pool or a map-reduce/distributed framework such as Spark, Dask, or Ray, because Python threads do not give true CPU parallelism due to the GIL. If it is IO-bound, I would use async I/O or a thread pool and batch/pipeline the calls, and if it is accelerator-bound I would batch work for the GPU or accelerator instead of spawning many CPU workers. For independent records, the key is a clean map stage with no shared mutable state and a simple reduce/collect at the end. If records depend on one another, I would not shard arbitrarily; I would partition by key or dependency group so interacting records stay together, then add a reduce/aggregation stage and use message passing or queues to coordinate stages and handle ordering. I would make each task idempotent with retries, checkpoints, and dedupe keys so failures can be replayed safely. Finally, I would estimate the gain with Amdahl’s law, roughly 1/((1-p)+p/N), and remember that serial work, data movement, and coordination overhead often cap the real speed-up, so I would measure on a representative sample before committing.

Checked against sources by an independent AI reviewer.

What a strong answer covers

  • Profile first: CPU, IO or accelerator bound?
  • Shard the data; use process pools or map-reduce.
  • Python’s GIL: threads vs processes; async for IO-bound work.
  • With dependencies: partition by key, add a reduce stage, use message passing.
  • Idempotent retries.
  • Amdahl’s law for the expected speed-up.

Common mistakes

  • Threads for CPU-bound Python.
  • No plan for failures or ordering.