Lakehouse Small Files Compaction and Streaming Latency: A Measurement-Driven Guide
Diagnose lakehouse small files, separate compaction from clustering, and plan safe rewrites using measured latency, ingestion load and replay retention.
Author: jackey.ye | Last updated: 2026-11-24
Small-file compaction can cut streaming read latency when metadata planning and file-open overhead are bottlenecks. Schedule and resource rewrites to limit ingestion contention, and preserve the retention required by replay consumers. This guide diagnoses that overhead, separates compaction from clustering and partitioning, and rolls out scheduling you can measure.
Why small files inflate streaming latency
Picture a library holding 10,000 thin pamphlets instead of 100 bound volumes. Finding one fact means pulling many items off the shelf, and the catalog itself grows heavy. In a lakehouse, each data file is a pamphlet and the table metadata is the catalog.
When a streaming job writes micro-batches, each trigger can commit new files. Over time the table accumulates small files plus the manifest and metadata entries that track them. A read then pays two costs before it touches a row: planning (scanning manifests and metadata to prune files) and opening (one storage request per file). Both scale with file count rather than data volume, so the same bytes spread across more files read slower.
The Iceberg table specification makes this concrete. Data files in a snapshot are tracked by one or more manifest files, each holding a row per data file with its partition data and metrics; in v1–v3, the manifests making up a snapshot are listed in a manifest list whose partition stats and file counts are used to avoid reading manifests an operation does not need. File proliferation therefore grows the structures a query must traverse before reading anything, and it grows the number of open calls at the storage layer.
Spark's own model explains why streaming makes this worse. Structured Streaming treats a live stream as a table being continuously appended, and every trigger interval appends new rows — which, written to a lakehouse table, means new files per trigger (Spark Structured Streaming guide). A short trigger interval multiplies commits, and each commit adds files and metadata. The practical consequence: if latency creeps upward while compute utilization looks normal, suspect a metadata and file-open problem before you add capacity.
Diagnose before you compact: separating metadata overhead from file-open overhead
Diagnose first, because compaction only pays off when file count is the actual cause. Work through these steps in order and record what each one shows.
Count files and average file size per partition. If a hot partition holds many files well below your target, you have a small-file problem. If file counts look reasonable but reads are slow, look elsewhere before rewriting anything.
Time planning separately from execution. Measure query planning — metadata and manifest scanning — against data-read time. High planning time points to metadata overhead; high read time across many files points to per-file open cost.
Check manifest and metadata growth. A rising manifest count or growing metadata files signals that commits are accumulating structure faster than maintenance removes it. Iceberg merges manifests on write by default, targeting 8 MB per manifest and accumulating at least 100 before merging (Iceberg configuration reference), so a manifest count that keeps climbing means your commit rate is outpacing that merge.
Confirm the partition layout matches query filters. If queries filter on a column that is neither a partition nor a sort key, the engine opens more files than necessary. That is a partitioning or clustering problem, not a file-size problem.
Compare write cadence to file production. Note the trigger interval and the files produced per commit. A one-minute trigger that writes several files per commit explains growth that no amount of one-off compaction will fix.
Attribute latency to a layer. Use the split from steps 2 and 3 to decide whether the fix is compaction, repartitioning, clustering, or write-side batching.
The output is a short record: files per hot partition, planning versus read time, manifest growth trend, and write cadence. That record is your baseline, and it is what you compare against after each change. Without it, you cannot tell a successful compaction from one that merely moved cost around.
Compaction, clustering and partitioning are not the same fix
These three operations are routinely conflated, yet they solve different problems and carry different costs. Choosing the wrong one leaves the original problem in place and adds rewrite cost on top.
Compaction rewrites many small data files into fewer larger ones. It targets file count and the metadata and file-open overhead that comes with it.
Clustering reorganizes rows — by sorting or Z-ordering during a rewrite — so queries can skip more files using statistics. It targets data skipping, not file count as such.
Partitioning defines the layout that lets the engine prune whole partitions. It targets which files a query must consider at all.
Intervention | What it physically changes | Cost it targets | Expected effect when it fits | Cost and risk you accept |
|---|---|---|---|---|
Compaction (bin-pack rewrite) | Rewrites many small data files into fewer larger ones; file count drops, metadata stops growing per commit | Per-query planning plus one storage open per file | Fewer files per hot partition, so planning and file-open time fall | Rewrite compute and storage requests; competes with ingestion; may rewrite data a replay still needs |
Clustering (sort / Z-order rewrite) | Rewrites files with rows ordered so min/max and other statistics prune better | Files opened per query for selective filters | More files skipped per query on non-partition filter columns | Same rewrite cost as compaction, and benefit depends entirely on whether query filters match the sort key |
Partitioning (spec change) | Changes how future writes are physically split; existing files keep their old layout until rewritten | Files a query must consider at all | Pruning granularity matches the columns queries actually filter | Over-partitioning multiplies small files; the change needs planning and does not rewrite old data |
Read the table as a decision aid, not a menu — the three fixes are not interchangeable, and the cost column is why. Bin-pack compaction never sorts rows, so it will not rescue a query whose filter column is not a sort key. A sort rewrite can improve data skipping and may also change file count; measure both effects separately. A new partition spec only shapes future writes, which is why changing it never cleans up the small files already on disk.
Iceberg's rewrite_data_files procedure defaults to a bin-pack strategy and exposes target-file-size-bytes, min-file-size-bytes and max-file-size-bytes thresholds that decide which files qualify for rewriting; a sort strategy with a sort order or zorder(...) is what turns the same procedure into clustering (Iceberg Spark procedures). Partition evolution, by contrast, is a metadata operation that does not eagerly rewrite files — old data keeps its earlier layout and new data is written under the new spec, with each layout planned separately (Iceberg evolution). Changing a partition spec is therefore not a substitute for compacting existing data, and compacting existing data will not fix a spec that prunes badly.
Choosing a file-size target from measurement, not a universal number
There is no universal ideal file size. A target that suits a nightly batch table can be wrong for a low-latency streaming table, and the right number depends on your storage, your query engine, and how much rewriting you can afford. Iceberg treats it as a table property for exactly this reason: write.target-file-size-bytes defaults to 536870912 (512 MB) and is described as controlling the size of files generated to target about that many bytes (Iceberg configuration reference). That default is a starting point, not a verdict for your workload.
Derive your own target from three measurements:
Latency sensitivity. Measure planning and file-open time at your current file count, then at a reduced count after a trial compaction. The file count at which latency crosses your SLA sets an upper bound on how many files a hot partition should hold.
Storage request cost. Each file open is a request. If your object store bills or throttles per request, that cost belongs in the target calculation alongside read latency.
Rewrite cost. Larger target files mean more data rewritten per compaction run and longer jobs holding compute. Balance the read benefit against the write and compute cost, and against how often the streaming job will re-fragment the partition.
Set the target, re-measure planning and read time after compaction, and adjust. Treat the number as a hypothesis you validate on your own table rather than a constant you inherit from a blog post — including this one.
Designing compaction that does not fight streaming ingestion
Compaction and streaming ingestion compete for the same table, the same compute, and the same commit path. The goal is to compact without stalling writes and without deleting data a replay still needs. Roll out in this order.
Two things decide whether that works: when the rewrite runs, and how long superseded files stay reachable. Iceberg snapshot expiration defaults to 5 days with at least 1 snapshot retained, and Delta VACUUM defaults to 7 days, which Databricks also recommends as a floor. Those are starting points to override from your replay requirement, not targets. With that in mind, roll out the changes below in order.
Narrow the compaction scope. Restrict rewrites to partitions that are not being actively written. AWS's guidance on concurrent writes recommends narrowing maintenance operations like compaction to minimize overlap with other operations, giving the example of a table partitioned by date where a streaming job continuously upserts the latest date while compaction processes historical partitions via a
wherefilter (AWS Iceberg concurrency guidance). Expected outcome: fewer commit conflicts and steadier ingestion latency.Separate compaction from ingestion compute. Run compaction as its own job with its own resources. Hudi's clustering documentation describes this asynchronous model: a separate job schedules, plans and executes the operation, so fewer compute resources are needed for ingestion and ingestion latency stays stable, with lock providers configured for concurrency control across writer and table-service jobs (Hudi clustering). Expected outcome: ingestion latency decoupled from rewrite load.
Set concurrency and commit controls. Use the rewrite procedure's concurrency options —
max-concurrent-file-group-rewritesdefaults to 5 — and the table's commit retry properties so a long compaction does not fail on contention. Iceberg's commit retries default to 4 attempts with a 30-minute total retry timeout (Iceberg configuration reference). Expected outcome: compaction completes without repeated manual restarts.Protect replay retention before expiring anything. Confirm the retention window your replay and time-travel consumers need, then expire snapshots only beyond it. Iceberg's
expire_snapshotsdefaults to removing snapshots older than five days and retaining at least one ancestor snapshot, and snapshots still referenced by branches or tags are not removed (Iceberg Spark procedures). Expected outcome: replay still resolves after compaction.Verify after each run. Re-measure file count, planning time and read time for the compacted partitions, and confirm the streaming job's latency returned to baseline. Expected outcome: a documented before-and-after you can compare on the next run.
Step 4 is where safe compaction is won or lost. Compaction rewrites files and snapshot expiration removes the old ones; if expiration runs ahead of your replay window, a replay that depends on an expired snapshot fails. Set the retention window from your actual replay requirement rather than accepting a default because it is the default. The same discipline applies to orphan-file cleanup, which Iceberg's maintenance documentation warns must not use a retention interval shorter than the time expected for any write to complete (Iceberg maintenance).
Compaction should also not bypass the quality gates that sit between layers. A compacted partition still has to satisfy the same promotion checks before downstream consumers trust it, and the bronze, silver and gold promotion gates guide describes how those checks are enforced at layer boundaries — the same discipline of scoping, verifying and recording that compaction scheduling needs. Singdata sells a lakehouse platform, so it has a commercial interest in how you evaluate this pattern; the scheduling design above stands on its own regardless of which engine executes it.
Common misconceptions
"There is one ideal file size." The target depends on your latency SLA, storage request costs and rewrite budget. Iceberg exposes it as a configurable table property for that reason, with a 512 MB default that is a starting point rather than a rule.
"Compaction also improves data skipping." Plain bin-pack compaction reduces file count; it does not sort rows. Clustering is the operation that improves skipping, and it is a different strategy on the same rewrite procedure.
"Compaction is free because it runs in the background." It consumes compute and storage requests and competes with ingestion unless scoped and resourced separately. A background job that saturates the same cluster is not free.
"Expiring old snapshots is always safe after compaction." Only if the retention window covers your replay and time-travel needs. Expire too early and replay breaks, which is a correctness failure, not a performance trade-off.
"More partitions always mean faster queries." Over-partitioning produces small files and more metadata — the problem you started with, now harder to compact because the files are scattered across more partitions.
FAQ
Does compaction always reduce streaming latency?
No. It reduces latency only when file count and metadata overhead are the cause. If planning time stays flat as file count changes, and open calls are not the bottleneck, a rewrite spends compute and storage requests without moving the number you care about. Measure planning separately from data reads before scheduling anything, and treat a flat planning curve as a signal to look at clustering, partitioning or write-side batching instead.
How do I know if I have a small-file problem?
Count files and average file size per hot partition, then time planning separately from data reads. Many files well below your target size paired with planning time that grows in step with file count is the signature. Two caveats matter here. Average size across the whole table hides a single fragmented partition, so measure per partition. And a table with a modest file count can still plan slowly if the manifest structure has grown — check manifest growth as well as file size.
Can I compact a table that is actively receiving streaming writes?
Yes, provided you narrow the scope and separate the resources. Run the rewrite against partitions that are not currently being written, with a where filter that excludes the active one, and give compaction its own compute so a long rewrite job does not starve ingestion. Compacting the partition the stream is upserting into invites commit conflicts, retries and unpredictable latency on both sides. Commit retry settings soften contention but do not remove it.
Will compaction break time travel or replay?
Not by itself — a rewrite produces new files and a new snapshot while the previous ones stay referenced. The real risk is snapshot expiration running ahead of your replay window and deleting a snapshot that a replay still needs. Set the expiration threshold from the replay requirement you actually have, and remember that orphan-file cleanup has the same constraint: it must not use a retention interval shorter than the time any write may take to complete.
Is clustering a replacement for compaction?
No, and treating it as one is a common and expensive mistake. Clustering reorganizes rows within and across files so statistics can skip more of them; compaction reduces how many files exist. A clustered table with thousands of small files still pays per-file planning and open costs, and a compacted table with unsorted rows still opens every file for a selective filter. Most large streaming tables eventually need both, plus a partition layout that matches how people query.
References
Apache Iceberg table specification — manifest, manifest list and table metadata structure.
Apache Iceberg configuration reference —
write.target-file-size-bytes, manifest merge and commit retry properties.Apache Iceberg Spark procedures —
rewrite_data_filesstrategies, thresholds andexpire_snapshotsdefaults.Apache Iceberg maintenance — snapshot expiration, manifest compaction and orphan-file retention warnings.
Apache Iceberg evolution — partition and sort-order evolution as metadata operations.
AWS: managing concurrent write conflicts in Apache Iceberg — narrowing maintenance scope with a partition filter.
Apache Hudi clustering — asynchronous scheduling and execution by a separate process.
Spark Structured Streaming programming guide — micro-batch model and trigger intervals.
Use the medallion implementation checklist to coordinate maintenance with layer ownership and promotion gates.