Tech challenge · PySpark

One task takes 40 minutes; the other 199 take 20 seconds

HardPySpark

A join between events (3 TB) and accounts (400 GB) on account_id finishes 199 of 200 tasks in seconds, then one task runs for 40 minutes and sometimes spills to disk. What is happening, how do you confirm it, and what are your options?

Think it through or sketch an answer first, then open the hint or the solution.

Show a hint

Look at the distribution of rows per key. One customer may generate a large share of all events.

Show the solution

This is data skew: one key (often a test account, a NULL or a huge customer) holds a large share of the rows, so one shuffle partition is far bigger than the rest. Confirm it in the Spark UI (task duration and shuffle read size per task) or with a count per key. Options, in order: enable adaptive query execution with skew-join handling, which splits oversized partitions automatically; filter or handle NULL keys separately; broadcast the smaller side if it fits; or salt the hot key by adding a random suffix on the big side and replicating the matching rows on the other side.

Example (Python)

spark.conf.set('spark.sql.adaptive.enabled', 'true')
spark.conf.set('spark.sql.adaptive.skewJoin.enabled', 'true')

# manual salting when AQE is not enough
from pyspark.sql import functions as F
N = 16
events_s = events.withColumn('salt', (F.rand() * N).cast('int'))
accounts_s = accounts.crossJoin(spark.range(N).withColumnRenamed('id', 'salt'))
joined = events_s.join(accounts_s, ['account_id', 'salt']).drop('salt')

Common mistakes

  • Simply raising spark.sql.shuffle.partitions: the hot key still lands in a single partition.
  • Adding executors: one task runs on one core however big the cluster is.

Learn more

More PySpark challenges

Today's challenge and the full archive