Library/Coding patterns that get asked/Building a small system

A pipeline of transforms, then make it parallel

100 min8 partsCoreFundamentalsChecked Nov 2026
Start the lessonShort steps, each with something to do
What you'll learn
  • Write a pipeline as data, each step a name and its arguments, run by a dict from name to function and one loop, and say what that gives you over a list of functions
  • Check the whole step list before anything runs, never change the input, and return a result that shares nothing with it
  • Run a batch where one bad item becomes that item's result and the rest still run, in input order, and tell a bad item from a bad step list
  • Run the batch on a ThreadPoolExecutor with results in input order, and prove with a barrier that the workers really overlap
  • Choose threads or processes from a measurement, say what can be pickled and sent to a worker process, and size the pool
  • Cut one item that is too big into bands, run the row-by-row steps on the bands and the rest on the whole, and answer the follow-ups on overlaps, bounded queues, generators, timeouts and retries
Part 1 of 8about 13 min
Steps

Image pipeline

Anthropic candidates report an image round, with layers the interviewer adds one at a time (1 report). Others were asked to speed it up with processes, and why processes rather than threads (2 reports). It starts like this:

An image is a list of rows, and each row is a list of (r, g, b) pixels from 0 to 255. A step is a tuple: a name, then its arguments, such as ("grayscale",) or ("rotate", 90).

Write apply(image, steps). Run the steps in order and return a new image, without changing the input. The steps are grayscale, which makes each pixel (y, y, y) with y = (299 * r + 587 * g + 114 * b) // 1000, rotate by 90, 180 or 270 degrees clockwise, resize, crop, and map, which runs a function on every pixel. Check every step before you run any, and raise ValueError for a bad one.

Call, on the 1 by 2 image [[(255, 0, 0), (0, 0, 255)]]Returns
apply(image, [("rotate", 90)])[[(255, 0, 0)], [(0, 0, 255)]]
apply(image, [("grayscale",)])[[(76, 76, 76), (29, 29, 29)]]
apply(image, [("spin", 1)])raises ValueError

Then the layers come: a batch of images where one bad image doesn't stop the others, then the batch on several threads, then one huge image split into bands and worked on in parallel. Each layer reuses the code before it, so your first version decides how hard the rest will be.

You don't write it yet. This lesson builds the same pattern on something smaller first, a table of sensor readings, and the practice problem at the end puts it back on images. At the end you solve the whole problem, level by level, in an interview simulation with a 60-minute timer.

Later it runs the work on a pool of threads, then adds processes: the same pool, used on work that keeps the CPU busy instead of work that waits.

A pipeline runs a list of steps in order, and each step returns a new table

Start with the small version: a table of sensor readings, with two glitches in it.

READINGS = [
    [21, 19, 23],
    # -40 is a sensor glitch
    [25, -40, 24],
    [22, 20, 99],       # so is 99
    [24, 21, 22],
]

A table in this lesson is a list of rows. Each row is a list of numbers, every row has the same length, and there's at least one row. Think of sensor readings: one row per hour, one column per sensor.

Predict

Clip every value into 0 to 40. What do the glitches -40 and 99 become?

Pick an answer above to see the rest

Write each step as a name and its arguments, not as a function

You could write the cleanup as a list of functions:

cleanup = [
    lambda t: clip(t, 0, 40),
    lambda t: sort_by(t, 1),
    lambda t: scale(t, 10),
    lambda t: head(t, 2),
]

Or as a list of steps, where each step is a tuple of a name and its arguments:

cleanup = [("clip", 0, 40), ("sort", 1), ("scale", 10), ("head", 2)]

Both give [[250, 0, 240], [210, 190, 230]]. The difference is what you can do with the list without running it:

With the list you want toA list of functionsA list of steps
print it in a log[<function <lambda> at 0x101a16ac0>, <function <lambda> at 0x1015ea2a0>, ...][('clip', 0, 40), ('sort', 1), ('scale', 10), ('head', 2)]
check it before runningthe arguments are hidden inside closuresevery name and argument is right there
save it as JSONTypeError: Object of type function is not JSON serializable[["clip", 0, 40], ["sort", 1], ["scale", 10], ["head", 2]]
send it to another processPicklingError: Can't pickle <function <lambda> at 0x101a16ac0>: attribute lookup <lambda> on __main__ failed63 bytes with pickle.dumps

A step list is a value. You can compare two of them, store one with a job, show one to a user, and send one to a worker process. That last one decides the design of the parallel version, later in this lesson.

In the editor, use the step list cleanup as a value. Write describe(steps), one log line for a step list, and from_json(text), which reads a step list back from JSON and makes each step a tuple again.

A dict from name to function and one loop run any step list

Each step name maps to a function that takes a table and returns a new one:

def scale(table, factor):
    return [[value * factor for value in row] for row in table]


def clip(table, low, high):
    return [[min(max(value, low), high) for value in row] for row in table]


def each(table, func):
    return [[func(value) for value in row] for row in table]


def transpose(table):
    return [list(column) for column in zip(*table)]


def sort_by(table, column):
    if column >= len(table[0]):
        raise ValueError(f"no column {column} in a table {len(table[0])} wide")
    return sorted(table, key=lambda row: row[column])


