KatInterview

Speeding Up a Pillow Photo Pipeline with Workers

System DesignModel answer
HardModel answerSystem Designpythonpillowmultiprocessing

Last updated

Build a per-photo Pillow pipeline that applies a fixed series of edits, then cut wall-clock time with parallelism and justify processes vs threads and the worker count.

Photo Batch Pipeline

You have a directory of photographs and need to run the same ordered series of edits on each one using the Pillow library. Think of a typical chain such as resize, then rotate, then convert to grayscale. In a real exercise, the exact operations and their Pillow calls are supplied to you.

A test harness runs your code on every photo, verifies the outputs, and reports total elapsed time.

Rules

  • Use Pillow for every image operation.
  • A faster version must write byte-for-byte the same results as the straightforward version, since the tests compare output.
  • You are not told how many images there are, how big they are, or how many CPU cores the machine has. Ask about these or state your assumptions.

Part 1: Make it work

Write the processing code. For each input photo: open it, apply the edits in order, and save the result. Cover:

  • Correct ordering and correct handling of image modes and output formats
  • Proper cleanup of file handles, and holding only one image in memory at a time
  • A small, self-contained function for one image, plus a driver that loops over all inputs
  • What happens when a file is corrupt or unreadable

Part 2: Make it faster

Total time is reported, so reduce it. If you introduce parallelism, expect to defend two choices:

  1. Why processes instead of threads (or the reverse)?
  2. If you use processes, how many workers do you launch and why?

Discuss whether the job is CPU-bound or I/O-bound and how you would verify that, what the global interpreter lock implies here, and what overheads (start-up, inter-process data transfer, task batching, memory per worker) affect your design.

What to deliver

Describe your approach, write the code for both parts, state your assumptions and clarifying questions, and explain how you would measure the improvement.

Hints

Hint 1

Get a correct sequential version first and time it; you cannot argue about speedups without a baseline.

Hint 2

Decide whether the time goes to decoding/resampling (CPU) or to disk reads and writes (I/O). Profile a few images, or compare CPU time to wall time.

Hint 3

Pass file paths to workers rather than pixel data, and let each worker open, transform, save, and close its own image.

Hint 4

Start from the number of cores actually available to the process (consider affinity or container limits), then benchmark nearby values and chunk the tasks to amortize overhead.