Apache iceberg compaction what fewer files can and cant tell you about query speed?
In this article
- Why Iceberg Tables Accumulate Files
- What Compaction Actually Does (and Doesn't Do)
- When Fewer Files Means Faster Queries
- When Fewer Files Doesn't Mean Faster Queries
- How to Choose Compaction Targets
- Common Misconceptions and Pitfalls
- Compaction vs. Other Optimization Techniques
- Costs and Safety Considerations
- Frequently Asked Questions
Apache Iceberg compaction reduces the number of data files in a table, but fewer files alone do not guarantee faster queries. Query speed depends on how the files align with your query's filters, the file format, and whether you're running metadata-only or scan-heavy operations. Compaction helps most for small-file problems, yet it can hurt performance if done blindly or too aggressively.
Why Iceberg Tables Accumulate Files
Iceberg is built for streaming and incremental writes. Every commit—whether from a Spark, Flink, or Trino job—creates new data files. Over time, especially with frequent micro-batches, you end up with thousands of tiny files. This is often called the "small files problem."
Each file has overhead: metadata in the manifest, listing time, and per-file processing. When you query a table with 50,000 small files, the engine must read many small objects from storage, which adds latency. Compaction rewrites these small files into larger ones, reducing the number of files the engine has to touch.
But compaction is not a magic speed-up. It's a maintenance operation that trades write-time cost for read-time benefit. Understanding what it can and cannot do helps you decide when to run it and how to measure its impact.
What Compaction Actually Does (and Doesn't Do)
Iceberg compaction rewrites data files that meet certain criteria (like being too small or having too many deletes) into fewer, larger files. It does not change the table's schema, partition layout, or file format unless you explicitly choose to rewrite into a different format (e.g., from Parquet to ORC, though that's rarely done).
Compaction also does not sort data by default. Some engines (like Spark) offer sort-based compaction, but the standard Iceberg rewrite just merges files. If you want to make queries faster by clustering related data, you need to enable sorting or use a separate clustering operation.
What compaction can do:
- Reduce the number of files, lowering metadata overhead.
- Remove rows that are marked for deletion (from deletes or updates), shrinking table size.
- Improve scan throughput for full-table scans or queries that read most of the data.
What it cannot do:
- Make all queries faster—especially those that use selective filters and rely on partitioning or statistics.
- Fix poorly chosen partition schemes.
- Compensate for a bad file format or compression choice.
When Fewer Files Means Faster Queries
Fewer files help most when your query has to read a large fraction of the table. For example, a SELECT COUNT(*) FROM events or an aggregation over many partitions benefits from fewer, larger files because the engine spends less time opening files and more time reading data.
Another clear win is when you have many tiny files (e.g., under 128 MB) that cause excessive network round-trips. Compacting them into files of 256 MB or 512 MB can cut query time by 30–70% in those cases.
Also, if your table has many delete files (from updates or merges), compaction can merge those deletes into the data files, reducing the overhead of applying them during reads. This directly speeds up queries that touch updated rows.
When Fewer Files Doesn't Mean Faster Queries
Here's the counterintuitive part: compaction can sometimes make queries slower.
If you have a highly selective query that reads only a few rows from a specific partition, the engine can use Iceberg's metadata to skip entire files. With many small files, it can skip most of them and read only the one or two that match. After compaction, those rows might be spread across fewer, larger files, forcing the engine to read a bigger file to find the same rows.
For example, imagine you have 100 files of 10 MB each, and a query filters on a column that only exists in one of them. The engine reads 10 MB. After compaction, you have 10 files of 100 MB each. The same query now reads 100 MB. That's 10x slower for that query.
Compaction also rewrites data, which costs CPU and I/O. If you run compaction too frequently, you're spending resources that could go to queries. And if you compact files that are already optimally sized, you gain nothing.
How to Choose Compaction Targets
There's no one-size-fits-all answer, but a common heuristic is to compact files smaller than 128 MB (or your block size) up to a target of 256–512 MB. Many engines have default thresholds: Spark's rewriteDataFiles uses a target file size of 512 MB by default.
You should also consider your query patterns. If your queries are mostly full scans, larger files are better. If they're point lookups or narrow range scans, smaller files might be better—but you also need good partitioning and statistics.
A practical approach:
- Monitor your table's file sizes and counts.
- Run compaction when the average file size is below 100 MB or when you have many small files.
- Set a target file size that matches your storage and query engine (e.g., 256 MB for Parquet on S3).
- Use Iceberg's
rewrite_data_filesprocedure with amin_file_sizeandmax_file_sizethreshold.
Common Misconceptions and Pitfalls
One big misconception is that fewer files always mean faster queries. As shown above, it depends on the query. Another is that compaction is a one-time fix. New writes will create new small files, so compaction is an ongoing maintenance task.
A common pitfall is compacting too often or without considering the partition layout. If you compact across partitions, you might create files that span partition boundaries, which breaks partition pruning. Iceberg's rewrite procedure usually respects partitioning, but you should verify.
Also, don't confuse compaction with clustering. Clustering sorts data within files to improve filter efficiency. Compaction only merges. If you need sorted data, use a clustering operation (e.g., Spark's optimize with sort) after compaction.
Compaction vs. Other Optimization Techniques
Compaction is just one tool. Others include:
- Partitioning – Choosing the right partition columns can drastically reduce data scanned.
- File format – Parquet and ORC offer columnar compression and predicate pushdown.
- Statistics and manifests – Iceberg uses stats to skip files; keeping them accurate helps.
- Z-ordering or sorting – Clusters similar values together, improving filter performance.
Compaction works best when combined with these. For example, compacting and then sorting by a frequently filtered column can give you both fewer files and better skip rates.
Costs and Safety Considerations
Compaction is not free. It reads and writes data, consuming CPU and storage I/O. On cloud storage like S3, it also incurs request costs. You should schedule compaction during off-peak hours or use Iceberg's built-in optimizers that run in the background (like in AWS Glue or Snowflake).
Safety is generally good: Iceberg's snapshot isolation means compaction creates new files and doesn't delete old ones until you expire snapshots. That means you can roll back if something goes wrong. However, you should still monitor the compaction job for failures and ensure you have enough storage for the temporary files.
Also, be aware that compacting a table with many deletes can temporarily increase storage usage before the old snapshots are expired. Plan accordingly.
Frequently Asked Questions
Does compaction always improve query performance?
No. It improves performance for scans and aggregations that read most of the table, but can hurt selective queries that rely on file skipping. Test with your actual workload.
How often should I run compaction?
It depends on write frequency. If you write micro-batches every minute, you may need to run compaction hourly or daily. Monitor the file count and size, and run when the average file size falls below your target.
What is the ideal file size for Iceberg?
There's no universal number, but a common target is 256–512 MB for Parquet on object storage. Smaller files (e.g., 64 MB) might be fine for low-latency queries, but larger files reduce overhead for scans.
Can compaction cause data loss?
No. Iceberg's compaction is atomic and uses snapshots. Old files are kept until you expire snapshots, so you can roll back. Always keep a few snapshots for safety.
Does compaction affect concurrent writes?
Iceberg uses optimistic concurrency. Compaction writes new files and commits them as a new snapshot. If a concurrent write conflicts, the compaction may retry or fail, but it won't corrupt data.
Should I compact before or after clustering?
Typically, you compact first to reduce file count, then cluster to sort data. Some engines combine both in one operation. The order depends on your engine's capabilities.