Zero Labs
Industry News / AI

Part XVIII — The Small-Files Tax: Compaction Strategies That Don’t Stall

Source · Towards AI By chakshu_salgotra

From the publisher’s feed, collected in the ZeroLabs newsroom.

Your lakehouse doesn’t slow down because the data grew. It slows down because the file count did — and every one of those files is a tax your query planner pays before it reads a single byte.Part I | Part II | Part III | Part IV | Part V | Part VI | Part VII | Part VIII | Part IX | Part X | Part XI | Part XII | Part XIII | Part XIV | Part XV | Part XVI | Part XVII | Part XVIIIThe 58-Minute Query That Read Nothing UsefulThe Slack message landed at 9:41 PM, eleven minutes into the nightly reporting window: “finance dashboard is stuck again.” Not failed — stuck. The aggregate query over our events Delta table had been creeping for months: 11 minutes in March, 24 in May, 41 in July. That night it hit 58 minutes, and the CFO's morning numbers were going to be late.The table wasn’t that big. 2.9 TB, which is a rounding error on our cluster. But the file count was 3.8 million, median file size 2.4 MB — a graveyard of hourly micro-batch writes, backfills, and streaming checkpoints, each one dutifully committed as its own tiny Parquet file. The Spark UI told the story in one line: the job spent its first 22 minutes doing nothing but listing and planning. Twenty-two minutes before a single task read data.The driver was the casualty. To plan the query it had to fetch 3.8 million file statuses, hold them in memory, and prune against them. Driver GC pauses stretched to 40 seconds. Meanwhile every listing hammered S3: 3,800 LIST requests per full scan at 1,000 keys a pop, and we were listing that prefix several times a day across jobs — the LIST bill alone had quietly crossed $900/month, which is absurd money to spend on finding your data.And the cruelest part: data skipping was dead. With 2.4 MB files, the min/max statistics on each file overlapped everything. A filter on event_date that should have pruned 90% of files pruned almost nothing, because every tiny file's date range bled into its neighbors'. We were reading the whole table to answer a query that needed 3% of it.So: where does file count actually bite in a lakehouse engine, and how do you compact millions of small files without stalling the readers who are querying them right now?The Mechanic Underneath: Every File Is a Row in Your Query PlanHere is the mental model that makes everything else click: a lakehouse query planner does not read data — it reads files, then reads data. Every file on the table is a unit of planning work. Listing it, fetching its statistics, evaluating it against partition and data-skipping predicates, assigning it to a task. That work scales with file count, not data volume. A 3 TB table in 3,000 files plans in seconds. The same 3 TB in 3.8 million files plans in tens of minutes and occasionally kills the driver trying.This is why the small-files problem never shows up in benchmarks and always shows up in production. Benchmarks generate clean, big files. Production accumulates files the way a desk accumulates paper — one small write at a time, each one individually reasonable, collectively catastrophic.Listing Is a Distributed Systems Bill, Not a Free LookupObject stores don’t have directories. A “listing” is a paginated API call returning 1,000 keys at a time, and the planner needs the full listing before it can prune. For our table: 3.8M files meant 3,800 LIST calls per scan, each with its own latency. Delta Lake’s transaction log helps — the log knows the current file set without listing the prefix — but the driver still materializes every active file’s metadata into the plan. The listing cost moved from S3 to driver memory, which is arguably worse: S3 LIST costs you dollars; driver-side file metadata costs you GC pauses and OOMs.The math that matters:Plan-time is O(files). Doubling the file count roughly doubles planning latency, regardless of data size.Driver memory is O(files). Each file’s status and statistics live in the driver’s heap during planning. Millions of files is a multi-GB planning footprint before Spark reads anything.Task granularity follows files. One file is (roughly) one task’s minimum unit. Millions of tiny files mean millions of tiny tasks — scheduler overhead, tiny I/O, no vectorization benefit.Data Skipping Dies When Min/Max Ranges OverlapPart X of this series covered Z-ordering and file-level statistics in depth; the short version: data skipping works when a file’s min/max range for a filtered column sits outside your predicate. A 128 MB file holding one hour of events has a tight range and skips cleanly. A 2.4 MB file holding ninety seconds of events has a range that overlaps its neighbors on every side — and with 3.8 million such files, nearly every file overlaps nearly every predicate.Overlapping ranges are the tax; the files are just the receipt. Compaction’s real job isn’t reducing file count for its own sake — it’s restoring non-overlapping, tight min/max ranges so skipping works again.Compaction Is Bin-Packing With a Write-Amplification BillOPTIMIZE (Delta) / rewrite_data_files (Iceberg) is bin-packing: read N small files, write M large ones at the target size (128 MB–1 GB is the sane band), commit atomically. The engine mechanics are straightforward; the economics are the interesting part:Write amplification: compacting 3.8M files of 2.4 MB means reading 2.9 TB and rewriting 2.9 TB. You pay the full I/O twice, plus the compute to do it. Compaction is never free — it’s a loan you repay in faster reads.Z-order interplay: a plain bin-pack restores file size but not clustering. If you Z-order on the hot filter columns during compaction (see Part X), you fix size and skipping in one pass. Skip the Z-order and you’ll be compacting again in six months.Scheduling without stalling readers: compaction commits are atomic snapshot swaps, so readers never see a half-compacted table. The real contention is compute: a full-table OPTIMIZE hogs the cluster. The fix is incremental — compact only what drifted (more in The Fix).The File-Count Budget: Sizing Compaction Before It Owns YouDon’t compact by vibes. Run the budget:Production rate: our table gained ~48,000 files/day (hourly micro-batches + streaming + backfills).Planning pain threshold: on our driver shape, planning stayed under 60 seconds up to ~150K files per query’s file set.Compaction capacity: our nightly window could rewrite ~400 GB/hour without starving production.48,000 files/day × 2.4 MB ≈ 115 GB/day of small files — well within a nightly incremental window. The mistake had been letting it compound for 18 months instead of draining it nightly. File count is a queue; compaction is the drain. Size the drain to the inflow, not to the backlog.One operational habit made this stick: we started emitting the table’s file count as a first-class metric, scraped nightly from the Delta log, with an alert at 2× the planning-pain threshold. File count had been invisible for 18 months because nobody was watching it — it wasn’t in any dashboard, so it never became anyone’s problem until it became everyone’s. The cheapest compaction strategy is the one that never lets the backlog form, and that starts with a number on a graph, not a cron job.The Fix, and What It Cost-- Naive: blanket OPTIMIZE on the whole table every night.-- Rewrites 2.9 TB nightly, 6+ hours, burns the compute budget,-- and re-clusters data that was already fine.OPTIMIZE events;-- Optimized: compact only what drifted, predicate-filtered,-- Z-ordered on the hot filter column, low concurrency.-- Naive: OPTIMIZE events; (whole table, nightly, no filter)-- Optimized: target files below 64MB in recent partitions onlyOPTIMIZE eventsWHERE event_date >= current_date() - INTERVAL 7 DAYS AND _metadata.file_size ZORDER BY (event_date, user_id);# Naive: spark.conf.set("spark.databricks.delta.optimize.maxFileSize", 134217728)# then OPTIMIZE the entire table — one giant job, reader-visible# cluster contention, and a 6-hour rewrite of data that was fine.# Optimized: incremental, partition-scoped, off-peak, bounded rewrite# Schedule: nightly, 2 AM, max 4 concurrent compaction tasksspark.conf.set("spark.databricks.delta.optimize.maxFileSize", "134217728") # 128MB targetspark.conf.set("spark.databricks.delta.optimize.minFileSize", "67108864") # only touch spark.sql(""" OPTIMIZE events WHERE event_date >= current_date() - INTERVAL 7 DAYS ZORDER BY (event_date, user_id)""")# Readers see atomic snapshot swaps; the 2 AM slot keeps production clear.The backfill took one weekend (the 18-month backlog had to drain once). After that, the nightly incremental ran in 25–40 minutes. Results:File count: 3.8M → 41K (then held steady; the drain matches the inflow).Planning time: 22 minutes → 47 seconds.The finance query: 58 minutes → 9 minutes. Same data, same cluster.S3 LIST spend: ~$900/month → under $40/month.Data skipping restored: the event_date filter now prunes 94% of files instead of 11%.The Catch: Compaction Has Its Own BillsTime travel and retention. Every compaction commit obsoletes old files. If your VACUUM retention is 7 days, you can no longer time-travel past a compaction boundary. Set retention deliberately; don’t discover this during an incident.Z-order decays. New writes are unclustered by definition. Compaction restores clustering, but if your hot filter column changes (new query pattern), the old Z-order is just expensive decoration. Re-evaluate the Z-order columns quarterly.Don’t compact the landing zone obsessively. The raw ingestion prefix is write-heavy and rarely queried directly. Compacting it nightly is pure write amplification with no read payoff. Compact the serving tables; leave the landing zone chunky.Streaming sources need the fix upstream. If a streaming job writes 2 MB files every trigger, no compaction schedule keeps up gracefully. Fix the trigger interval and foreachBatch output partitioning first — compaction is the drain, not the faucet.TakeawaysPlan-time is O(files), not O(bytes): a 3 TB table in 3,000 files plans in seconds; in 3.8M files it plans in 22 minutes.Driver memory is the real listing bill: S3 LIST costs dollars, but materializing millions of file statuses costs driver GC pauses and OOMs.Overlapping min/max ranges are the tax: tiny files poison data skipping because every file’s range bleeds into its neighbors’.Compaction is bin-packing with write amplification: you pay the full read+rewrite once to buy back every future query.Z-order during compaction, or do it twice: size alone doesn’t restore skipping; clustering does.Budget file count like a queue: size the nightly compaction drain to the daily file inflow, not to the backlog.Small files are the compound interest of lazy writes — invisible daily, brutal eventually.If this saved you a 3 AM pager incident, follow me on Medium for Twice a week for the next 3 Months of Advanced Data Engineering & AI. Let’s connect on LinkedIn and X.Part XVIII — The Small-Files Tax: Compaction Strategies That Don’t Stall was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.