Partitions and shuffles
Each lesson runs in a fresh session. We read ShopKart's orders with a schema, as in lesson 2:
from pyspark.sql import SparkSession, functions as F
spark = (SparkSession.builder.appName("shopkart").master("local[*]")
.config("spark.ui.showConsoleProgress", "false").getOrCreate())
spark.sparkContext.setLogLevel("ERROR")
schema = ("order_id INT, customer_id INT, product_id INT, quantity INT, "
"unit_price DECIMAL(10,2), status STRING, order_ts TIMESTAMP")
orders = (spark.read.option("header", True).schema(schema).csv("data/orders/")
.dropna(subset=["order_id", "quantity"])
.withColumn("amount", F.col("quantity") * F.col("unit_price")))
print(orders.count(), "orders,", orders.rdd.getNumPartitions(), "partitions")5315 orders, 8 partitionsA shuffle happens after wide operations (groupBy, join, distinct). Spark then splits the result into spark.sql.shuffle.partitions pieces: 200 by default, far too many for small data.
print("spark.sql.shuffle.partitions =", spark.conf.get("spark.sql.shuffle.partitions"))
def partitions_used(df): # how many partitions actually held rows when the job ran
return df.groupBy(F.spark_partition_id()).count().count()
by_customer = orders.groupBy("customer_id").agg(F.sum("amount").alias("revenue"))
spark.conf.set("spark.sql.adaptive.enabled", "false")
print("AQE off:", partitions_used(by_customer), "partitions used after groupBy")
spark.conf.set("spark.sql.adaptive.enabled", "true")
print("AQE on :", partitions_used(by_customer), "partition(s) used after groupBy")spark.sql.shuffle.partitions = 200
AQE off: 127 partitions used after groupBy
AQE on : 1 partition(s) used after groupByWithout AQE, the 200 customers' totals were scattered over 127 partitions (each one a separate task, mostly tiny). With Adaptive Query Execution on (the default), Spark saw the real size and merged everything into one partition. On big data, AQE picks a sensible number for you.
repartition vs coalesce
print(orders.repartition(16).rdd.getNumPartitions(), "after repartition(16) (full shuffle)")
print(orders.coalesce(2).rdd.getNumPartitions(), "after coalesce(2) (merges, no shuffle)")
(orders.repartition(4, "status")
.groupBy(F.spark_partition_id().alias("partition")).count()
.orderBy("partition").show())16 after repartition(16) (full shuffle)
2 after coalesce(2) (merges, no shuffle)
+---------+-----+
|partition|count|
+---------+-----+
| 0| 200|
| 1| 4590|
| 2| 525|
+---------+-----+repartition(4, "status") puts all rows with the same status in the same partition. Four statuses landed in only three partitions because two hashed to the same one: hashing doesn't guarantee one key per partition.
| repartition(n / cols) | coalesce(n) | |
|---|---|---|
| Shuffle? | Yes (full) | No (merges neighbours) |
| Increase partitions? | Yes | No |
| Even sizes? | Yes | Not necessarily |
| Typical use | Before a big join/groupBy on a key; fix skewed or too few partitions | Before writing, to produce fewer files |
Caching: measured
import time
big = (orders.crossJoin(spark.range(1000)) # about 5.3 million rows
.withColumn("score", F.sha2(F.concat_ws("-", "order_id", "id"), 256))) # some real work per row
def timed(label):
start = time.time(); n = big.filter(F.col("score").startswith("a")).count()
print(f"{label:<24} {n} rows {time.time() - start:.2f} s")
timed("no cache, run 1"); timed("no cache, run 2")
big.cache(); big.count() # cache() is lazy: an action fills it
timed("cached, run 1"); timed("cached, run 2")
big.unpersist()no cache, run 1 331399 rows 1.76 s
no cache, run 2 331399 rows 0.79 s
cached, run 1 331399 rows 0.31 s
cached, run 2 331399 rows 0.28 sThe first uncached run read the CSV files, built 5.3 million rows and hashed each one (1.76 s). The second was faster only because the files were warm in the OS cache. Once cached in memory, the same query took about 0.3 s. Cache what you reuse; don't forget unpersist().
Data skew, and salting
Skew means one key has far more rows than the others, so one task does most of the work while the rest wait:
# 1 million events; 90% belong to one huge customer (key 0): a skewed key
events = spark.range(1_000_000).withColumn(
"customer_id", F.when(F.col("id") % 10 < 9, F.lit(0)).otherwise(F.col("id") % 1000))
spark.conf.set("spark.sql.adaptive.enabled", "false")
sizes = (events.repartition(8, "customer_id")
.groupBy(F.spark_partition_id().alias("partition")).count()
.orderBy(F.desc("count")))
sizes.show(3)+---------+------+
|partition| count|
+---------+------+
| 5|912000|
| 1| 17000|
| 7| 17000|
+---------+------+
only showing top 3 rowsOne partition got 912,000 rows; the others about 17,000. That one task would decide the whole job's runtime.
# Salting: spread the hot key over 8 sub-keys, aggregate, then combine
salted = events.withColumn("salt", (F.rand(seed=1) * 8).cast("int"))
partial = salted.groupBy("customer_id", "salt").agg(F.count("*").alias("n"))
(partial.repartition(8, "customer_id", "salt")
.groupBy(F.spark_partition_id().alias("partition")).count()
.orderBy(F.desc("count")).show(3))
final = partial.groupBy("customer_id").agg(F.sum("n").alias("events"))
final.orderBy(F.desc("events")).show(2)
spark.conf.set("spark.sql.adaptive.enabled", "true")+---------+-----+
|partition|count|
+---------+-----+
| 1| 132|
| 0| 115|
| 5| 99|
+---------+-----+
only showing top 3 rows
+-----------+------+
|customer_id|events|
+-----------+------+
| 0|900000|
| 259| 1000|
+-----------+------+
only showing top 2 rowsSalting adds a random number (0–7) to the hot key so its rows spread over 8 groups; you aggregate per (key, salt), then once more per key. The biggest partition dropped from 912,000 rows to 132 partial results, and the final count (900,000 for customer 0) is unchanged. With AQE on, Spark also splits skewed partitions in joins automatically (spark.sql.adaptive.skewJoin.enabled).
A tuning checklist
| Symptom (Spark UI) | Likely cause | Fix |
|---|---|---|
| One task much slower than the rest | Skew | AQE skew join, salting, broadcast the small side |
| Huge shuffle read/write | Wide ops on big data | Filter and select early; broadcast small tables; pre-aggregate |
| Thousands of tiny tasks | Too many partitions / small files | AQE coalescing, coalesce before write, compact files |
| Spill to disk | Partitions too big for memory | More partitions, more memory, less data per row |
| Same stage recomputed | Reused DataFrame not cached | cache() / persist(), then unpersist() |
| BatchEvalPython steps | Python UDFs | Built-in functions or pandas UDFs (lesson 5) |
🎯 Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1What is a shuffle and why is it expensive?Fresher+
Q2repartition vs coalesce?1–3 yrs+
Q3What is Adaptive Query Execution?1–3 yrs+
Q4How do you handle data skew?3+ yrs+
Q5cache vs persist vs checkpoint?3+ yrs+
Key takeaways
- ✓Find the expensive part first: shuffles, skew, recomputation.
- ✓AQE fixes many partition problems automatically.
- ✓Cache only what you reuse; we saw 1.76 s → 0.3 s.
- ✓Salting turned one 912,000-row partition into even work.
Frequently asked questions
What's the most common cause of slow Spark jobs?
Shuffles: groupBy, joins, distinct and orderBy move data between partitions across the network and disk. After that: data skew (one huge partition), too many tiny files or partitions, and Python UDFs.
repartition or coalesce?
repartition(n or columns) does a full shuffle and can increase or decrease partitions, evenly. coalesce(n) only merges existing partitions without a shuffle, so it's cheap but can only reduce the count and may leave partitions uneven. Use coalesce before writing fewer files.
When should I cache?
When the same DataFrame is used more than once (in several actions or branches) and recomputing it is expensive. Don't cache everything: memory is limited, and caching data used once only adds work. Call unpersist() when you're done.
What does AQE do?
Adaptive Query Execution re-plans a query while it runs, using real data sizes: it merges small shuffle partitions, switches joins to broadcast when one side turns out small, and splits skewed partitions. It's on by default since Spark 3.2.
🧠 Quick check: performance
1. Default spark.sql.shuffle.partitions?
2. With AQE on, our tiny groupBy result used...
3. One customer owns 90% of rows and one task runs forever. That's...
4. cache() is...
Checking your access…