def head(table, n):
    return table[:n]


TRANSFORMS = {"scale": scale, "clip": clip, "map": each, "transpose": transpose, "sort": sort_by, "head": head}

TRANSFORMS is a dict from name to function. It's the hash maps lesson's O(1) lookup, used as a dispatch table: look up the name, then call what you find. One loop runs any step list:

def run(table, steps):
    for name, *args in steps:
        table = TRANSFORMS[name](table, *args)
    return table

name, *args splits each step into its name and a list of its arguments. Then *args in the call spreads that list back out.

Predict

For the step ("transpose",), what is args?

Pick an answer above to see the rest
Part 1 done
Part 2 of 8about 11 min
Checking

Check every step before you run any

A typo caught before the run costs one error, and caught during it, one per table

Here is a typo, ("srot", 0), as the third step after ("scale", 2) and ("clip", 0, 50). The batch is 1,000 tables of 100 rows by 10 columns. Two ways to handle it, timed, best of 3:

Predict

The third of three steps is a typo, and the batch has 1,000 tables. Checked per table, just before each step runs, how many times do the first two steps run?

Pick an answer above to see the rest

Two dicts say what each step needs: how many arguments, and which values pass

To check a step list before it runs, the code needs to know what each step expects.

ARITY = {"scale": 1, "clip": 2, "map": 1, "transpose": 0, "sort": 1, "head": 1}

RULES = {
    "scale": lambda factor: isinstance(factor, (int, float)),
    "clip": lambda low, high: isinstance(low, (int, float)) and isinstance(high, (int, float)) and low <= high,
    "map": callable,
    "transpose": lambda: True,
    "sort": lambda column: isinstance(column, int) and column >= 0,
    "head": lambda n: isinstance(n, int) and n >= 1,
}


for step in [("srot", 0), ("clip", 0), ("clip", 40, 0), ("head", 0), ("map", "x")]:
    try:
        check([step])
    except ValueError as error:
        print(error)
bad step: ('srot', 0)
bad step: ('clip', 0)
bad step: ('clip', 40, 0)
bad step: ('head', 0)
bad step: ('map', 'x')

An unknown name, a missing argument, a low above its high, a count of 0 and a map without a function: each one raised the same ValueError, with the step in the message.

The check needs two facts per step name: how many arguments it takes, and what makes them valid. Both are data too, so a new step adds one entry to each dict.

ARITY.get(name) returns None for a name it doesn't know, and None never equals a count. So one comparison catches both an unknown name and a wrong count. RULES[name](*args) runs only when the name is known and the count is right, because or stops at the first side that's true.

A problem that depends on the data is the step's own job, when it runs

("sort", 3) is a fine step for a table four columns wide, and a bad one for a table three wide. The width can also change along the way. READINGS has 3 columns:

StepsThe width as they run
[("transpose",), ("sort", 3)]3 columns, then 4, then sorted
[("sort", 3)]3 columns: ValueError, no column 3 in a table 3 wide

The check catches what the step list alone can tell you. What depends on the data at that point, the step itself raises when it runs.

The editor holds ARITY and RULES from above. Write check(steps), so it raises ValueError, with the step in the message, for an unknown name, a wrong count, or values that RULES rejects.

Copy each row once, so the result shares nothing with the input

Each step returns a new table. Make sure it really is new.

table = [[21, 19, 23], [25, -40, 24]]
# what ("sort", 1) does
out = sorted(table, key=lambda row: row[1])
out[0][0] = 99
print(table)
Predict

out = sorted(table, ...), then out[0][0] = 99. Does the caller's table change?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 2 done
Part 3 of 8about 7 min
Batches

One bad table doesn't stop the batch

Catch the error per table, and put it in that table's slot

Now many tables, one per day, through the same steps. Tuesday's table has only two columns, because a sensor was offline:

monday = [[21, 19, 23], [25, 18, 24]]
tuesday = [[20, 22], [19, 21]]
wednesday = [[23, 20, 30], [22, 21, 25]]

The obvious loop is [apply(t, steps) for t in tables]. With [("sort", 2)], it raises ValueError: no column 2 in a table 2 wide at Tuesday. Monday's finished result is lost with it, and Wednesday never runs. On a batch of ten thousand files, one bad file would cost you all of them.

So catch per table, and put what went wrong where the result would have gone:

def run_batch(tables, steps):
    check(steps)
    results = []
    for table in tables:
        try:
            results.append(apply(table, steps))
        except Exception as error:
            results.append(error)
    return results

On the three days with [("sort", 2)], each table gets its own slot in the result:

TableShapeIts slot in the result
monday2 x 3[[21, 19, 23], [25, 18, 24]]
tuesday2 x 2ValueError('no column 2 in a table 2 wide')
wednesday2 x 3[[22, 21, 25], [23, 20, 30]]

Result i belongs to table i, so the caller needs no ids to match them up. isinstance(result, Exception) tells a failure from a table.

Keep the exception itself, not None. It says what went wrong, and the caller can log it, retry that table or raise it. Some codebases return (ok, value) pairs instead. Either works, as long as the failure keeps its reason.

