Batch-Apply Transform Chains to a Folder of Photos
System DesignModel answerLast updated
Apply every transform chain to every photo, in order, with deterministic output names, no repeated decoding, and a design that parallelizes cleanly.
You have a list of m photos (given as file paths) and a list of n transform chains. Each chain is an ordered list of k callables, and each callable takes an image and returns a new image (for example resize, rotate, crop, blur, or a colour adjustment).
Task
Write a function that produces m × n result images by running every chain on every photo.
Requirements
- Every result must be identifiable by the pair
(image_id, pipeline_id). - The operations inside a chain must run strictly in the listed order.
- Photos are read from disk; chains are plain callables.
- Structure the code so it can be parallelized easily. In particular, avoid redundant work such as decoding the same file more than once.
Suggested interface
- Inputs:
image_paths: List[str](length m)pipelines: List[List[Callable[[Image], Image]]](length n, each of length k)output_dir: str
- Output: write
m*nfiles intooutput_dirusing deterministic names such asimg{i}_pipe{j}.png, and/or return the list of written paths.
Assumptions
mandnmay be large enough that runtime and I/O efficiency matter.- Operations can be CPU-heavy; decoding and encoding files is I/O-heavy.
Discussion (no implementation needed)
- How would you scale this to very large
mandn? - Which parallelization strategy would you choose, and why?
Give your approach, its complexity, and code, and mention the edge cases you would handle.
Hints
Hint 1
The result set is a Cartesian product. Think about which loop should be outer so that expensive per-photo work (decoding) happens once per photo rather than once per (photo, chain) pair.
Hint 2
Operations might modify their input in place. What must you do before running each chain so that chains do not contaminate each other?
Hint 3
Name outputs from indices, not from completion order or file contents. Also think about how to make writes safe if a task crashes and is retried, and how to avoid re-sending the chains to workers with every task.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
The outputs form the Cartesian product of photos and chains, so the product itself is trivial. The real design question is how to group the work to avoid repeated effort and to parallelize without coordination.
Each output (i, j) has three cost components:
- Decode photo
i. This depends only oni. - Apply k operations. CPU-bound, depends on
(i, j). - Encode and write the result. Depends on
(i, j).
A naive nested loop that opens the file in the inner loop decodes each photo n times. Instead, make the photo the unit of work:
- Decode photo
ionce. - For each chain
j, run it on a fresh copy of the decoded image. - Write the
nresults.
Tasks for different photos share no mutable state, so they can run in a process pool with no locking.
Key details
- Copy before each chain. An operation may mutate its input. Without a copy, chain
jcould corrupt the starting image for chainj+1. - Ordered application. Fold the operations left to right:
out = op(out). - Deterministic names. Use
img{i}_pipe{j}.pngfrom indices. Completion order, duplicate input paths, and scheduling then cannot cause collisions or nondeterminism. - Atomic writes. Save to a temporary path, then
os.replaceinto the final name. A crashed or retried task never leaves a half-written file under the real name. - Send chains to workers once. Use a pool initializer so the callables are pickled once per worker, not once per task.
- Ordered results.
pool.mapreturns results in input order, so the returned list is deterministic.
Complexity
Let D = decode cost, C = cost per operation, E = encode cost, P = number of workers.
- Total work:
O(m·D + m·n·k·C + m·n·E). Wall time is roughly this divided byP. The naive version paysm·n·Dfor decoding; this one paysm·D. - Memory:
O(P·S), withSthe size of one decoded image (the base copy plus one in-flight intermediate per worker). - Disk:
m·noutput files.
Code
import os
from concurrent.futures import ProcessPoolExecutor
from typing import Callable, List, Optional, Tuple
from PIL import Image
Op = Callable[[Image.Image], Image.Image]
Pipeline = List[Op]
_PNG_MODES = {"1", "L", "LA", "I", "P", "RGB", "RGBA"}
_PIPES: Optional[List[Pipeline]] = None
def output_name(i, j):
return f"img{i}_pipe{j}.png"
def _init(pipelines):
global _PIPES
_PIPES = pipelines
def _run(base, ops):
out = base.copy() # isolate from in-place ops
for op in ops: # strict order
out = op(out)
if not isinstance(out, Image.Image):
raise TypeError(f"{op!r} did not return an Image")
return out
def _save_atomic(img, path):
if img.mode not in _PNG_MODES:
img = img.convert("RGBA")
tmp = path + ".tmp"
img.save(tmp, format="PNG")
os.replace(tmp, path)
def _process_image(task: Tuple[int, str, str]):
i, path, out_dir = task
n = len(_PIPES)
try:
with Image.open(path) as f:
base = f.copy() # force full decode, once per photo
except Exception:
return [None] * n
res = []
for j, ops in enumerate(_PIPES):
p = os.path.join(out_dir, output_name(i, j))
try:
_save_atomic(_run(base, ops), p)
res.append(p)
except Exception:
res.append(None)
return res
def generate_outputs(image_paths, pipelines, output_dir, max_workers=None):
m, n = len(image_paths), len(pipelines)
if m == 0 or n == 0:
return []
os.makedirs(output_dir, exist_ok=True)
tasks = [(i, p, output_dir) for i, p in enumerate(image_paths)]
if max_workers == 1:
_init(pipelines)
rows = [_process_image(t) for t in tasks]
else:
w = max_workers or os.cpu_count() or 1
with ProcessPoolExecutor(w, initializer=_init,
initargs=(pipelines,)) as pool:
rows = list(pool.map(_process_image, tasks,
chunksize=max(1, m // (w * 4))))
return [p for row in rows for p in row] # index i*n + j
Edge cases
m == 0orn == 0: return an empty list.- Empty chain (
k == 0): output is a re-encoded copy of the input. - Missing or corrupt input: mark all
noutputs for that photo as failed; do not abort the job. - One chain raising: fail only that
(i, j); other chains on the same photo still run. - An operation returning a non-image: raise a clear
TypeError. - Modes PNG cannot store (e.g. CMYK): convert before saving.
output_dirmissing: create it.- Lambdas and closures cannot be pickled for a process pool: use module-level functions or
functools.partial, or fall back to a single worker.
Scaling and parallelization strategy
- Processes, not threads. The operations are CPU-bound and arbitrary user code, so threads would serialize on the GIL. Pillow releases the GIL in some C routines, but you should not depend on that.
- Per-photo granularity is the default. It amortizes decoding, bounds memory to roughly one decoded image per worker, and needs no inter-task coordination. Use a modest chunk size (about
m / (4P)) to balance scheduling overhead against load balancing. - Few photos, many chains (
m < P): per-photo tasks leave cores idle. Split into(photo, chain-block)tasks. This decodes a photo a few times, which is a fine price for utilization. Alternatively, decode once and share the pixels through shared memory. - Many photos, few chains: per-photo tasks are already ideal.
- Shared prefixes. If chains share leading operations (for example, the same resize), compute the common prefix once per photo using a trie of operations and branch from there. This can cut CPU work substantially but needs ops to be deterministic and pure.
- Beyond one machine. Shard photos across nodes (each node gets a disjoint subset of
i). Because names are index-based and writes are atomic, tasks are idempotent and can be retried safely. Keep inputs and outputs on shared or object storage, and prefetch the next photo while the current one is processing to overlap I/O with CPU. - I/O tuning. Decoding and encoding are I/O-heavy, so use a bounded queue with a few reader/writer threads feeding the compute processes if disk or network latency dominates. Choose a cheaper PNG compression level if encoding is the bottleneck.
Common mistakes
- Opening the file inside the inner loop (
m·ndecodes). - Forgetting to copy, so in-place operations leak between chains.
- Naming outputs by completion order or by source filename (collisions on duplicates, nondeterminism).
- Writing directly to the final filename, leaving corrupt files after a crash.
- Using threads for CPU-bound work and expecting a speedup.
- Re-pickling the full chain list with every task.