A daily Spark write leaves tens of thousands of tiny files — find and fix the cause
This job appends one day of events to a table partitioned by country. Each run adds tens of thousands of files, most under 1 MB, and downstream reads crawl.
Constraints: events arrives in about 2,000 partitions, each holding rows of every country; there are ~30 countries; aim for a few files per country per run, with no file over a few million rows; no table format is available, so fix this write.
(events
.filter(F.col("event_date") == run_date)
.write
.mode("append")
.partitionBy("country")
.parquet("s3://lake/events"))Find and fix the bug.
Each task writes one file per country it holds, so 2,000 mixed tasks × 30 countries ≈ 60,000 files. Add repartition('country') before the write so each country's rows meet in one task, and cap files with maxRecordsPerFile. Old files need compaction.
- Using
coalesce(1)and collapsing the scan and filter into one task - Blaming
appendmode instead of the tasks × partition values product - Repartitioning by country without capping file size for a dominant country
- How would you compact files already written without a table format?
- What does one dominant country do to this write after
repartition('country')?
partitionBy lays files out in folders, but tasks create the files: each of the ~2,000 tasks holding rows of 30 countries opens one file in every country's folder. Hence tens of thousands of files of about a hundred kilobytes per run. Readers then spend their time listing and opening files instead of reading data.
(events
.filter(F.col("event_date") == run_date)
.repartition("country") # each country's rows in one task
.write
.option("maxRecordsPerFile", 5_000_000) # split a big country into several files
.mode("append")
.partitionBy("country")
.parquet("s3://lake/events"))repartition("country") adds a shuffle, but each country lands whole in one task and is written as one file; maxRecordsPerFile keeps a dominant country from spilling into a file of hundreds of millions of rows. coalesce(1) is wrong here: with no shuffle it squeezes the whole stage, scan and filter included, into one task.
The small files already written do not go away this way: a compaction job has to reread the partition and rewrite it as large files (in Delta Lake that is OPTIMIZE, in Iceberg the rewrite_data_files procedure).