Lesson · Capstone Core-Python Skills
Build a Concurrent Data Processor
150 min readBuild a Concurrent Data Processor
This capstone builds a data-processing pipeline and forces you to choose among threads, processes, interpreters, and asyncio based on workload characteristics, failure behavior, and resource limits.
Learning goals
- Write the sequential baseline for a file batch and measure it before adding any concurrency.
- Choose threads, processes, interpreters, or asyncio from the workload's bottleneck and defend the choice with the pipeline's stages.
- Place a bounded handoff between producers and workers, and explain how the bound provides backpressure instead of memory growth.
- Define per-item failure behavior (abort, retry, quarantine, report) and get worker exceptions back to the coordinator.
- Shut workers down cleanly on success, failure, and cancellation, closing files, executors, and queues.
Mental model
The choice of execution model follows the workload, not the other way around: blocking I/O gives threads something useful to do, CPU-heavy work needs processes or isolated interpreters to get around the GIL, and asyncio fits many small cooperative waits. Whatever the model, the pipeline keeps the same stages and the same handoffs, and the comparison that matters is against the measured sequential baseline, because concurrency only pays when the work it overlaps is larger than the coordination it adds.
Mental model
read it top to bottom
workload: what is the batch made of? ↓ blocking I/O (files, network) threads over a bounded queue ↓ CPU-heavy work (parsing, hashing) processes or isolated interpreters ↓ thousands of small concurrent waits asyncio tasks ↓ in every case measure the baseline first; the model follows the bottleneck
Core idea
Concurrency in this capstone is an engineering trade, not a feature: every model (threads, processes, interpreters, asyncio) moves work off the main path at a cost, and the pipeline's shape decides where that cost lands. The discipline is to build the sequential baseline first, bound the handoff so memory cannot grow without limit, decide what one failing item does to the batch, and only then measure whether the concurrent version actually beats the baseline on the real workload.
File processing
A production file pipeline separates discovery, reading, parsing, transformation, and output so each stage can be tested and measured independently. Stream large files and define how one bad file affects the rest of the batch.
Queues
A queue creates an explicit handoff point between producers and consumers. Bounded queues also provide backpressure, while thread/process/async queue types differ in how they synchronize and move data.
Threads / processes / async
Choose the execution model from the workload: threads are often effective for blocking I/O, processes or isolated interpreters can suit CPU work, and asyncio suits large numbers of cooperative asynchronous I/O operations.
Error handling
Define whether one item failure aborts the batch, is retried, is quarantined, or is reported while other work continues. Concurrent systems also need a way to surface worker exceptions to the coordinator.
Resource cleanup
Workers must close files, executors, queues, temporary resources, and network clients on success, failure, and cancellation. Context managers and structured concurrency make ownership explicit.
Logging
Log lifecycle events, failures, retries, and high-level progress with enough context to identify the work item. Avoid logging secrets or producing one log event for every tight-loop operation unless diagnostics require it.
Profiling
Profile the sequential baseline and the concurrent version separately. Measure useful throughput, CPU use, wait time, serialization cost, and queueing so concurrency overhead is visible.
Walkthrough
- The left column of the diagram is the sequential core: discover files, then read and parse each one. Those stages exist in the baseline before any concurrency is added, which is what makes the later speedup measurable.
- The bounded work queue in the middle is the handoff: producers put work items in, workers take them out, and the bound is what applies backpressure when reading and parsing outpace processing.
- Errors and results return on a separate edge, which is the diagram's way of saying one failed file needs a defined outcome (reported, quarantined, retried) instead of killing workers silently.
- The comment below the diagram states the model-selection rule: threads for blocking I/O, processes or interpreters for CPU-heavy work, asyncio for many async I/O operations. Predict before building: for local file parsing, which stage is the bottleneck, and which model the rule points to.
Experiments to try
- Write the sequential baseline over a directory of text files (count lines and words per file) and record wall-clock time with
time.perf_counter. - Run the same workload through a
ThreadPoolExecutorwith a fixed worker count; compare the time against the baseline and note which stage the workers are waiting on. - Make the per-file work CPU-heavy (for example hashing file contents repeatedly) and compare threads with a
ProcessPoolExecutoron the same input; record which wins and how the GIL predicts the result. - Insert one unreadable or corrupt file and run the batch with per-item error handling; record whether the batch completes and what the error sink reports, then let the exception propagate and compare the two outcomes.
Capstone specification
Build a file-oriented data processor and implement a measured concurrency strategy.
Common mistakes
- Choosing a concurrency model before building the sequential baseline: without a measurement there is nothing to compare against, and coordination overhead can turn a design that looks faster into a slower program.
- Using threads for CPU-heavy work and expecting a speedup: the GIL lets only one thread execute Python bytecode at a time, so compute stays serialized while context switching adds cost; processes or isolated interpreters are the models that multiply compute.
- Leaving the work queue unbounded: when producers outrun consumers, the backlog accumulates in memory instead of applying backpressure, and the failure appears later as an out-of-memory crash far from the code that caused it.
- Launching workers without planning shutdown: on cancellation or failure, threads or processes left running keep holding files, sockets, and locks, so cleanup (context managers, executor shutdown, task cancellation) belongs in the design from the start.
Practice: Easy
- Write the sequential baseline over a directory of text files: discover, read, count lines and words, and write results; time it with
time.perf_counterand record the number. - Convert the baseline to a
ThreadPoolExecutorwith a fixed worker count, run the same input, and compare the wall-clock time with the baseline. - Insert one deliberately corrupt file and record what the baseline does (abort, skip, or report); write one sentence stating the behavior the batch should have.
Practice: Medium
- Add a bounded
queue.Queue(maxsize=...)between a reader stage and worker threads; make the reader fast and the workers slow, then record whether memory stays flat and where the producers block. - Wrap the per-file work in a CPU-heavy function and run it with threads and with a
ProcessPoolExecutor; record both times and explain the difference using the GIL. - Give the pipeline a per-item error policy: catch one expected exception type per item and send failures to a separate error sink; test with a mixed batch and record the final counts of results and errors.
Practice: Hard
- Implement the capstone specification: sequential baseline, two concurrency models, bounded submission, worker error propagation, graceful cancellation and shutdown, structured logging with the file path, and a benchmark or profiler report, plus the written model justification.
- Compare threads and processes over two workloads (blocking I/O versus CPU-heavy) with
time.perf_counterand a profiler where available; write a decision table stating which model wins, by how much, and the overhead that explains the gap. - Force a mid-batch cancellation (a stop flag or a cancelled future), verify that workers close their files and the queue drains, and record the shutdown sequence; then rerun without the cleanup to show what hangs or leaks.
Lesson checklist
- I can write the sequential baseline and measure it before adding any concurrency.
- I can pick threads, processes, interpreters, or asyncio from the workload and defend the choice.
- I can bound the work handoff and explain how backpressure limits memory growth.
- I can define and test what happens when one item fails or the batch is cancelled.
Remember
A concurrent data processor is a measured trade: build the sequential baseline first, bound the handoff between stages, decide per-item failure behavior, and clean up workers on success, failure, and cancellation. Then choose the model from the bottleneck (threads for blocking I/O, processes or interpreters for CPU-heavy work, asyncio for many small waits) and prove the choice with numbers rather than intuition.
Interview angles
What is the main purpose of **File processing**?+
A production file pipeline separates discovery, reading, parsing, transformation, and output so each stage can be tested and measured independently. Stream large files and define how one bad file affects the rest of the batch.
What should you pay attention to when using **Queues**?+
A queue creates an explicit handoff point between producers and consumers. Bounded queues also provide backpressure, while thread/process/async queue types differ in how they synchronize and move data.
How does **Threads / processes / async** fit into this lesson?+
Choose the execution model from the workload: threads are often effective for blocking I/O, processes or isolated interpreters can suit CPU work, and asyncio suits large numbers of cooperative asynchronous I/O operations.
Why can an unbounded work queue be worse than a smaller bounded one?+
A bounded queue makes a fast producer wait for slow consumers, which is backpressure. An unbounded queue accepts everything immediately, so the backlog accumulates in memory and the failure appears later as an out-of-memory crash far from the code that caused it.