Spark · mid
Partitions, repartition, coalesce and small files
The number and size of partitions decides speed and file count. repartition shuffles and balances; coalesce only merges. Thousands of tiny files slow every read.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- repartition(n) does a full shuffle and gives even partitions; it can increase or decrease. repartition(col) hash-partitions so equal keys land together.
- coalesce(n) merges existing partitions without a shuffle, can only decrease, and leaves uneven sizes.
- With no shuffle between, coalesce(10) also cuts the parallelism of the stage before it, so a 2,000-task scan and filter runs with 10 tasks. repartition(10) adds a stage boundary, so the scan keeps 2,000 tasks.
- repartition(1) on a big dataset to get one file is a trap. repartition by a column before partitionBy gives one file per value, but a big value gives one huge file.
- Adaptive execution merges small shuffle partitions (64 MB advisory size) but does not change a stage with no shuffle.
- Tiny files slow reads: listing, S3 GET requests, opening files, footers, task scheduling, worse compression and statistics. Aim for about 128 MB to 1 GB.
- Cause example: a streaming job that writes every minute, with many tasks each writing a file per (date, event name) value. Files are about batches x tasks x partition values.
- Fix the writer first: fewer partition columns (cluster instead), repartition by the partition columns before writing or use a REBALANCE hint, a longer trigger interval, Delta optimized writes or Iceberg hash distribution.
- Compact old files with an atomic commit: Delta OPTIMIZE, Iceberg rewrite_data_files, Hudi clustering. Then clean up (VACUUM, expire_snapshots, remove_orphan_files) after the retention period. Do not delete files in place while readers run.
The red pen
Common traps: mistake → fix
Mistake: coalesce is always faster because it does not shuffle
Fix: it can cut the parallelism of the stage before it.
Mistake: Compaction alone fixes small files
Fix: fix the writer too, or they come back.
Mistake: Delete and rewrite the files in place
Fix: readers may see missing data; use an atomic table commit.
Easy to hard
Questions interviewers ask, easy to hard
- What is the difference between repartition and coalesce?
- A job filters out 97% of rows from 2,000 partitions. Which do you use before the write?
- Queries got slower and the table gets 40,000 small files a day. What happened and how do you fix it?
- How do you get one file per city without one huge file?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.