The full answer
Many small files slow Spark down because every file has to be listed, opened and its metadata read, often over object storage with high latency, and because they can create too many small tasks. The fixes are, in order of effect: compact the files, stop creating them in the first place, and tune how Spark reads them in the meantime.
1. Compact existing files
- Table formats: Delta Lake's
OPTIMIZErewrites small files into large ones without changing the data; Iceberg has therewrite_data_filesprocedure. Run them on a schedule, or let the platform do it (predictive optimisation and auto compaction on Databricks). - Plain files: a one-off job reads a folder and writes it back with fewer partitions:
(spark.read.parquet("/raw/events/date=2026-10-15")
.repartition(16)
.write.mode("overwrite").parquet("/compacted/events/date=2026-10-15"))
2. Stop creating small files
- Reduce output partitions before writing:
coalesce(n),repartition(n)or theREBALANCEhint, which lets AQE produce evenly sized output. - When writing partitioned tables,
repartitionby the partition column first, so each task writes one file per partition instead of one per task per partition. - Don't partition by high-cardinality columns (user id, timestamp); prefer date-level partitions, or clustering (liquid clustering on Databricks) instead of partitions.
- In streaming, use longer trigger intervals or
availableNowruns, and enable optimised writes and auto compaction where available. spark.sql.files.maxRecordsPerFileonly splits large files; it doesn't merge small ones.
3. Tune reading while the files exist
- Spark packs small files into one partition up to
spark.sql.files.maxPartitionBytes(128 MB), treating each file as costingspark.sql.files.openCostInBytes(4 MB). Lowering the open cost packs more files per task when files are tiny. - Read with an explicit schema so Spark doesn't open files to infer it; for Parquet, avoid
mergeSchemaunless needed. - Listing: with many directories, Spark lists them in parallel (
spark.sql.sources.parallelPartitionDiscovery.threshold, 32 paths by default). Use partition filters so only needed directories are listed, andpathGlobFilterto skip unrelated files. - Table formats avoid listing altogether: the transaction log or metadata already holds the file list and statistics.
4. Use incremental ingestion for arriving files Instead of re-listing a growing landing folder, use a streaming file source or Auto Loader on Databricks, which tracks which files it has already processed.
How to see the problem
In the Spark UI, look at the number of files read, scan time and task count for the scan stage. For a table, DESCRIBE DETAIL (Delta) shows the number of files and total size; an average file size of a few megabytes or less is a sign to compact.
Last updated 16 October 2026
Sources