Skip to the page
Tecyfy

PySpark interview question · medium

How can you diagnose and optimize a slow join operation in PySpark?

The short answerStart by finding where the time goes: open the query in the Spark UI's SQL tab, see which join strategy was used and which stage is slow, and compare task durations and shuffle sizes.

The full answer

Start by finding where the time goes: open the query in the Spark UI's SQL tab, see which join strategy was used and which stage is slow, and compare task durations and shuffle sizes. The cause is almost always one of: too much data being shuffled, the wrong join strategy, skewed keys, badly sized partitions, or spilling because of too little memory. Each has a specific fix.

1. Diagnose

  • Plan: df.explain("formatted") and the SQL tab show BroadcastHashJoin, SortMergeJoin or ShuffledHashJoin, and whether filters were pushed to the scans.
  • Stage details: for the slow stage, compare the median and maximum task duration and shuffle read size. A maximum far above the median means skew.
  • Spill: "Spill (memory)" and "Spill (disk)" columns show memory pressure.
  • Sizes: input rows and shuffle bytes for each side of the join.
  • Key distribution: df.groupBy("customer_id").count().orderBy(F.desc("count")).show(10) reveals hot keys, including nulls or placeholder values such as 0 or "unknown".

2. Fixes by cause

Too much data shuffled

  • Filter and select before the join; avoid UDFs that block pushdown.
  • Pre-aggregate if you only need totals per key.
  • Check the join condition: a missing or wrong key can multiply rows.

Wrong join strategy

  • Broadcast the small side if it fits: big.join(F.broadcast(small), "key"), or raise spark.sql.autoBroadcastJoinThreshold (10 MB by default) carefully.
  • Keep statistics current (ANALYZE TABLE ... COMPUTE STATISTICS) so the planner sees true sizes.
  • AQE (on by default) converts to a broadcast join at runtime if a side turns out small.

Skew

  • AQE's skew join handling splits partitions over 5 times the median and over 256 MB in sort-merge joins; check that it happened (the plan shows skewed partitions in AQEShuffleRead).
  • Handle null or placeholder keys separately: filter them out, join the rest, then union back.
  • Salting for extreme cases: add a random suffix to hot keys on the large side and replicate the matching rows on the small side.

Partition sizing

  • Too few shuffle partitions give huge tasks that spill; too many give overhead. Set spark.sql.shuffle.partitions (or spark.sql.adaptive.coalescePartitions.initialPartitionNum) high enough for the data, aiming at roughly 100–200 MB per partition, and let AQE coalesce.

Memory and spill

  • Fewer cores per executor or more memory per executor gives each task more room; more partitions makes each task smaller.

3. Structural fixes for joins that run repeatedly

  • Store both tables bucketed or clustered on the join key so the shuffle can be skipped (bucketing or storage-partitioned joins with Iceberg), or use liquid clustering on Databricks to improve file skipping.
  • Materialise a pre-joined or pre-aggregated table if many queries need the same join.

Example

from pyspark.sql import functions as F

orders = spark.table("sales.orders").filter("order_date >= '2026-01-01'").select("order_id", "customer_id", "amount")
customers = spark.table("crm.customers").select("customer_id", "segment")

joined = orders.join(F.broadcast(customers), "customer_id")   # if customers is small enough
joined.explain("formatted")

Change one thing at a time and compare the stage metrics, so you know which fix helped.

Last updated 16 October 2026