A map step that divides by a zero reading works the same way. It gives ZeroDivisionError('division by zero') in that table's place, and the other tables come out normally.

Catch Exception, not everything, so Ctrl-C still stops the batch

Predict

Is KeyboardInterrupt, what Ctrl-C raises, a kind of Exception?

Pick an answer above to see the rest

A bad step list is one mistake, so it raises once, before the loop

The first line of run_batch, check(steps), sits outside the loop on purpose. A bad step list is one mistake, made once, by whoever wrote the steps. It should raise once, before anything runs.

Leave that line out and apply still checks, but now inside the try, so the step list's ValueError is caught per table. Two tables with [("sort", -1)] came back as [ValueError("bad step: ('sort', -1)"), ValueError("bad step: ('sort', -1)")]. The caller sees what looks like two bad tables, and one mistake is reported once per table.

apply checking again inside the loop is harmless: O(s) per table, next to work that touches every value.

Cost. O(n r c s) time for n tables of r by c, through s steps that touch every value. Memory holds all n results, which the caller asked for.

In the editor, write run_batch(tables, steps) yourself. check and apply are the ones from the lesson. A bad table fills its own slot, and a bad step list raises before any table runs.

CheckpointErrors stay with their table

Write run_batch(tables, steps). Return one result per table, in order: the new table, or the exception that stopped that table. A bad step list is different: it raises ValueError before any table runs. check(steps) and apply(table, steps) are defined as in the lesson.

Part 3 done
Part 4 of 8about 12 min
Pools

Run many tables at once, with results in input order

pool.map gives results in input order, and as_completed gives them as they finish

Here are three items that sleep 0.3, 0.1 and 0.2 seconds:

def slow(item):
    name, seconds = item
    time.sleep(seconds)
    return name


items = [("a", 0.3), ("b", 0.1), ("c", 0.2)]

concurrent.futures.ThreadPoolExecutor(max_workers=n) is a thread pool: it runs the calls you hand it on at most n threads of its own. pool.submit(fn, x) returns a future at once. A future is a placeholder for that call's result, and future.result() waits for the call and returns its value.

Four ways to collect the results, with 3 workers:

Predict

Three calls sleep 0.3, 0.1 and 0.2 s on 3 workers. Submitted all at once, about how long does the batch take? And submitted and waited on one at a time?

Pick an answer above to see the rest

An exception inside a worker stops pool.map at that item, so catch it inside the worker

The future keeps the exception, and pool.map raises it in your loop when the loop reaches that item. Measured on items 0 to 7 with 2 workers, each item sleeping 50 ms and returning k * 10, except item 2, which raises ZeroDivisionError:

Predict

pool.map on items 0 to 7, 2 workers, and item 2 raises. Which items never run?

Pick an answer above to see the rest

A barrier with a timeout proves that the workers overlap

Correct results don't show that the tables ran at the same time. A test can show that too.

def test_tables_run_at_the_same_time():
    barrier = threading.Barrier(3, timeout=2)
    lock, first = threading.Lock(), set()

    # each table holds one value, k
    def meet(value):
        with lock:
            # the first value of this table?
            arrived = value not in first
            first.add(value)
        if arrived and value < 3:
            # tables 0, 1 and 2 must all be running
            barrier.wait()
        return value

    tables = [[[k, k], [k, k]] for k in range(6)]
    assert run_batch(tables, [("map", meet)], workers=3) == tables
    assert not barrier.broken

A batch that runs one table at a time returns exactly the right results, so checking the results can't catch it. This test makes the workers prove it from inside.

A threading.Barrier(3) blocks each thread that calls wait() until 3 threads are waiting, then lets them all go. With a timeout, a barrier that never fills raises BrokenBarrierError instead of hanging.

Predict

Barrier(3, timeout=2), but the batch runs one table at a time. What does table 0's wait() do?

Pick an answer above to see the rest
Part 4 done
Part 5 of 8about 19 min
Threads or processes

On standard CPython, threads speed up waiting, and processes speed up Python computing

Measured: 4 threads did nothing for Python computing and cut the waiting to a quarter

Two kinds of work, eight tables of 100 rows by 100 columns, three ways each:

  • Computing. Every value goes through heavy, 200 rounds of Python arithmetic. It stands in for real work on each value, like parsing. Then a clip.
  • Waiting. Each table first sleeps 0.1 s. It stands in for a read from a slow disk or the network. Then a cheap clip.
# in tables.py, next to this lesson's other functions
def heavy(value):
    for _ in range(200):
        value = (value * 31 + 7) % 1_000_003
    return value


def to_fahrenheit(celsius):
    return celsius * 9 / 5 + 32

The script runs each kind of work in a plain loop, on 4 threads and on 4 processes:

import time
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

from tables import apply, heavy


def compute(table):
    return apply(table, [("map", heavy), ("clip", 0, 500_000)])


def wait(table):
    time.sleep(0.1)
    return apply(table, [("clip", 0, 500)])


