Salt a Spark join on one hot customer key with AQE turned off
orders joins customers on customer_id, but customer C42 owns 40% of all orders, so one join task runs for hours. Write orders_by_customer using salting.
Constraints: AQE is off (spark.sql.adaptive.enabled=false); customers is about 20 GB, too big to broadcast; the hot key's rows must spread over n_salts join tasks; the result must equal what the plain join would give; return customer_id, segment, n_orders, avg_amount.
from pyspark.sql import DataFrame, functions as F
HOT = ["C42"]
def orders_by_customer(orders: DataFrame, customers: DataFrame, n_salts: int) -> DataFrame:
# orders: order_id, customer_id, amount; customers: customer_id, segment
# your code hereWrite the implementation.
Salt the hot key's orders with a random 0..N-1 (others get 0), copy the hot customer row once per salt, and join on (customer_id, salt): each order still matches exactly one row. Aggregate by customer_id from sums and counts, not by averaging per-salt means.
- Salting both sides randomly, so most orders never meet their customer row
- Averaging per-salt averages, which overweights small salt groups
- Replicating the whole 20 GB dimension N times instead of only the hot keys
- How do you choose N, and what does too large an N cost?
- What would AQE's skew-join handling do here if it were turned on?
Only hot keys get a salt: C42's orders spread randomly over N values, and its row in customers is replicated N times, one per salt. All other keys use salt 0, so the 20 GB dimension barely grows.
from pyspark.sql import DataFrame, functions as F
HOT = ["C42"]
def orders_by_customer(orders: DataFrame, customers: DataFrame, n_salts: int) -> DataFrame:
is_hot = F.col("customer_id").isin(HOT)
salted_orders = orders.withColumn(
"salt",
F.when(is_hot, (F.rand(seed=7) * n_salts).cast("int")).otherwise(F.lit(0)),
)
salted_customers = customers.withColumn(
"salt",
F.explode(
F.when(is_hot, F.sequence(F.lit(0), F.lit(n_salts - 1)))
.otherwise(F.array(F.lit(0)))
),
)
joined = salted_orders.join(salted_customers, ["customer_id", "salt"])
return (joined
.groupBy("customer_id", "segment")
.agg(F.count("*").alias("n_orders"),
(F.sum("amount") / F.count("amount")).alias("avg_amount")))Each order gets exactly one salt, and its customer has exactly one row with that salt, so there is one match — as in the plain join. Aggregate by the original key. If you first compute partial totals per (customer_id, salt), combine them through sums and counts: an average of per-salt averages is wrong, because the salt groups differ in size.
With AQE on (the default since 3.2), its skew join usually relieves such a sort-merge join by itself: it splits the skewed partition (over 5× the median and over 256 MB) without a manual salt.