The tuning checklist (in order)
๐1. Read less
Filter early, select columns, data skipping
๐2. Shuffle less
Broadcast joins, fewer wide steps
โ๏ธ3. Fix skew
AQE, salting, split hot keys
๐๏ธ4. Fix files
Compaction, clustering, right partitions
๐ฅ๏ธ5. Then compute
Photon, right instance size
Reading the Spark UI
| Where | What to look for | It means |
|---|---|---|
| Jobs โ Stages | One stage much slower than others | Start there |
| Stage โ task summary | Max task time โซ median | Skew |
| Stage โ shuffle read/write | Huge numbers (GBs+) | Too much shuffling |
| Stage โ spill (memory/disk) | Any spill | Partitions too big for memory |
| SQL / DataFrame tab | The plan: scans, joins, Exchange | Join type, files read vs skipped |
| Executors tab | GC time, failed tasks | Memory pressure |
1. Read less data
- Filter early and select only needed columns. Catalyst pushes filters into the Parquet scan when it can.
- Data skipping: Delta keeps min/max per file; clustering (liquid or Z-ORDER) on filter columns lets queries skip most files.
- Avoid functions on filter columns where possible (
WHERE to_date(ts) = ...can block skipping; filter on a range oftsor a date column).
2. Shuffle less: broadcast joins
Spark's default join for two big tables is a sort-merge join: shuffle both sides by key, sort, merge. If one side is small, a broadcast hash join copies it to every executor instead, and the big side never moves.
from pyspark.sql import functions as F
from pyspark.sql.functions import broadcast
orders = spark.table("shopkart.silver.orders") # big table
customers = spark.table("shopkart.silver.customers") # small table
joined = orders.join(broadcast(customers.filter("is_current")), "customer_id")
joined.explain() # look for BroadcastHashJoin: no shuffle of the big tableWe checked that the plan contains BroadcastHashJoin.
| Join strategy | When | Shuffle? |
|---|---|---|
| Broadcast hash join | One side small (< threshold or hinted) | No (small side is copied) |
| Sort-merge join | Both sides large (default) | Yes, both sides |
| Shuffle hash join | One side medium, fits in memory per partition | Yes |
Partitions: repartition and coalesce
print(orders.rdd.getNumPartitions())
fewer = orders.coalesce(1) # merge partitions, no shuffle (e.g. before writing a small result)
more = orders.repartition(8, "order_id") # full shuffle into 8 partitions by key
print(fewer.rdd.getNumPartitions(), more.rdd.getNumPartitions())spark.sql.shuffle.partitions(default 200) sets how many partitions a shuffle creates. On Databricks, setting it toautolets the platform choose.- Aim for partitions of roughly 100โ200 MB, and at least as many partitions as cores.
- coalesce to reduce without a full shuffle; repartition to rebalance or split by key.
Adaptive Query Execution (AQE)
# Adaptive Query Execution: Spark re-plans while running (on by default since Spark 3.2).
spark.conf.set("spark.sql.adaptive.enabled", "true")
spark.conf.set("spark.sql.adaptive.coalescePartitions.enabled", "true") # merge tiny shuffle partitions
spark.conf.set("spark.sql.adaptive.skewJoin.enabled", "true") # split huge skewed partitions
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", str(10 * 1024 * 1024)) # auto-broadcast tables under 10 MBAQE (on by default since Spark 3.2) re-plans at each shuffle using real sizes: merges tiny partitions, converts joins to broadcast, and splits skewed partitions. Leave it on.
3. Data skew and salting
Imagine one corporate customer with 40% of all orders. Joining by customer_id sends all their rows to one task. Fixes, in order of simplicity: let AQE's skew join handle it, broadcast the other side, filter or process the hot key separately, or salt the key:
# One customer has millions of orders โ one task gets most of the work (skew).
# Salting spreads that key over N buckets.
N = 8
salted_orders = orders.withColumn("salt", (F.rand() * N).cast("int"))
salted_customers = (customers.filter("is_current")
.crossJoin(spark.range(N).select(F.col("id").cast("int").alias("salt"))))
joined = salted_orders.join(salted_customers, ["customer_id", "salt"]).drop("salt")Each order gets a random salt 0โ7; the small side is copied 8 times, once per salt. The hot customer's rows now spread over 8 tasks. We checked that the salted join returns exactly the same row count as the normal join.
Caching
gold_input = spark.table("shopkart.silver.orders").filter("status = 'DELIVERED'").cache()
gold_input.count() # first action fills the cache
by_product = gold_input.groupBy("product").sum("amount") # reuses cached data
by_day = gold_input.groupBy(F.to_date("order_ts")).sum("amount")
gold_input.unpersist() # free the memory when done| Spark cache (.cache / .persist) | Databricks disk cache | |
|---|---|---|
| What | A DataFrame's result in executor memory/disk | Copies of remote Parquet/Delta files on local SSDs |
| How | You call it, and unpersist after | Automatic on supported instance types |
| Use for | A DataFrame reused several times in one job | Repeated reads of the same tables |
4. Small files
Every file has overhead (opening, listing, metadata). Streaming and frequent appends create thousands of tiny files. Fixes: OPTIMIZE (compaction), optimized writes and auto compaction (Delta settings that write bigger files), liquid clustering, and predictive optimization on managed tables. And don't partition by high-cardinality columns.
Memory errors
| Error | Usual cause | Fix |
|---|---|---|
| Driver OutOfMemory | collect(), toPandas() on big data; huge broadcast | Don't bring big data to the driver; lower broadcast |
| Executor OOM / heavy spill | Huge partitions, skew, wide rows | More partitions, fix skew, bigger memory per core |
| Container killed | Python UDF memory, too many cores per executor | Built-in functions, adjust executor sizing |
5. Then the compute
- Photon for SQL-heavy and DataFrame workloads.
- Memory-optimized instances for joins and caching; compute-optimized for CPU-bound work.
- Autoscaling for variable loads; a fixed size for steady jobs.
- Upgrade the Databricks Runtime: newer versions often bring free speed-ups.
๐ฏ Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1How do you optimize a slow Spark job?1โ3 yrs+
Q2Explain broadcast join and its limits.1โ3 yrs+
Q3What is data skew and how do you handle it?1โ3 yrs+
Q4repartition vs coalesce, and when do you use each?1โ3 yrs+
Q5What does AQE do?3+ yrs+
Q6Your job fails with driver OOM. Causes?3+ yrs+
Q7How would you tune a MERGE that takes hours?3+ yrs+
Key takeaways
- โMeasure with the Spark UI before changing anything.
- โReading less and shuffling less beat bigger clusters.
- โSkew and small files are the classic hidden killers.
- โAQE and Photon help automatically; good code helps most.
Frequently asked questions
What is the most common reason a Spark job is slow?
Too much shuffling, data skew (one task gets most of the data), and too many small files. Reading far more data than needed (no filters, no data skipping) comes close behind.
What is a broadcast join?
Spark sends a copy of the small table to every executor, so the big table is joined where it sits, with no shuffle. Spark does this automatically for tables under spark.sql.autoBroadcastJoinThreshold (10 MB by default); you can force it with broadcast().
What is data skew?
When a few keys have far more rows than the rest, the tasks handling those keys run much longer while everything else waits. In the Spark UI you see one or two tasks taking minutes while others take seconds.
Should I cache everything?
No. Cache only a DataFrame you reuse several times in the same job, and unpersist it after. Caching uses memory that Spark needs for processing, and on Databricks the disk cache already speeds up repeated reads of Delta files.
What is Adaptive Query Execution?
AQE lets Spark change the plan while the query runs, using real sizes measured after each shuffle: it merges tiny partitions, switches to a broadcast join if a side turns out small, and splits skewed partitions. It's on by default.
๐ง Quick check: Spark performance
1. You join a 2 TB orders table with a 5 MB country table. Best join?
2. One task takes 40 minutes, the other 199 take 30 seconds. Likely cause?
3. You need to write a small result as ONE file. Use...
4. Thousands of tiny files slow down reads. Fix?
Checking your accessโฆ