if __name__ == "__main__":
    tables = [[[(k * 7 + i * 100 + j) % 997 for j in range(100)] for i in range(100)] for k in range(8)]
    for work in (compute, wait):
        start = time.perf_counter()
        loop = [work(t) for t in tables]
        print(work.__name__, "loop", time.perf_counter() - start)
        for Pool in (ThreadPoolExecutor, ProcessPoolExecutor):
            start = time.perf_counter()
            with Pool(max_workers=4) as pool:
                assert list(pool.map(work, tables, timeout=30)) == loop
            print(work.__name__, Pool.__name__, time.perf_counter() - start)

Medians of 3 runs of that script, Python 3.12, on a 10-core laptop, pool start-up included:

Predict

Each of eight tables first waits 0.1 s. A plain loop took 0.86 s. About how long on 4 threads?

Pick an answer above to see the rest

The GIL lets one thread at a time run Python bytecode, and a thread that waits doesn't hold it

The reason is the GIL, the global interpreter lock: in standard CPython, only one thread at a time runs Python bytecode. Four threads doing Python arithmetic take turns. A thread that's waiting, on I/O or in time.sleep, lets the GIL go, so four sleeps overlap.

4 threads, over time
Python arithmetic, thread 1
AAAA
thread 2
BBBB
thread 3
CCCC
thread 4
DDDD
each waiting 0.1 s, thread 1
thread 2
thread 3
thread 4
running Python, holding the GILwaiting, which holds no GIL

With one GIL, threads doing arithmetic take turns. Threads that wait all wait at once.

Some C code lets go of the GIL while it works, too. The Python glossary names extension modules that release it for heavy work such as compression or hashing. Hashing is easy to try:

# four 2 MB inputs
blobs = [os.urandom(2 << 20) for _ in range(4)]


def digest(blob):
    sha = hashlib.sha256()
    for _ in range(25):
        # 50 MB of hashing per call
        sha.update(blob)
    return sha.hexdigest()

The four calls took 0.090 s in a loop and 0.023 s on 4 threads, medians of 5. Work that runs in C code like that gets the speedup on threads, with no processes needed.

All of this is the standard CPython build, the one these timings ran on. Since Python 3.13 there is also a separate free-threaded build, with the GIL disabled, where threads can run Python bytecode in parallel. Python 3.14 made it officially supported, but it's still optional. So the GIL is still there unless you choose that build.

In the editor, write thread_time(items, seconds_each, workers, holds_gil): the time a thread pool takes. Work that holds the GIL adds up, and work that waits runs in rounds of workers items.

A worker process costs start-up, and pickling every item both ways

Each worker in a ProcessPoolExecutor is a separate Python with its own GIL, which is the point. The price is that only objects that can be pickled can go to a worker or come back. Everything crosses as bytes, by pickle:

One table to a worker process and backInteractive
the table, in the main process.

Start-up. On macOS a worker starts by spawn: a fresh Python interpreter that imports your module. Spawn is the default on Windows and macOS. Starting 4 workers, running one trivial call on each and shutting down took 0.101 s, median of 3.

On Linux, Python up to 3.13 started workers by fork, which copies the running process and is quicker. Since 3.14 the default there is forkserver: one server process starts fresh, and each worker is forked from it. The 3.14 docs give the reason: it keeps the speed and avoids common problems with forking a process that runs threads.

Pickling every item, both ways. One 100 by 100 table pickles to 27,826 bytes, and a round trip took 0.218 ms, against about 86 ms of heavy work per table. That's cheap.

When the work per item is small, it isn't. 20,000 one-row tables through two cheap steps, ("scale", 2) and ("clip", 0, 50), took 0.036 s in a loop and 1.803 s on 4 processes. Raising chunksize, which sends items in groups, brought it to 0.094 s, still slower than the loop. The docs say a large chunksize can make very long inputs much faster than the default of 1. When each item is cheap, don't send it anywhere.

In the editor, put those costs into numbers. process_time is the start-up plus rounds of workers items, each item paying its work and its pickling. faster compares that with a plain loop, which pays only the work.

A function can go to a process only if it is a top-level def

Pickle sends a function as its module and its name, and the worker imports it. So the pickle docs list only functions that can be reached from the top level of a module: built-in ones, and ones defined there with def, not lambda. Tried one at a time with pickle.dumps:

ObjectResult
[("clip", 0, 40), ("sort", 1), ("scale", 10), ("head", 2)]63 bytes
[("map", to_fahrenheit), ("head", 1)], with to_fahrenheit a top-level def in tables.py62 bytes: the names tables and to_fahrenheit, not the code
a lambdaPicklingError: Can't pickle <function <lambda> at 0x...>: attribute lookup <lambda> on __main__ failed
a function defined inside another functionAttributeError: Can't get local object 'make.<locals>.f'
threading.Lock()TypeError: cannot pickle '_thread.lock' object
a generatorTypeError: cannot pickle 'generator' object
an open fileTypeError: cannot pickle 'TextIOWrapper' instances

This is where steps as data pays off. The worker gets names and numbers, looks each name up in its own copy of TRANSFORMS, and runs it. A list of lambdas can't make the trip at all. Submitting apply(table, [("map", lambda v: v * 2)]) to a process pool raised _pickle.PicklingError from future.result(), while [("map", abs)] ran fine.

The same rule covers the function you hand the pool. A worker imports your main module, so the workers must be able to import it. Keep the work in top-level functions, and start the pool under if __name__ == "__main__":, as the script above does. Then importing the module doesn't start pools of its own.

