The full answer
repartition(n) performs a full shuffle to produce exactly n roughly equal partitions, and can increase or decrease the count or partition by columns. coalesce(n) only decreases the number of partitions by merging existing ones without a shuffle, so it is cheaper but can leave partitions uneven.
df = spark.range(0, 1_000_000, numPartitions=8)
df.repartition(16) # shuffle → 16 even partitions
df.repartition("country") # shuffle by column (hash partitioning), spark.sql.shuffle.partitions partitions
df.repartition(32, "country") # by column, 32 partitions
df.coalesce(2) # merge 8 into 2, no shuffle
df.coalesce(16) # still 8: coalesce can't increase
repartition | coalesce | |
|---|---|---|
| Shuffle | Always | None (narrow dependency) |
| Direction | Increase or decrease | Decrease only |
| Partition sizes | Even (or by key) | Can be uneven: merges neighbouring partitions |
| Partition by column | Yes | No |
| Cost | Network and disk for the shuffle | Cheap |
| Effect on upstream work | Upstream stage keeps its parallelism | Can reduce upstream parallelism, since the merged stage runs with fewer tasks |
When to use repartition
- Too few partitions for the cluster (for example after reading one large gzip file) or very uneven partitions.
- Before heavy processing by key, or before a partitioned write, to group rows by the partition column so each task writes few files:
df.repartition("event_date").write.partitionBy("event_date"). repartitionByRangewhen you need range-ordered partitions.
When to use coalesce
- Reducing the number of output files after a filter has shrunk the data:
df.coalesce(10).write.... - Any decrease where small imbalance doesn't matter.
The coalesce trap
coalesce(1) before writing one file makes the whole last stage, sometimes including the expensive work before it, run in a single task. For large data, repartition(1) is often faster, because the upstream work stays parallel and only the final result is shuffled to one task. Better still, avoid single files for big data.
In SQL and with adaptive query execution
Hints do the same in SQL: /*+ REPARTITION(16) */, /*+ COALESCE(4) */, and /*+ REBALANCE */, which lets adaptive query execution produce evenly sized output partitions. With AQE on (the default), Spark already merges small shuffle partitions, so manual repartitioning is needed less often than it used to be.
Last updated 16 October 2026
Sources