Joins and Shuffles in Spark
Choose and control join strategies in Spark: broadcast hash joins, sort-merge joins, handling skewed keys and reducing shuffle volume.
Advanced · about 6 hours · difficulty 4/5
Learn first: PySpark DataFrames
Joins are where most Spark jobs spend their time and where most of them fail. Interviewers for Spark roles ask about join strategies almost every time.
Join strategies
- Broadcast hash join: the small table is copied to every executor, so the large table does not shuffle. Ideal for joining a huge fact (orders) to a small dimension (cities). Spark does this automatically under
spark.sql.autoBroadcastJoinThreshold, or you can hint withbroadcast(df). - Sort-merge join: both sides are shuffled by key and sorted, then merged. The default for two large tables.
- Shuffle hash join: a middle option, less common.
Check the plan with df.explain() to see which one Spark chose.
Handling skew
- Find skew: in the Spark UI one task is far slower and processes far more data.
- AQE skew join handling splits skewed partitions automatically when enabled.
- Salting: add a random suffix to the hot key on the large side and replicate the small side, spreading one key over many tasks.
- Filter or handle NULL keys separately; they often form one giant skewed partition.
Reducing shuffle
- Filter and select columns before joining.
- Aggregate before joining when possible.
- Tune
spark.sql.shuffle.partitions(default 200) to the data size, or let AQE coalesce partitions. - Bucketing tables on the join key avoids repeated shuffles for frequent joins.
Pitfalls
- Broadcasting a table that is too large and causing out-of-memory errors.
- Joins that explode row counts because the key is not unique on the side you assumed.
You are ready to move on when you can force a broadcast join and a sort-merge join on the same data, compare their plans and runtimes, and fix a deliberately skewed join with salting or AQE.
Key concepts
- Broadcast hash join
- Sort-merge join
- Reading explain() output
- Detecting skew in the Spark UI
- Salting skewed keys
- AQE skew handling
- shuffle.partitions tuning
- Bucketing
Mini project
Generate a skewed orders dataset where one seller has 30 percent of rows. Join it to a sellers table three ways (default, broadcast, salted) and record runtimes and Spark UI task distributions in a short write-up.
Check yourself
Your join stage has 199 tasks finishing in 10 seconds and one running for 40 minutes. What is happening and what are two fixes?
Free resources
- Spark SQL performance tuning (Apache Spark)
- Spark SQL, DataFrames and Datasets guide (Apache Spark)
- Spark web UI (Apache Spark)