That's also why this lesson's checkpoints use threads. They run your code from a string, which a worker process can't import.

In the editor, write can_send(obj): True when pickle.dumps(obj) works. The rows of the table above are your test cases, and the failures raise different exception types.

About one process per core for computing, and more threads for waiting

For computing, use about one process per core. The same eight computing tables took 0.780 s on 1 process, 0.428 s on 2 and 0.261 s on 4. Past the number of cores, extra processes take turns, and they add start-up and memory.

os.cpu_count() gives the number of logical CPUs. It printed 10 on this laptop. In Python 3.12, ProcessPoolExecutor() with no max_workers uses that number. Each worker is a whole Python process that holds its own copy of what you send it, so memory can set the limit before cores do.

For waiting, use more: enough to keep the waits overlapped. That's the number of calls you want to start per second times how long each one waits, which is Little's law. For 50 reads a second that each wait 0.2 s, that's about 10 threads.

ThreadPoolExecutor() defaults to min(32, os.cpu_count() + 4) in 3.12. The docs give the plus 4 as a way to keep at least 5 workers for I/O-bound tasks. Since 3.13, both pools count os.process_cpu_count() instead of os.cpu_count(): the CPUs this process is allowed to run on, which can be fewer than the machine has.

In the editor, write process_count(cpus, memory_gb, per_worker_gb), one process per CPU unless memory runs out first, and thread_count(per_second, wait_seconds), by Little's law.

Answer "threads or processes?" with your measurements, then the costs

Everything in this part feeds one follow-up question, and the numbers you measured are the answer.

Watch · 26 min

ProcessPoolExecutor with submit, as_completed and map, then a batch of high-resolution photos processed on a process pool, one photo per worker. That's the batch level of the practice problem done with processes and real images.

Python Multiprocessing Tutorial: Run Code in Parallel Using the Multiprocessing Module · Corey Schafer · Sep 2019YouTube
Part 5 done
Part 6 of 8about 13 min
Bands

Cut one huge table into bands of rows

Start a band at every multiple of band_rows, and stitch the bands back in order

A batch gives a pool something to share out. One huge table doesn't: a pool of 4 with one item runs it on one worker. So cut the table into bands, runs of consecutive rows, and share out the bands.

T = [[21, 19, 23], [25, -40, 24], [22, 20, 99], [24, 21, 22], [20, 18, 21]]

Cutting, running and stitching are one line each. group is the list of steps that runs on the bands:

bands = [table[top:top + band_rows] for top in range(0, len(table), band_rows)]
# one band at a time, for now
done = [run(band, group) for band in bands]
table = [row for band in done for row in band]
Predict

T has 5 rows, cut into bands of band_rows = 2. How many bands, and how big is the last?

Pick an answer above to see the rest

A step can run on bands with no overlap only if each output row depends only on its own input row

A step like that is row-local. scale, clip and map change each value on its own, so they are row-local. transpose, sort and head aren't. Here is each of them run per band on T, in bands of 2, with the bands stitched back:

StepWhole tablePer band, stitched
("sort", 1)column 1 reads -40, 18, 19, 20, 21column 1 reads -40, 19, 20, 21, 18
("head", 3)3 rowsall 5 rows, since each band kept its own first 3
("transpose",)3 rows of 59 rows of 2 or 1

The sort only sorted within each band.

The dangerous steps look row-local and aren't. Normalizing divides every value by the table's largest value:

def normalize(table):
    top = max(max(row) for row in table)
    return [[round(value / top, 2) for value in row] for row in table]

It touches each value on its own, but the divisor comes from the whole table. On bands, each band divided by its own largest value. The first row came out [0.84, 0.76, 0.92] instead of [0.21, 0.19, 0.23]. There was no error, just wrong numbers. Before a step goes on bands, ask what else it reads.

In the editor, write same_on_bands(step, table, band_rows): run step on each band of table, stitch, and compare with step on the whole table. To try it, the editor holds three steps as plain functions of a table: clip_step, sort_step and normalize.

groupby splits the steps into runs, and only the row-local runs go on bands

Some steps can run on bands and some can't, so split the step list where that changes.

from itertools import groupby

ROW_LOCAL = {"scale", "clip", "map"}


def to_fahrenheit(celsius):
    return celsius * 9 / 5 + 32


steps = [("clip", 0, 40), ("map", to_fahrenheit), ("sort", 1), ("scale", 10), ("head", 3)]
for local, run_of_steps in groupby(steps, key=lambda step: step[0] in ROW_LOCAL):
    print(local, [step[0] for step in run_of_steps])
True ['clip', 'map']
False ['sort']
True ['scale']
False ['head']

A run here is a stretch of consecutive steps of the same kind. itertools.groupby starts a new group each time the key changes, and the key is whether a step is row-local. Each True run goes on bands. Each False run goes on the whole table, stitched together first:

The steps split into runsInteractive
T, 5 x 3.

Grouping runs, not single steps, means clip then map cut and stitch once, not twice. Don't sort the steps first, as the usual groupby recipe does: the order of the steps is the meaning of the pipeline.

Put together, with the bands on a thread pool, in_bands on T in bands of 2 with these steps returned [[770.0, 320.0, 752.0], [680.0, 644.0, 698.0], [698.0, 662.0, 734.0]]. That's the same as apply.

In the editor, write runs(steps, row_local): the groupby loop above, returned as a list of (local, names) pairs.

On one 400-row table, bands on threads were no faster, and on processes about twice as fast

One table of 400 rows by 100 columns, steps [("clip", 0, 900), ("map", heavy), ("sort", 1), ("map", to_fahrenheit), ("head", 300)], bands of 100 rows, median of 3:

RunTime
apply alone0.347 s
bands on 4 threads0.354 s
the same function with a ProcessPoolExecutor of 4 in place of the thread pool, start-up included0.169 s

Threads don't beat the GIL on bands either. On processes, each band is pickled out and back. Only the steps in the list, names and top-level functions, travel with it.

In the editor, in_bands checks the steps, copies the rows and walks the runs from groupby, with ROW_LOCAL and run from above. The whole-table branch is done. Finish the row-local branch: cut, run group on each band with pool, and stitch.

CheckpointBands on the pool, stitched in order

Finish the row-local branch of in_bands. Cut table into bands of band_rows rows. The last band can be shorter. Run group on every band with pool, so up to workers bands run at once, and stitch the bands back in order. The result must equal apply(table, steps).

Part 6 done
Part 7 of 8about 7 min
The worked example

A worked example: cleaning log files in parallel

Clarify the prompt, then say the design before the code

The prompt: you get log files, each a list of lines, and a recipe of cleanup steps such as [("strip",), ("lower",), ("drop_blank",), ("dedupe",)]. Return the cleaned files, in order. Run up to 4 files at a time. A file that can't be cleaned must not stop the others, and a recipe with a mistake in it should be rejected up front.

Clarify first, out loud:

  • Which steps exist, and what arguments does each take?
  • Does dedupe keep the first copy of a line, and the order? Yes.
  • Should a failed file's slot hold the error, or be dropped? Hold the error, so the results line up with the files.
  • May the input be changed? No.
  • Are the files already in memory, or do they have to be read? In memory, for now.

Design, before code. The recipe is data: a name and its arguments per step. An ARITY dict checks it, and a TRANSFORMS dict runs it. Each file is independent, so the batch shape fits: check the recipe once, clean each file inside a try, and use pool.map for input order.

from concurrent.futures import ThreadPoolExecutor

ARITY = {"strip": 0, "lower": 0, "replace": 2, "drop_blank": 0, "dedupe": 0}

TRANSFORMS = {
    "strip": lambda lines: [line.strip() for line in lines],
    "lower": lambda lines: [line.lower() for line in lines],
    "replace": lambda lines, old, new: [line.replace(old, new) for line in lines],
    "drop_blank": lambda lines: [line for line in lines if line],
    "dedupe": lambda lines: list(dict.fromkeys(lines)),
}


def check(recipe):
    for step in recipe:
        name, *args = step
        if ARITY.get(name) != len(args) or not all(isinstance(arg, str) for arg in args):
            raise ValueError(f"bad step: {step!r}")


def clean(lines, recipe):
    lines = list(lines)
    for name, *args in recipe:
        lines = TRANSFORMS[name](lines, *args)
    return lines


def clean_all(files, recipe, workers=4):
    check(recipe)

    def one(lines):
        try:
            return clean(lines, recipe)
        except Exception as error:
            return error

    with ThreadPoolExecutor(max_workers=workers) as pool:
        return list(pool.map(one, files))

Say two things while you write it. dedupe is dict.fromkeys, from the hash maps lesson: the first copy of each line, in order. And list(lines) is a full copy here, because a line is a string, and strings can't be changed in place. With tables, the rows were lists, and each needed its own copy.

In the editor, write two of the recipe's steps as plain functions: drop_blank(lines) and dedupe(lines).

Trace one file step by step, then run the batch and test it

Before you run the batch, trace one file by hand.

files = [
    ["  Disk OK ", "", "disk ok", "Fan: ERROR"],
    ["Boot", None, "boot"],
    ["   ", "temp: error", "Temp: Error  "],
]

The first file, step by step:

AfterLines
start[' Disk OK ', '', 'disk ok', 'Fan: ERROR']
("strip",)['Disk OK', '', 'disk ok', 'Fan: ERROR']
("lower",)['disk ok', '', 'disk ok', 'fan: error']
("drop_blank",)['disk ok', 'disk ok', 'fan: error']
("dedupe",)['disk ok', 'fan: error']

clean_all(files, recipe) returned [['disk ok', 'fan: error'], AttributeError("'NoneType' object has no attribute 'strip'"), ['temp: error']]. The second file has a line that isn't text, so its slot holds the error, and the third file is cleaned anyway.

The recipe [("strip",), ("lowercase",)] raised ValueError: bad step: ('lowercase',) before any file ran. So did ("replace", "error"), one argument short. files[0] was unchanged afterwards.

Test it with what this lesson's checkpoints test:

  • a file that fails in the middle of the batch
  • a bad recipe with a spy step in front of it
  • results in order, with the first file held back
  • a barrier to prove the files overlap

