intermediate
Repartition vs Coalesce
10 min readLast updated: 2026-07-09
Overview
Learn the critical differences between repartition and coalesce to optimize partition layouts while minimizing network shuffles.
What You Will Learn
In this lesson, you will learn:
- Repartition Mechanics: Full network shuffles for partition counts adjustments.
- Coalesce Optimization: Decreasing partitions without shuffles.
- Trade-offs: When to use repartition vs coalesce.
Detailed Concept Explanation
Managing partition layout is crucial for query efficiency. Spark provides two API methods to adjust partition counts:
1. repartition(n)
- Behavior: Performs a full network shuffle to redistribute data evenly across
nnew partitions. - Direction: Can increase or decrease the partition count.
- Use Case: Balancing data sizes across partitions to avoid skew before joins or aggregations.
- Cost: High, due to network and disk I/O shuffles.
2. coalesce(n)
- Behavior: Decreases partition count without performing a full network shuffle. It merges adjacent partitions on the same executor node.
- Direction: Can only decrease the partition count.
- Use Case: Reducing partition counts to optimize file sizes before writing to disk.
- Cost: Low, as it avoids network shuffles.
Code Examples
Python (PySpark) Implementation
python
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("RepartitionCoalesce").getOrCreate()
df = spark.range(1, 1000).repartition(10)
print("Partitions after repartition:", df.rdd.getNumPartitions())
# Reduce partitions using coalesce (no shuffle)
coalesced_df = df.coalesce(2)
print("Partitions after coalesce:", coalesced_df.rdd.getNumPartitions())
Expected Output
text
Partitions after repartition: 10
Partitions after coalesce: 2
Execution Plan Diagram (Python & Scala)
Execution Plan Diagram
SparkSession.builder
range(1
1000)
repartition(10) [Full Shuffle]
coalesce(2) [No Shuffle]
getNumPartitions()
Scala Implementation
scala
import org.apache.spark.sql.SparkSession
val spark = SparkSession.builder().appName("RepartitionCoalesceScala").getOrCreate()
val df = spark.range(1, 1000).repartition(10)
println(s"Partitions after repartition: ${df.rdd.getNumPartitions}")
val coalesced = df.coalesce(2)
println(s"Partitions after coalesce: ${coalesced.rdd.getNumPartitions}")
Interview Perspective
What is the difference between repartition and coalesce? When would you use which?
repartition performs a full network shuffle to redistribute data evenly across a specified number of partitions (either increasing or decreasing the count). coalesce decreases partition counts without triggering a full network shuffle by merging adjacent partitions on the same node. Use repartition to balance data before joins or aggregations, and coalesce to group files before writing to disk to avoid shuffles.