Speeding Up a Pillow Photo Pipeline with Workers
System DesignModel answerLast 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:
- Why processes instead of threads (or the reverse)?
- 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.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Clarifying assumptions
I would first ask: is the same edit chain applied to every image; where do outputs go and how are they named (never overwrite inputs by default); should one corrupt file abort the run or be recorded and skipped; roughly how many images, how large, and how many cores are available (including container CPU limits). Without answers I assume thousands of medium-size JPEGs, 4 to 16 cores, outputs in a separate directory, and that a bad file should be reported but not stop the batch.
Part 1: Correct sequential version
The unit of work is a function that takes an input path and an output path:
from pathlib import Path
from PIL import Image
def process_one(src: str, dst: str) -> tuple[str, str | None]:
try:
with Image.open(src) as im:
im = im.resize((800, 600))
im = im.rotate(90, expand=True)
im = im.convert("L")
im.save(dst)
return src, None
except Exception as e:
return src, repr(e)
def run_sequential(in_dir, out_dir):
out = Path(out_dir); out.mkdir(parents=True, exist_ok=True)
return [process_one(str(p), str(out / p.name))
for p in sorted(Path(in_dir).iterdir())
if p.suffix.lower() in {".jpg", ".jpeg", ".png"}]
Points worth stating:
- The
withblock closes the file; only one image is alive at a time, so memory stays flat. - The order of operations matters (resizing before or after rotating gives different results), so follow the given order exactly.
- Mode and format on save: converting to grayscale then saving in a format that supports it, and handling modes like RGBA going to JPEG, are common bugs.
- Errors are returned, not raised, so one bad file does not kill the batch, and the driver can summarize failures at the end.
Part 2: Speeding it up
Measure first
Time the sequential run. Then compare process CPU time (time.process_time) with wall time on a sample. If CPU time is close to wall time, the job is CPU-bound (decode, resample, encode). If wall time is much larger, I/O dominates. For typical photos, decoding and resampling dominate, so I expect CPU-bound.
Processes vs threads
- Python's GIL lets only one thread run Python bytecode at a time. Pillow does release the GIL in many heavy C routines (decoding, resize, filters, encoding), so threads can give real speedup, but not reliably: the Python glue between calls, and any operation that holds the GIL, serialize. The gain depends on the Pillow version and the specific operations.
- Processes sidestep the GIL entirely and scale predictably with cores for CPU-bound work. The cost is start-up time, memory per worker, and serialization of arguments and results.
- Choice: processes as the default for CPU-bound image work, because the result does not depend on which calls release the GIL. Threads are reasonable if profiling shows most time in GIL-releasing C code or the work is mainly I/O (for example, reading from network storage), and they are cheaper in memory and start-up. I would back the choice with a quick benchmark of both.
Parallel structure
import os
from concurrent.futures import ProcessPoolExecutor
def available_cpus():
try:
return len(os.sched_getaffinity(0))
except AttributeError:
return os.cpu_count() or 1
def run_parallel(pairs, workers=None, chunksize=16):
workers = workers or available_cpus()
with ProcessPoolExecutor(max_workers=workers) as ex:
srcs, dsts = zip(*pairs)
return list(ex.map(process_one, srcs, dsts, chunksize=chunksize))
Key design decisions:
- Send paths, not pixels. Pickling a multi-megabyte image per task would cost more than it saves. Each worker opens, transforms, saves, and closes its own file.
- Chunking (
chunksize) reduces per-task IPC overhead when images are small. Too large a chunk hurts load balancing when sizes vary. - Workers return only a small status tuple, so failures still propagate to the parent and get reported.
- Output is identical to the sequential version because each image is processed independently with the same code.
ex.mappreserves input order for the result list.
Worker count
Start with the number of usable cores, not the number the OS reports: use sched_getaffinity and respect container CPU quotas (cgroup limits). For purely CPU-bound work, more workers than cores adds context switching and memory without benefit. If there is meaningful I/O wait, a modest oversubscription (for example 1.5x cores) can help. Large images also bound the count by memory: workers times peak per-image memory (roughly width x height x channels, plus decode buffers) must fit in RAM. Then confirm empirically by timing 1, 2, 4, ... and cores workers and picking the knee of the curve.
Overheads and expectations
- Process start-up (especially with
spawn) is a fixed cost, so for a tiny batch the parallel version can be slower. Ask whether timing includes pool start-up. - Speedup is below linear because of disk contention, memory bandwidth, and uneven image sizes. Expect something like 70 to 90 percent efficiency on a few cores.
- Reusing one pool for the whole batch avoids repeated start-up.
- Pillow-SIMD,
Image.draft()for JPEG downscaling at decode time, orreduce()could give further speedups, but only if output must stay identical;draftchanges results, so it is out of bounds here.
Common mistakes
- Optimizing before having a correct, tested baseline.
- Passing opened images or byte buffers between processes.
- Choosing a worker count by guess (or
cpu_count()inside a limited container) without measuring. - Letting an exception in a worker silently disappear or crash the whole pool.
- Claiming threads never help because of the GIL, or that they always do; the honest answer is "it depends on where Pillow releases the lock, so measure."
- Overwriting inputs, or non-deterministic output naming that breaks the test comparison.
Complexity
Sequential time is O(N x cost per image). With P workers on P free cores it is roughly O(N x cost / P) plus fixed start-up and IPC overhead. Memory is O(P x peak image size).