On these files, threads tied the loop and processes lost, so say so

Eight files of 20,000 lines each, about 4.8 MB of text, made by [[f" Host-{f} Event {i % 3000} error code {i % 7} " if i % 9 else "" for i in range(20_000)] for f in range(8)]. The recipe was [("strip",), ("lower",), ("replace", "error", "ERROR"), ("drop_blank",), ("dedupe",)]. Median of 3:

RunTime
a plain loop0.030 s
4 threads0.030 s
4 processes0.094 s

The string methods run under the GIL, so threads don't help. The whole job costs less than starting the processes and pickling the lines.

Say so: here the loop wins. Threads earn their place only once the files come off slow storage, where each worker spends its time waiting.

For a process version, one has to move to the top level with the recipe as an argument: pool.map(clean_one, files, [recipe] * len(files)). A function defined inside clean_all can't be pickled. The lambdas in TRANSFORMS are fine either way: they never travel, because the worker imports them with the module.

A file too big for one worker splits into bands of lines, but dedupe needs the whole file

strip, lower, replace and drop_blank look at one line at a time, so they can run on bands. dedupe can't: a line in band 3 may repeat one in band 1. So it runs on the stitched whole, or it merges each band's first-seen lines in band order.

In the editor, write that merge, merge_firsts(bands). Each band already holds its own first-seen lines, and you return the first copy of each line across all bands, in band order.

Part 7 done
Part 8 of 8about 18 min
Follow-ups

What interviewers ask next

Why processes, and how many: lead with whether the work holds the GIL

Say first whether the work holds the GIL. Then the start-up and pickling cost. Then about one process per core for computing. The numbers are in the section on threads and processes.

Follow-up: a blur reads the rows next to it, so each band needs an overlap

The practice problem has no step like this. A blur is the likely follow-up to level 4.

def smooth(table):
    out = []
    for i in range(len(table)):
        # the row above, this row, the row below
        near = table[max(0, i - 1):i + 2]
        out.append([sum(column) // len(near) for column in zip(*near)])
    return out


S = [[0], [30], [0], [30], [0], [30]]
print(smooth(S))
print(smooth_in_bands(S, 2, overlap=0))
print(smooth_in_bands(S, 2, overlap=1))
[[15], [10], [20], [10], [20], [15]]
[[15], [15], [15], [15], [15], [15]]
[[15], [10], [20], [10], [20], [15]]

smooth turns each value into the mean, rounded down, of itself and its neighbors above and below, so each output row reads up to three input rows. A blur on an image is the same kind of step. It isn't row-local, so the groupby split runs it on the whole table.

Predict

smooth reads one row above and one below. Bands of 2 rows: how many extra rows must each band read on each side?

Pick an answer above to see the rest

A million tables: pool.map reads every item first, so keep a window of futures

In Python 3.12, pool.map reads its whole input before it hands back the first result: the docs say it collects the iterables immediately, not lazily. Fed a generator of 200 records of 20 KB each, pool.map on 4 threads pulled all 200 before the first result came back. Memory peaked at 4.41 MB, by tracemalloc. With a million records, that's every record in memory at once, plus a future for each.

Keep a window of futures instead. It submits until limit calls are pending, then hands back the oldest result before it reads the next record. Here is the window with limit = 3, oldest future on the left:

StepThe window, oldest first
read r0, r1 and r2, submit eachf0, f1, f2: full
hand back f0's resultf1, f2
read r3, submit itf1, f2, f3: full
hand back f1's resultf2, f3
read r4, submit itf2, f3, f4

The results stay in input order, and at most limit records are held. The measurement, with a counter in the generator:

pulled = 0


def records(n, size):
    global pulled
    for i in range(n):
        pulled += 1
        yield bytes([i % 256]) * size


def work(record):
    time.sleep(0.002)
    return len(record)


with ThreadPoolExecutor(max_workers=4) as pool:
    # or pool.map(work, records(200, 20_000))
    results = bounded_map(pool, work, records(200, 20_000), 8)
    first = next(results)
    print(pulled)

pool.map printed 200, and bounded_map with limit=8 printed 8. Memory peaked at 0.19 MB against 4.41 MB, and both runs took 0.152 s in all.

Python 3.14 builds this into Executor.map: a new buffersize argument limits how many submitted calls can wait with results not yet handed back. The other classic shape is a reader thread that feeds workers through queue.Queue(maxsize=n). A put into a full queue blocks until a worker takes an item out. Either way, a slow consumer slows the reader down instead of letting memory grow.

In the editor, write the generator bounded_map(pool, fn, items, limit), with the window of futures in a deque.

A chain of generators moves each item through every step before it reads the next

Some inputs are too big to hold at all, like a log that keeps growing. Generators handle those one item at a time.

from collections import Counter


def read(n):
    for i in range(n):
        yield f"  Sensor-{i % 7} reading {i} OK  \n" if i % 5 else "\n"


stripped = (line.strip() for line in read(20_000))
kept = (line for line in stripped if line)
lowered = (line.lower() for line in kept)
counts = Counter(line.split()[0] for line in lowered)

A generator produces one item at a time, when it's asked: a function with yield, or a comprehension in parentheses. Building the chain does no work. No line is read until Counter asks for the first item, and then that line goes through every stage before the next one is read.

Predict

The same 20,000-line pipeline, once with a list at each stage and once with a chain of generators. The lists peaked at 3,844 KB. About how much did the generators take?

Pick an answer above to see the rest

A timeout on result() stops your waiting, not the call

A step that hangs needs a timeout. Know what the timeout actually stops.

with ThreadPoolExecutor(max_workers=1) as pool:
    future = pool.submit(time.sleep, 0.5)
    # raises TimeoutError
    future.result(timeout=0.1)
Predict

result(timeout=0.1) on a call that sleeps 0.5 s raises TimeoutError at 0.1 s. When does leaving the with block finish?

Pick an answer above to see the rest

Retry only what might succeed next time

A timeout leaves you a choice: try the call again, or give up on it.

Retry a timeout, a dropped connection or a busy server. Don't retry a ValueError from a bad step or bad data, which fails the same way every time.

Cap the attempts. Wait longer each time, with some randomness, so retries don't arrive together. Record which tables gave up.

The steps here are pure functions of their input, so running one twice is safe. A step that writes somewhere has to be written so that doing it twice does no harm.

In the editor, write retry(fn, attempts, retry_on), the capped retry this step describes. It retries only the exception types in retry_on. flaky is a test function that times out twice and then answers.

A cache that the workers share needs a lock

A Netflix candidate reported designing a multi-threaded cache (1 report). If workers share a cache of finished tables, it needs a lock, and in an LRU cache even a read is a write. The caches lesson measures what breaks without one.

The tests to write: input order, errors in place, a bad list before a spy, and a barrier

Write the ones in this lesson:

  • results in input order, with the slow item first
  • an error that stays with its item
  • a bad step list that raises before a spy step runs
  • a barrier with a timeout that proves the workers overlap

Every wait has a timeout, so a broken version fails in seconds instead of hanging the test run.

The practice problem, start to finish

That's every piece the practice problem needs. It asks for every level from the start of the lesson, from a blank file, and the interviewer follows up after each one.

Check yourself
6 questions
  1. 1.On standard CPython, a pure-Python function that only computes runs on 8 items. You switch from a plain loop to ThreadPoolExecutor(max_workers=4). What happens to the wall time?

  2. 2.You collect a thread pool's results with [f.result() for f in as_completed(futures)]. The first table is the slowest. What do you get?

  3. 3.Which step list can a ProcessPoolExecutor send to a worker?

  4. 4.A batch of 1,000 tables runs a step list whose third step is a typo, ("srot", 0). What should the batch do?

  5. 5.One huge table is cut into bands of rows that run in parallel. Which step can run on each band separately and still give the same answer as on the whole table?

  6. 6.You call pool.map(work, records()), where records() is a generator of 200 records, on 4 threads. How many records has the generator produced when the first result comes back?

Where this shows up

The reports behind this lesson, each with its source.

Crawler question (candidate comment, Feb 2024): implement a batch-processing version of a crawler with processes or threads.

Candidate report·Blind (candidate comment)·2024-02-16Source

Practice

Sources (12)
  1. concurrent.futures: Launching parallel tasks · Python 3.12 documentation · Oct 26, 2026
    “If a fn call raises an exception, then that exception will be raised when its value is retrieved from the iterator.”
  2. concurrent.futures: Executor.map · Python 3.14 documentation · Nov 10, 2026
    “unless a buffersize is specified to limit the number of submitted tasks whose results have not yet been yielded”
  3. pickle: What can be pickled and unpickled? · Python 3.12 documentation · Oct 26, 2026
    “functions (built-in and user-defined) accessible from the top level of a module (using def, not lambda)”
  4. multiprocessing: Contexts and start methods · Python 3.12 documentation · Oct 26, 2026
    “The default on Windows and macOS.”
  5. multiprocessing: Contexts and start methods · Python 3.14 documentation · Nov 10, 2026
    “On POSIX platforms the default start method was changed from fork to forkserver to retain the performance but avoid common multithreaded process incompatibilities.”
  6. Glossary: global interpreter lock · Python 3.14 documentation · Nov 10, 2026
    “The mechanism used by the CPython interpreter to assure that only one thread executes Python bytecode at a time.”
  7. What's New In Python 3.14: Free-threaded Python is officially supported · Python 3.14 documentation · Nov 10, 2026
    “This is the start of phase II where free-threaded Python is officially supported but still optional.”
  8. copy: Shallow and deep copy operations · Python 3.12 documentation · Oct 26, 2026
    “A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.”
  9. threading: Barrier objects · Python 3.12 documentation · Oct 26, 2026
    “This class provides a simple synchronization primitive for use by a fixed number of threads that need to wait for each other.”
  10. itertools.groupby · Python 3.12 documentation · Oct 26, 2026
    “Make an iterator that returns consecutive keys and groups from the iterable.”
  11. queue: A synchronized queue class · Python 3.12 documentation · Oct 26, 2026
    “Insertion will block once this size has been reached, until queue items are consumed.”
  12. os.cpu_count · Python 3.12 documentation · Oct 26, 2026
    “Return the number of logical CPUs in the system.”