Video in progress

You need to join two large datasets (say 2 billion transactions and 50 million customers) by key. Which join algorithm do you choose, and what do you do about data skew?

If the small side fits in memory, a broadcast hash join. If both are large, shuffle by key and do a partitioned hash join or a sort-merge join. With skew (one customer has 100 million rows), you need to split the "hot" keys with a salt and spread them out, or broadcast them separately.

📖 Answer

This question is really the same algorithmic choice whether it's in a DB, in Spark, or in a batch we wrote ourselves.

Broadcast hash join. If you need only id → segment from the 50 million customers, that's ~1-2 GB. We send a copy to every worker and stream the transactions through. There is no shuffle, so it's the cheapest option. If the small side grows, the workers fall over with an OOM, so you need size monitoring.

Shuffle hash join. We distribute both sides into P partitions by hash(customerId) % P. A key is always in one partition. In each partition, we build a hash table from the small side and stream the big side through it. The cost is moving both datasets over the network.

Sort-merge join. We sort both by key and walk with two pointers. It has low memory requirements and is stable even when it spills to disk. If the data is already sorted (for example bucketed tables), it's very cheap.

Skew is what hurts most in prod. 199 tasks finish in 2 minutes, and one task runs for 3 hours, because it holds a "test" customer or a null key.

This is what I do:

  1. First I measure: the top-100 key frequencies. Often the hot key is null, 0 or a test account. Filtering them out before the join is the cheapest fix.
  2. For genuinely hot keys, salting: on the big side I append rand(0..N) to the key, and on the small side I copy that key's row N times. One heavy task is split into N average ones.
  3. In Spark 3, AQE (spark.sql.adaptive.skewJoin.enabled) splits skewed partitions automatically; before manual salting I try turning that on.

Selection criteria: the size and growth rate of the small side, the key distribution, how often it repeats (if it's daily, storing the data pre-bucketed by key removes the shuffle completely), and the SLA. The algorithm is easier than what's in the textbook, but a correct choice made without knowing about skew will still be hours late.