This code demonstrates the salting technique for handling data skew in Apache Spark joins. Data skew occurs when certain keys appear much more frequently than others, causing some partitions to process significantly more data and creating performance bottlenecks.
The Problem
When joining datasets where one or both have skewed keys (keys that appear disproportionately often), those keys get assigned to the same partition, overloading it while other partitions remain underutilized. This leads to slow, unbalanced processing.
The Salting Solution
Step 1: Identify Skewed Keys
The code first identifies which keys are problematic by counting occurrences and flagging those above a threshold. Keys appearing more than skew_threshold times are considered skewed.
Step 2: Split the Data
The original dataset gets divided into two parts:
- Records with skewed keys
- Records with non-skewed keys
Step 3: Apply Salting to Skewed Data
For the skewed portion, the code adds a random "salt" value (0 to num_salts-1) to each record and creates a new composite key by concatenating the original key with the salt. For example, if key "A" appears 1000 times, it becomes "A_0", "A_1", "A_2" distributed randomly across records.
Step 4: Replicate Non-Skewed Data
To match the salted keys, the non-skewed dataset gets replicated. Each record is duplicated num_salts times with different salt values, so a record with key "A" becomes "A_0", "A_1", and "A_2".
Step 5: Perform Joins
- Skewed data joins using the salted keys, distributing the load across multiple partitions
- Non-skewed data joins normally using original keys
- Results are combined with a union operation
The Benefit
Instead of one partition handling all 1000 records of key "A", the work gets distributed across 3 partitions (with salting factor of 3), each handling roughly 333 records. This dramatically improves performance for skewed joins while maintaining correctness of results.
The technique trades some additional storage and computation (replication) for much better parallelization and faster overall execution times.