Build a Parallel Image Transform Pipeline With Worker Processes
System DesignModel answerLast updated
Design a resize-then-watermark pipeline for a batch of photos, then scale it across a bounded pool of worker processes with safe output writes and per-photo failure isolation.
A photo-hosting service needs to convert every newly uploaded image into a feed-ready thumbnail: resized to specified dimensions and marked with a small corner watermark. Your job is to build this pipeline in two stages — first get the single-image operation right, then scale it across multiple worker processes.
Context
To keep the problem self-contained and easy to test without external dependencies, represent images as 2D lists of integers (pixel values). The design decisions you make here — transform ordering, output safety, process boundaries — carry over directly to a real implementation using a library like Pillow.
Constraints
- Every image comes with an explicit job spec: source file path, destination file path, target width and height, and a watermark intensity value. None of these are hardcoded or defaulted anywhere.
- Images are independent of each other, but memory and disk I/O are shared across the whole batch.
- A corrupt or missing image must never abort the batch. It should produce an error record; every other image should continue unaffected.
- Worker count is bounded — you should not spawn one process per image.
Part 1 — Single-image processing
Implement a function that reads one image, resizes it, stamps the watermark into the bottom-right corner, writes the output, and returns a result record. It must never raise an exception past its own boundary.
def process_image(spec: dict) -> dict:
"""
spec keys: id, src_path, dst_path, target_size (w, h), watermark_value
Returns {'id': ..., 'status': 'ok'}
or {'id': ..., 'status': 'error', 'error': str}
"""
Consider what happens to the destination file if the process is killed mid-write. How do you ensure no reader ever mistakes a half-written file for a completed one?
Part 2 — Parallel batch processing
def run_pipeline(specs: list[dict], max_workers: int) -> list[dict]:
"""
Process every spec using at most max_workers processes in flight.
Return exactly one result or error record per spec.
"""
Think carefully about what you pass to each worker process and why it should be as small as possible.
What a strong answer covers
- Transform order: resize first, watermark second — explain why the order is not arbitrary.
- Atomic output: a destination file is either absent or complete, never partially written.
- A bounded worker pool rather than unbounded process spawning.
- Passing lightweight job specs across process boundaries, not decoded pixel buffers.
- Per-image failure isolation: one bad input produces one error record, nothing more.
Hints
Hint 1
Apply the watermark after resizing, not before. If you stamp the corner first, the resize step will scale and distort the watermark pixels along with the rest of the image.
Hint 2
Write output to a temporary file next to the destination, then use os.replace() to move it into place. On POSIX systems this rename is atomic, so a reader never sees a partially written file at the final path.
Hint 3
Each worker process receives a job spec (a few strings and numbers) and reads the source image file itself. Shipping the already-decoded pixel grid through the IPC pipe would cost tens of megabytes per image and negate most of the parallelism benefit.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Transform order matters
Resize must happen before the watermark is applied. If you stamp the corner first and then shrink the image, the watermark pixels get resampled along with everything else — they may blur, shift, or disappear entirely depending on the scale factor. Stamping after resize guarantees the watermark always lands in the exact bottom-right corner of the final output at full intensity.
Atomic output publication
Writing directly to dst_path creates a window where a crash or signal mid-write leaves a partial file at that path. Any downstream reader — a thumbnail server, a CDN prefetch job — cannot tell a partial file from a complete one just by checking whether the path exists.
The fix is to write to a sibling temp path (dst_path + ".tmp"), then call os.replace(tmp_path, dst_path). On POSIX filesystems, rename/replace is atomic: the destination path flips from absent to fully-written in a single syscall. No reader ever observes an intermediate state. One caveat: os.replace is only atomic when source and destination are on the same filesystem, so if your temp directory is on a different volume than the output location, write the temp file into the same directory as the destination.
What crosses the process boundary
Worker processes don't share memory, so every argument passed to a worker is serialized and piped. A job spec — a handful of strings and integers — serializes in microseconds and costs negligible bandwidth. A decoded image at, say, 1920×1080 with integer pixel values is several megabytes; multiplied across a large batch, shipping buffers through IPC would consume more time and memory than the actual transforms. Each worker should receive only the spec and read its own source file directly from disk.
Bounded worker pool
ProcessPoolExecutor(max_workers=N) keeps at most N images in flight simultaneously. Peak memory is bounded by N × (one image in memory), which stays predictable regardless of batch size. Spawning one process per image would cause the entire batch to be decoded and held in memory at once, potentially exhausting RAM and causing the OS to thrash.
Failure isolation
Every exception inside process_image is caught at the function boundary and turned into an error record. This means pool.map receives a return value for every spec, and the caller never sees an unhandled exception from a bad input. The rest of the batch keeps running.
Implementation
import os
import pickle
import concurrent.futures
def resize_nearest(grid: list, target_size: tuple) -> list:
"""Nearest-neighbor resize of a 2D pixel grid."""
src_h = len(grid)
src_w = len(grid[0]) if src_h else 0
dst_w, dst_h = target_size
if src_h == 0 or src_w == 0 or dst_w <= 0 or dst_h <= 0:
raise ValueError(f"invalid dimensions: src=({src_w},{src_h}) dst=({dst_w},{dst_h})")
out = []
for ty in range(dst_h):
sy = min(src_h - 1, (ty * src_h) // dst_h)
row = []
for tx in range(dst_w):
sx = min(src_w - 1, (tx * src_w) // dst_w)
row.append(grid[sy][sx])
out.append(row)
return out
def stamp_watermark(grid: list, value: int, mark_size: int = 2) -> list:
"""Overwrite the bottom-right corner with watermark_value."""
h = len(grid)
w = len(grid[0]) if h else 0
# Shallow-copy rows so we don't mutate the input
out = [row[:] for row in grid]
for y in range(max(0, h - mark_size), h):
for x in range(max(0, w - mark_size), w):
out[y][x] = value
return out
def process_image(spec: dict) -> dict:
"""
Reads, resizes, watermarks, and atomically writes one image.
Never raises; returns a result or error record.
"""
try:
with open(spec["src_path"], "rb") as f:
grid = pickle.load(f)
resized = resize_nearest(grid, spec["target_size"]) # step 1
stamped = stamp_watermark(resized, spec["watermark_value"]) # step 2
tmp_path = spec["dst_path"] + ".tmp"
with open(tmp_path, "wb") as f:
pickle.dump(stamped, f)
os.replace(tmp_path, spec["dst_path"]) # atomic publish
return {"id": spec["id"], "status": "ok"}
except Exception as exc:
return {"id": spec["id"], "status": "error", "error": str(exc)}
def run_pipeline(specs: list[dict], max_workers: int = 4) -> list[dict]:
"""
Process every spec with a bounded worker pool.
Returns one result dict per spec, preserving input order.
"""
with concurrent.futures.ProcessPoolExecutor(max_workers=max_workers) as pool:
return list(pool.map(process_image, specs))
Verification
import tempfile
if __name__ == "__main__": # guard required for process spawning on Windows/macOS
tmpdir = tempfile.mkdtemp()
specs = []
for i in range(3):
grid = [[(r + c + i) % 256 for c in range(8)] for r in range(8)]
src = os.path.join(tmpdir, f"src_{i}.pkl")
with open(src, "wb") as f:
pickle.dump(grid, f)
specs.append({
"id": f"img{i}",
"src_path": src,
"dst_path": os.path.join(tmpdir, f"out_{i}.pkl"),
"target_size": (4, 4),
"watermark_value": 999,
})
# intentionally broken spec — file does not exist
specs.append({
"id": "bad",
"src_path": os.path.join(tmpdir, "missing.pkl"),
"dst_path": os.path.join(tmpdir, "out_bad.pkl"),
"target_size": (4, 4),
"watermark_value": 999,
})
for r in run_pipeline(specs, max_workers=2):
print(r)
# {'id': 'img0', 'status': 'ok'}
# {'id': 'img1', 'status': 'ok'}
# {'id': 'img2', 'status': 'ok'}
# {'id': 'bad', 'status': 'error', 'error': '[Errno 2] No such file...'}
Complexity and edge cases
Time: O(total output pixels / max_workers) in the parallel regime, bounded below by the single slowest image. Each pixel is visited once during resize and once during watermark stamping.
Memory: O(max_workers × image_size) — at most max_workers decoded images exist in memory simultaneously, independent of batch size.
Common mistakes:
- Watermarking before resizing — the mark gets distorted or lost.
- Writing directly to the destination — leaves corrupt files on crashes.
- Passing decoded buffers to workers instead of file paths — saturates IPC pipes on large images.
- Using a thread pool instead of a process pool for CPU-bound work — the GIL prevents true parallelism for pure Python pixel loops (less relevant with Pillow's C extensions, but still a good design habit).
- Not guarding the entry point with
if __name__ == "__main__"— breaks process spawning on platforms that usespawnrather thanfork.