Compaction, OPTIMIZE and Z-order
Streaming and frequent small writes leave tables full of tiny files, scattered data and slow queries. OPTIMIZE rewrites them into large files, and Z-order sorts data so queries can skip more of it. This lesson shows both, and how often to run them.
Step 3 · Data lake & lakehouse · Silver · Keeping tables fast, lesson 2 of 3
On this page
Show code in
Every code block on the page follows this.
Read first: Parquet and columnar storage · The small file problem (skip if you know them)
In plain words first
A filing cabinet where every letter is in its own folder is slow to search. Merging them into a few thick folders is compaction. Sorting the letters inside by sender and date, so you can jump straight to the right part, is clustering (Z-order is one way to sort by two things at once).
Compaction
from delta.tables import DeltaTable DeltaTable.forName(spark, "events").optimize() \ .where("event_date >= '2025-03-01'").executeCompaction()
-- Delta Lake OPTIMIZE events WHERE event_date >= '2025-03-01'; -- Apache Iceberg CALL catalog.system.rewrite_data_files( table => 'db.events', where => 'event_date >= "2025-03-01"');
- Delta OPTIMIZE bin-packs files toward a target size (1 GB by default, configurable).
- Iceberg rewrite_data_files targets
write.target-file-size-bytes(512 MB by default) and supports bin-pack and sort strategies. - Both commitcommit: One atomic change to a table: a new version that lists which files were added and removed. Learn more → atomically: readers see either the old files or the new ones. Old files stay until VACUUMVACUUM: The command that deletes data files no longer in the table, once they are older than the retention period. Learn more → or snapshotsnapshot: A complete, consistent version of a table at one moment. Readers always see one snapshot, never a half-finished write. Learn more → expiration.
- Compaction is idempotentidempotent: Safe to run again: running a step twice gives the same result as running it once. Learn more →: running it on already compacted data does little.
Why clustering matters
File skipping uses min/max statistics per file. If rows are in arbitrary order, every file contains every customer, every file's range for customer_id spans almost everything, and a filter on one customer reads all files. Clustering puts similar values together so ranges are narrow.
| Layout | Files read for customer_id = 42 |
|---|---|
| Random order, 1,000 files | ≈ 1,000 (each file spans all ids) |
| Sorted by customer_id | 1 or 2 |
| Z-ordered by (customer_id, product_id) | A few, and also a few for a product_id filter |
Z-ordering
Sorting by one column clusters only that column perfectly; the second sort column is clustered only within ties of the first. A Z-order curve interleaves the bits of several columns, so rows close in any of them tend to land in the same file. It gives good, not perfect, skipping on each column.
# Delta Lake spark.sql("OPTIMIZE events ZORDER BY (customer_id, product_id)") # Apache Iceberg spark.sql(""" CALL catalog.system.rewrite_data_files( table => 'db.events', strategy => 'sort', sort_order => 'zorder(customer_id, product_id)') """)
-- Delta Lake OPTIMIZE events ZORDER BY (customer_id, product_id); -- Apache Iceberg CALL catalog.system.rewrite_data_files( table => 'db.events', strategy => 'sort', sort_order => 'zorder(customer_id, product_id)');
- Choose columns used in filters and joins with many distinct values, such as ids. Low-cardinalitycardinality: How many distinct values a column has. User ids are high cardinality; country codes are low. Learn more → columns are better as partitions or not needed.
- Effectiveness drops with each added column; two to four is typical.
- Z-ordering a column with no statistics (beyond the first 32 columns in Delta) is useless.
- Delta Z-order is not incremental: re-running it rewrites the affected data. Liquid clustering is the incremental successor.
How often
Compaction costs compute: it reads and rewrites data. Common practice is a daily or weekly job per table, limited to recent partitions with a WHERE clause, since old partitions rarely change. Streaming tables with many small commits need it more often, or auto compaction. Measure the average file size (DESCRIBE DETAIL, or Iceberg's files table) and the bytes scanned by common queries before and after to decide.
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 Delta Lake, with spark already created: each builds its own data.
Goal: Merge many small files into fewer large ones, and cluster them by the column queries filter on.
import os from pyspark.sql import functions as F path = os.path.abspath("lab/optimize/events") df = spark.range(0, 200_000).withColumn( "customer_id", (F.rand(seed=3) * 5000).cast("int")) for i in range(20): # 20 small appends batch = df.where(F.col("id") % 20 == i).repartition(4) batch.write.format("delta").mode("append").save(path) def files(): return spark.sql(f"DESCRIBE DETAIL delta.`{path}`").first()["numFiles"] print("files before:", files()) result = spark.sql(f"OPTIMIZE delta.`{path}` ZORDER BY (customer_id)").first() print("removed", result.metrics.numFilesRemoved, "files,", "added", result.metrics.numFilesAdded) print("files after:", files())
Output from a real run
files before: 80 removed 80 files, added 1 files after: 1
What to notice:
- 20 small appends left 80 files;
OPTIMIZEreplaced them with 1. - The 80 old files are still on disk for time traveltime travel: Reading a table as it was at an earlier version or time. Learn more →, until
VACUUMremoves them. - On a real table it targets files of about 1 GB, so you get many clustered files, not one.
Common mistakes
- Z-ordering by a low-cardinality column — Gains little; partitioning or nothing is better.
- Z-ordering by many columns — Each column gets weaker clustering.
- Compacting the whole table every day — Rewrites unchanged data. Limit to recent partitions.
Key takeaways
- Compaction rewrites small files into large ones in one atomic commit.
- File skipping only works when data is clustered by the filtered column.
- Z-order clusters by several columns, with decreasing effect per column.
- Schedule maintenance on recent data and measure the gains.
Interview prep
THE QUESTION
"Queries filter by customer_id and are slow on a large Delta table. What do you do?"
Avoid: "run OPTIMIZE" without checking file sizes and data layout first, and verifying files skipped afterwards.
Follow-ups · answer out loud, then open
Follow-up"How many columns should you Z-order by?"
Scenario"Nightly OPTIMIZE ZORDER on a 50 TB table takes six hours. What could you do?"
Trap"Z-ordering makes queries on every column faster."
Check yourself
3 questionsWhy does Z-ordering speed up filters?
Show the answer
It clusters similar values into the same files, narrowing per-file min/max ranges. Narrow ranges let file statistics rule out most files.
Which column is the best Z-order candidate?
Show the answer
customer_id (millions of values, often filtered). High-cardinality, frequently filtered columns benefit most.
What happens to readers while OPTIMIZE runs?
Show the answer
They keep reading the old version until the new one commits. Compaction is one atomic commit; readers use snapshots.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · Keeping tables fast · lesson 3 of 3 · 6 min readVACUUM and retention
Delete old data files safely without breaking running readers or time travel.
Related lessons
The small file problemData lake & lakehouse · 5 min read
Liquid clustering
Previous: Partitioning done right
Primary sources: Delta: optimizations · Iceberg: maintenance