The small file problem
A table stored as millions of tiny files can be far slower to read than the same data in a few hundred large ones. This lesson shows why small files hurt, how Spark jobs create them, and how to prevent and fix them.
Step 2 · Spark internals · Silver · Self-tuning and file layout, lesson 2 of 2
On this page
Show code in
Every code block on the page follows this.
Read first: Partitions · Shuffle partitions (skip if you know them)
In plain words first
Fetching 1,000 one-page letters from the post office, one trip each, takes far longer than fetching one 1,000-page parcel, because most of the time goes on the trips. Every file has a fixed cost to open, whatever its size.
Why small files hurt
Reading a file has a fixed cost that does not depend on its size:
| Cost per file | Why it adds up |
|---|---|
| Listing | Object stores list about 1,000 keys per request. Listing 1 million files takes 1,000 sequential requests before any planning. |
| Open and footer read | ParquetParquet: A columnar file format: values of each column are stored together, so queries read only the columns they need. Learn more → keeps its schema and statistics at the end of each file; every file needs at least one extra request. |
| Metadata | For Hive tables, every partitionpartition: A chunk of a DataFrame's rows. Spark processes each partition as one task, so partitions decide how much work runs in parallel. Learn more → and file is tracked by the metastore and the driverdriver: The process that runs your program, plans the work and sends tasks to executors. Learn more →. For Delta and Iceberg, every file is an entry in the log or manifestsmanifest: An Iceberg metadata file listing data files and their statistics. Learn more →, which grows and slows planning. |
| Taskstask: The work for one partition in one stage, run on one CPU core. Learn more → | Spark packs small files together (counting each as at least openCostInBytes, 4 MB) but scheduling still grows with the file count. |
| Compression and statistics | Tiny row groupsrow group: A block of rows inside a Parquet file. Its min and max statistics let readers skip blocks that cannot match a filter. Learn more → compress worse, and min/max statistics over a few rows rarely let a reader skip anything useful. |
On object stores like S3, ADLS and GCS, request latency, not bandwidth, dominates. Reading 10 GB as 100,000 files can take ten times longer than the same 10 GB as 80 files.
How Spark jobs create them
- Too many shuffleshuffle: Moving rows between machines so that all rows with the same key end up together. Needed by joins, groupBy and sorting, and usually the most expensive step of a job. Learn more → partitions at write time. A write after a join or aggregation produces one file per non-empty partition. 200 partitions writing 50 MB of data gives 200 files of 250 KB.
- partitionBy on a high-cardinalitycardinality: How many distinct values a column has. User ids are high cardinality; country codes are low. Learn more → column. Each task writes one file per partition value it holds. 200 tasks × 365 dates = up to 73,000 files per run.
- Streaming micro-batches. A stream that commits every 10 seconds writes files every 10 seconds: 8,640 batches a day, each with several files.
- Frequent small appends. Hourly or per-event loads of a few MB each.
- Over-partitioned sources. Reading thousands of files and writing straight back preserves the count.
Walk through one bad write
Step 1 · the job
daily and appends it to the table at path, partitioned by event_date and country (60 countries). The upstream shuffle has 200 partitions.The command
daily.write.mode("append").partitionBy("event_date", "country").parquet(path)
Step 2 · the math
Step 3 · a year later
Step 4 · the fix
The command
daily.repartition("event_date", "country") \ .write.mode("append").partitionBy("event_date", "country").parquet(path)
INSERT INTO events_by_country SELECT /*+ REPARTITION(event_date, country) */ * FROM daily
Preventing them when writing
| Technique | How | Watch out |
|---|---|---|
| Let AQEAQE: Adaptive Query Execution: Spark re-plans a running query using the real data sizes it has measured. Learn more → coalesce | With AQE on, a write after a shuffle uses merged partitions near 64 MB | Only after a shuffle; raise advisoryPartitionSizeInBytes to 128-256 MB for write-heavy jobs |
| repartition(n) | Pick n from the output size: 50 GB / 256 MB ≈ 200 | A full shuffle |
| repartition(partition cols) | One task per table partition, so one file per directory | A huge partition value becomes one huge task (skewskew: When one key has far more rows than the others, so one task does most of the work while the rest wait. Learn more →) |
| coalesce(n) | Merge without a shuffle | Reduces the parallelism of the whole stagestage: A group of steps Spark can run without moving data between machines. A new stage starts at every shuffle. Learn more → |
| maxRecordsPerFile | .option("maxRecordsPerFile", 5_000_000) caps file size from above | Does not merge small files |
| Coarser partitioning | Partition by month instead of day, or not at all for small tables | See Partitioning done right |
Delta Lake can do this for you: optimized writes add an adaptive shuffle before writing so each partition gets fewer, larger files, and auto compaction runs a small compaction after a write. They are table properties (delta.autoOptimize.optimizeWrite, delta.autoOptimize.autoCompact) on Databricks and in recent open-source Delta releases; check your version.
Fixing them afterwards
path = "s3://lake/events" # the table tmp = "s3://lake/_compact/events" # a staging location to write to first # Plain Parquet: rewrite one partition into fewer files, then swap it in (spark.read.parquet(f"{path}/event_date=2025-03-01") .repartition(8) .write.mode("overwrite").parquet(f"{tmp}/event_date=2025-03-01")) # Delta Lake from delta.tables import DeltaTable DeltaTable.forPath(spark, path).optimize().executeCompaction()
-- Delta Lake OPTIMIZE events WHERE event_date >= '2025-03-01'; -- Apache Iceberg CALL catalog.system.rewrite_data_files(table => 'db.events');
With plain Parquet, rewriting in place is unsafe for concurrent readers: they can see the old files deleted before the new ones appear. Table formats make compaction a single atomic commit, which is one of their biggest practical benefits. Old files remain until VACUUM (Delta) or expire_snapshots (Iceberg) removes them.
Detecting the problem
DESCRIBE DETAIL tableon Delta returnsnumFilesandsizeInBytes: divide to get the average file size. Under about 32 MB is worth fixing.- For Iceberg, query the metadata table
db.events.filesforfile_size_in_bytes. - In the Spark UI, a scan with tens of thousands of tasks reading a few hundred KB each, or a long gap before the first job (planning and listing), points to small files.
Try it yourself
Each example says what it shows, then the output from a real run and what to notice in it, so you can follow without running anything. To try one yourself, paste it into a local Spark session, with spark already created: each builds its own data.
Goal: Write a partitioned table with sensible file sizes: one task per folder, and a cap on rows per file.
import glob from pyspark.sql import functions as F events = (spark.range(0, 300_000) .withColumn("event_date", F.expr("date_add('2025-03-01', CAST(id % 5 AS INT))"))) (events .repartition("event_date") # one task per date folder .write.mode("overwrite") .option("maxRecordsPerFile", 50_000) # cap the file size inside a folder .partitionBy("event_date") .parquet("lab/small_files/events")) for folder in sorted(glob.glob("lab/small_files/events/event_date=*")): print(folder.split("/")[-1], len(glob.glob(folder + "/*.parquet")), "files")
Output from a real run
event_date=2025-03-01 2 files event_date=2025-03-02 2 files event_date=2025-03-03 2 files event_date=2025-03-04 2 files event_date=2025-03-05 2 files
What to notice:
- Each date folder has 2 files: 300,000 rows over 5 dates is 60,000 per date, and
maxRecordsPerFilecaps a file at 50,000. - Without
repartition("event_date"), every task would write a file into every folder.
Goal: See how a careless partitioned write produces hundreds of small files.
import glob from pyspark.sql import functions as F df = spark.range(0, 100_000).withColumn("day", (F.col("id") % 5).cast("string")) def write(df, path): df.write.mode("overwrite").partitionBy("day").parquet(path) return len(glob.glob(path + "/*/*.parquet")) bad = write(df.repartition(50), "lab/small_files/bad") good = write(df.repartition("day"), "lab/small_files/good") print("50 tasks x 5 days:", bad, "files") print("repartition by the key:", good, "files")
Output from a real run
50 tasks x 5 days: 250 files repartition by the key: 5 files
What to notice:
- 50 tasks × 5 date folders = 250 files: every task had rows for every date, so each wrote a file into each folder.
- Repartitioning by the folder column first gave 5 files: one task per date.
Common mistakes
- coalesce(1) to "fix" small files on big data — One task does all the work, and one giant file reduces read parallelism later.
- partitionBy on user_id or timestamp — Millions of directories, each with tiny files.
- Compacting plain Parquet in place while others read it — Readers can fail or see duplicates. Use a table format, or write to a new location and swap.
Key takeaways
- Each file has a fixed cost: listing, opening, metadata and often a task.
- Small files come from too many write partitions, high-cardinality partitionBy, streaming and small appends.
- Repartition by the partition columns, let AQE coalesce, and use maxRecordsPerFile to cap size.
- Table formats make compaction atomic; aim for 128 MB to 1 GB files.
Interview prep
THE QUESTION
"Queries on our events table got slower every month even though daily volume is flat. Why, and what do you do?"
Avoid: only "run OPTIMIZE" without saying why small files hurt, and how to stop creating them.
Follow-ups · answer out loud, then open
Follow-up"Why does writing with partitionBy("date") after a 200-partition shuffle create so many files?"
Scenario"A streaming job writes to a Delta table every 10 seconds. A month later, reads are slow. What do you do?"
Trap"coalesce(1) before every write solves the small file problem."
Check yourself
3 questions200 tasks each hold rows for 30 dates and write with partitionBy("date"). Up to how many files are written?
Show the answer
6,000. Each task writes one file per partition value it holds: 200 × 30.
Which change gives one file per date directory?
Show the answer
repartition("date") before the write. Repartitioning by the partition column sends all rows of a date to one task.
Why is compaction safer on Delta or Iceberg than on plain Parquet?
Show the answer
The rewrite is committed atomically, so readers see either the old files or the new ones. The new file list is published in one commit; old files stay readable until vacuumed.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · new module: Skew · 8 min readData skew and salting
Why one task runs for an hour while the rest finish in seconds, and how salting spreads a hot key.
Related lessons
Compaction, OPTIMIZE and Z-orderData lake & lakehouse · 6 min read
Partitioning done rightSpark internals · 5 min read
Shuffle partitions
Previous: Adaptive Query Execution
Primary sources: Performance tuning · Delta Lake: optimizations · Iceberg: maintenance