Skip to content
Silver 8 min read · maxRecordsPerFile 2 practice problems ↓

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

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 fileWhy it adds up
ListingObject stores list about 1,000 keys per request. Listing 1 million files takes 1,000 sequential requests before any planning.
Open and footer readParquetParquet: 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.
MetadataFor 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 statisticsTiny 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

  1. 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.
  2. 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.
  3. Streaming micro-batches. A stream that commits every 10 seconds writes files every 10 seconds: 8,640 batches a day, each with several files.
  4. Frequent small appends. Hourly or per-event loads of a few MB each.
  5. Over-partitioned sources. Reading thousands of files and writing straight back preserves the count.

Walk through one bad write

Step 1 · the job

A daily job aggregates 5 GB of events into the DataFrame 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

Each of the 200 tasks holds rows for most of the 60 countries, and writes one file per country it holds. That is up to 200 × 60 = 12,000 files for one day, averaging about 400 KB.

Step 3 · a year later

365 days × 12,000 = 4.4 million files. Queries spend minutes listing and opening files before reading meaningful data, and the driver needs gigabytes just to plan.

Step 4 · the fix

Repartition by the partition columns before writing, so each (date, country) combination is written by one task: one file per directory. 60 files per day instead of 12,000.

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

TechniqueHowWatch out
Let AQEAQE: Adaptive Query Execution: Spark re-plans a running query using the real data sizes it has measured. Learn more → coalesceWith AQE on, a write after a shuffle uses merged partitions near 64 MBOnly 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 ≈ 200A full shuffle
repartition(partition cols)One task per table partition, so one file per directoryA 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 shuffleReduces 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 aboveDoes not merge small files
Coarser partitioningPartition by month instead of day, or not at all for small tablesSee 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

PySparkSpark SQL · Compaction
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 table on Delta returns numFiles and sizeInBytes: divide to get the average file size. Under about 32 MB is worth fixing.
  • For Iceberg, query the metadata table db.events.files for file_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.
Why this matters: the healthy target for analytic tables is roughly 128 MB to 1 GB per file. Larger files reduce overhead further but make each task longer and reduce parallelism for small queries.

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.

Production patternPySpark · Writer settings that keep file sizes healthy
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 maxRecordsPerFile caps 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.

ExplorePySpark · How a careless write explodes into 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?"

Probably file count growth: daily appends or streaming write many small files, so listing, opening and planning grow with time. Confirm with the file count and average size (DESCRIBE DETAIL, Spark UI). Fix forward by repartitioning by the partition columns or tuning AQE before writes, and backward with compaction (OPTIMIZE / rewrite_data_files), scheduled regularly. For streaming, mention longer triggers or auto compaction.

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?"
Each of the 200 tasks writes one file for every date it contains. If dates are spread across all tasks, that is up to 200 files per date. Repartition by the partition column (and possibly a salt) before writing, so each task writes to few dates.
Scenario"A streaming job writes to a Delta table every 10 seconds. A month later, reads are slow. What do you do?"
Each micro-batch writes at least one file per task, so file counts explode. Lengthen the trigger interval if latency allows, enable optimized writes or auto compaction where available, and schedule OPTIMIZE (with a predicate on recent partitions) to compact regularly. Then VACUUM old files after retention.
Trap"coalesce(1) before every write solves the small file problem."
It produces one file, but it also runs the whole upstream stage on one task, and one huge file can be just as bad for parallel reads. Target files of roughly 128 MB to 1 GB instead, with repartitioning or maxRecordsPerFile.

Check yourself

3 questions

200 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 read
Data 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

Previous: Adaptive Query Execution

Primary sources: Performance tuning · Delta Lake: optimizations · Iceberg: maintenance