Data Engineering · Chapter 9 · ~15 min · Advanced
Distributed Compute: MapReduce & Apache Spark
Demystify large-scale distributed data processing: MapReduce mechanics, Apache Spark DAG execution engine, RDDs vs DataFrames, partition skew, shuffle operations, and memory spills.
- Trace Map, Shuffle, and Reduce operations across distributed cluster worker nodes
- Understand Apache Spark lazy evaluation, Catalyst Optimizer, and tungsten memory management
- Diagnose and resolve partition skew and disk spills caused by wide transformations
- Optimize Spark operations: broadcast joins, repartition vs coalesce, and caching strategies
Distributed Compute: MapReduce & Apache Spark: learn it visually
Demystify large-scale distributed data processing: MapReduce mechanics, Apache Spark DAG execution engine, RDDs vs DataFrames, partition skew, shuffle operations, and memory spills.
1Everyday Intuition: The Election Ballot Counting Model
Imagine counting 150 million election ballots. If a single person in Washington, D.C. examines every ballot one by one, it would take 40 years to declare a winner.
Instead, nations use a distributed MapReduce architecture:
Local Precinct Counting
Thousands of local voting precincts tally their local paper ballots in parallel. Each precinct emits key-value pairs: (Candidate_A, 520), (Candidate_B, 410).
Network Data Exchange
All tallies for Candidate A are routed to Table A; all tallies for Candidate B are routed to Table B. In distributed computing, this network data exchange is the Shuffle.
Candidate Aggregation
The candidate tables sum all incoming precinct totals to output the final national vote counts.
Why is the Shuffle phase typically the slowest part of a distributed Spark job?
2Under the Hood: The Apache Spark Architecture
While legacy Hadoop MapReduce wrote every intermediate stage back to physical disk, Apache Spark retains datasets in distributed RAM across memory-managed worker JVMs.
1. Driver Program
The brain of the cluster. Creates the SparkSession, plans execution DAGs, optimizes code via the Catalyst Optimizer, and assigns task partitions to executors.
2. Worker Executors
Worker processes running on cluster nodes. Each executor manages CPU cores, Tungsten off-heap memory, and disk caches to execute individual task partitions.
3. Narrow vs Wide Transformations
Narrow transformations (filter, map) execute locally without moving data across machines. Wide transformations (groupBy, join) force a cluster shuffle boundary.
Wrong idea: Assume DataFrame transformations load data into RAM immediately
Believing that writing df.filter() or df.select() immediately scans terabytes of Parquet files into memory. This causes engineers to manually chunk and slice queries unnecessarily.
Real system: Transformations build a logical DAG; Actions trigger execution
Transformations (map, filter, join) are lazily compiled by the Catalyst Optimizer. Spark only triggers physical execution when an Action (.count(), .write, .collect()) is evaluated.
When is a Broadcast Hash Join preferred over a standard Shuffle Hash Join in Apache Spark?
3Hands-On: Diagnose Partition Skew & Straggler Nodes
In distributed systems, the slowest worker core determines the completion time of the entire job. Inject key skew below and observe how key salting and broadcast joins balance executor load:
Spark Cluster & Partition Skew Simulator
Observe how key skew forces a single executor to bottleneck the entire cluster, and see how salting and broadcast joins fix it.
Why should you use .coalesce(n) instead of .repartition(n) when decreasing partition count from 500 to 10 after a heavy filter?
4Bug Hunt: Fix a Crashing Spark Job
The PySpark analytics script below crashes production clusters: it performs a full shuffle on a tiny 5KB table, triggers a JVM driver Out-Of-Memory error with .collect(), and suffers from severe key skew. Fix all three bottlenecks:
🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.
Need a hint?
- Wrap the dimension table with
broadcast(df_currencies). - Eliminate
metrics.collect()and usemetrics.write.parquet(...)instead. - Enable Adaptive Query Execution (AQE) with
spark.conf.set('spark.sql.adaptive.skewJoin.enabled', 'true')or salt the grouping key.
5Recap
- Apache Spark processes massive datasets in distributed RAM using directed acyclic graphs compiled by the Catalyst Optimizer.
- Lazy Evaluation queues transformations until an Action (e.g.
.write,.count()) is invoked, optimizing whole-stage execution. - Broadcast Hash Joins copy small dimension tables into executor RAM, avoiding hundreds of gigabytes of expensive network shuffle.
- Partition Skew causes straggler tasks; mitigate skew by key salting or enabling Spark 3+ Adaptive Query Execution (AQE).
Ready for Chapter 10? Mark this chapter as complete to proceed: