Skip to the page
Tecyfy

PySpark interview question · easy

What is the difference between `repartition` and `coalesce` in Spark?

The short answerrepartition(n) performs a full shuffle to produce exactly n roughly equal partitions, and can increase or decrease the count or partition by columns.

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
repartitioncoalesce
ShuffleAlwaysNone (narrow dependency)
DirectionIncrease or decreaseDecrease only
Partition sizesEven (or by key)Can be uneven: merges neighbouring partitions
Partition by columnYesNo
CostNetwork and disk for the shuffleCheap
Effect on upstream workUpstream stage keeps its parallelismCan 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").
  • repartitionByRange when 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

Where each fact comes from

  1. 1PySpark API reference
  2. 2Performance tuning
  3. 3Hints