Partitions & Adaptive Query Execution
Databricks · Apache Spark on Databricks
Theory
A partition is a chunk of a DataFrame's rows processed by one task. Spark reads files into partitions based on file sizes, and after a shuffle it uses spark.sql.shuffle.partitions (200 by default in open-source Spark). Too few partitions leave cores idle and cause large, spilling tasks; too many create thousands of tiny tasks. repartition(n, col) reshuffles into n partitions, and coalesce(n) merges partitions without a full shuffle.
Adaptive Query Execution (AQE), on by default in Databricks, re-optimizes a query while it runs using real statistics from finished stages. It coalesces small shuffle partitions, switches a sort-merge join to a broadcast join when one side turns out small, and splits skewed partitions so one hot key (for example region West with most of the orders) does not make one task run for an hour. Because of AQE, you rarely need to tune shuffle partitions by hand on Databricks.
Why we use it
Parallelism and data skew decide how fast a Spark job runs. AQE fixes many partition and skew problems automatically, but you still need the concepts to read query profiles and to choose repartition or coalesce correctly.
When to use it
Leave AQE on and start with defaults. Use coalesce to reduce the number of output files, repartition by a key before a heavy operation on that key, and investigate skew when one task runs much longer than the others.
How it works
- Stage finishes and writes shuffle data
- AQE reads real sizes of the shuffle partitions
- Are many partitions tiny? Yes: Coalesce them into fewer tasks. No: Keep the partition count.
- Is one partition much bigger (skew)? Yes: Split it into smaller tasks. No: Run the next stage normally.
- Next stage runs with the re-optimized plan
Syntax
df.rdd.getNumPartitions() (classic compute)
df.repartition(n) | df.repartition(n, "col") | df.coalesce(n)
spark.sql.shuffle.partitions
spark.sql.adaptive.enabled = true (default)
spark.sql.adaptive.skewJoin.enabledExample
orders = spark.read.table("main.sales.orders")
print(spark.conf.get("spark.sql.adaptive.enabled")) # true
by_region = orders.groupBy("region").sum("amount") # shuffle; AQE coalesces partitions
# Spread work by key before a heavy per-region step
balanced = orders.repartition(8, "region")
# Write fewer, larger files
(by_region.coalesce(1)
.write.mode("overwrite")
.saveAsTable("main.sales.region_totals"))Key points
- One task per partition: partitions control parallelism
- repartition does a full shuffle; coalesce only merges partitions
- AQE coalesces shuffle partitions, switches join strategy and handles skew at runtime
- Skew shows up as one task far slower than the rest in the same stage
- On serverless you cannot use RDD APIs like getNumPartitions; check the query profile