Apache Spark · Beginner
What is the difference between repartition and coalesce in Spark?
By Anurag Pandey, Lead Data Engineer ·
The short answer
repartition does a full shuffle and can raise or lower the number of partitions, giving evenly sized ones. coalesce only lowers the number by merging existing partitions without a full shuffle, so it's cheaper but can leave partitions uneven.
Opens this question on SpinTheMic. Start without signing up; sign in free for an AI report card.
Say it like this
About 55 seconds out loud. Use it as a model, then put it in your own words.
Both change the number of partitions in a DataFrame, but they work differently. repartition does a full shuffle. It can increase or decrease the number of partitions, and because every row is redistributed, the new partitions come out roughly even. I can also repartition by a column, so rows with the same key land together. coalesce can only reduce the number of partitions. It merges existing partitions instead of shuffling, so it's a narrow transformation and much cheaper. The catch is that partitions can end up uneven, and a drastic coalesce, say down to one partition, can make the whole stage before it run on very few tasks. So I use coalesce to cut the number of output files at the end of a job, and repartition when I need more parallelism or need to fix uneven data.
What interviewers look for
- You put the shuffle at the centre of the answer.
- You know coalesce can only reduce partitions.
- You mention the risk of a drastic coalesce cutting parallelism upstream.
Common mistakes
- Saying coalesce never moves data. It avoids a full shuffle but still merges partitions.
- Always preferring coalesce because it is cheaper, even when it creates one huge task.
- Forgetting that repartition can take column names to partition by key.
Follow-up questions to expect
- 1How would you control the number of files written to storage?
- 2When can coalesce be slower than repartition?
- 3What is the difference between repartition and partitionBy on write?
Opens this question on SpinTheMic. Start without signing up; sign in free for an AI report card.