Sub topic 14
Keeping tables healthy with OPTIMIZE and VACUUM
This chapter assumes you can create and modify Delta tables with SQL. You should also know that every write creates a new table version in the transaction log, and that RESTORE and time travel read older versions. Both commands here build on those ideas.
Every INSERT, UPDATE, DELETE and MERGE adds files to a Delta table and may stop referencing others. Over time two problems appear:
- Too many small files. Frequent small appends and streaming writes produce thousands of tiny Parquet files. Each file costs a metadata lookup and an open call, so queries slow down.
- Unreferenced files that take up storage. Delta never edits a data file in place. An
UPDATEwrites new files and marks the old ones as removed in the log. The old files stay in cloud storage so that time travel and concurrent readers keep working.
OPTIMIZE addresses the first problem. VACUUM addresses the second.
What OPTIMIZE does
OPTIMIZE rewrites many small files into fewer, larger ones. It is a normal Delta transaction. It adds the compacted files and marks the small ones as removed, and it produces a new table version.
OPTIMIZE main.sales.orders;Key properties:
- Data does not change. Readers see the same rows before and after. Only the physical layout changes.
- Readers are not blocked. A query that started before
OPTIMIZEkeeps reading the old files. A query that starts afterward reads the new ones. - It is incremental and safe to repeat. Files that are already large enough are skipped. Running it twice in a row does little the second time.
- It does not delete anything. The replaced small files remain in storage until
VACUUMremoves them. Right afterOPTIMIZE, storage use often goes up, not down. - It targets a file size. The default target is about 1 GB, and Databricks may choose a smaller size for small tables based on table size and workload. You can override it with the
delta.targetFileSizetable property.
The command returns one row of metrics, including the number of files added and removed. The DESCRIBE DETAIL command shows the current file count:
DESCRIBE DETAIL main.sales.orders;Compare the numFiles and sizeInBytes columns before and after OPTIMIZE to see the effect.
Limiting the work with WHERE
On a partitioned table you can optimize only some partitions. The predicate may reference only partition columns.
OPTIMIZE main.sales.orders_partitioned
WHERE order_date >= '2026-11-01';This is useful on large tables where only recent partitions receive small writes. Rewriting old partitions again would waste compute.
OPTIMIZE and data layout
What OPTIMIZE does besides compaction depends on how the table is laid out.
| Table layout | What OPTIMIZE does |
|---|---|
| No clustering, no partitioning | Compacts small files |
| Partitioned | Compacts files inside each partition |
| Partitioned or unclustered, with `ZORDER BY (col)` | Compacts and co-locates rows with similar values of `col` |
| Liquid clustering (`CLUSTER BY`) | Compacts and incrementally clusters data by the clustering keys |
For a table created with CLUSTER BY (event_date), as in the earlier layout chapter, OPTIMIZE is how new data actually gets clustered. Rows you write are not fully clustered until OPTIMIZE runs. Plain OPTIMIZE is all you need, and you do not specify the keys again. ZORDER BY is the older technique. You cannot combine it with liquid clustering on the same table.
OPTIMIZE main.sales.legacy_orders
ZORDER BY (customer_id);ZORDER BY rewrites more data than plain compaction, so it costs more. It is not incremental in the same way, because it reorganizes files within each partition.
What VACUUM does
VACUUM deletes data files from storage when both conditions are true:
- The current table version no longer references the file.
- The file is older than the retention threshold.
VACUUM main.sales.orders RETAIN 168 HOURS;The default retention is 7 days, which is 168 hours. Writing RETAIN 168 HOURS states the default explicitly. Without the clause, Delta uses the table property delta.deletedFileRetentionDuration, which defaults to interval 7 days.
Preview the deletion first with DRY RUN. It lists the files that would be removed and deletes nothing.
VACUUM main.sales.orders DRY RUN;What VACUUM does not touch
- Referenced files. Any file in the current version is safe.
- The transaction log. Log files (
_delta_log) are not removed byVACUUM. Delta cleans up old log entries itself as it writes checkpoints, based ondelta.logRetentionDuration(default 30 days). - Files inside
_delta_logand some hidden paths.VACUUMskips directories whose names begin with an underscore or a dot, such as_delta_log.
The cost of VACUUM: time travel
Time travel and RESTORE need the data files of the old version. After VACUUM removes them, those versions can no longer be read, even though DESCRIBE HISTORY still lists them.
Suppose a bad DELETE happened 10 days ago, and VACUUM has run with the 7-day default. The log still shows the version before the delete. But this fails because the files are gone:
RESTORE TABLE main.sales.orders TO VERSION AS OF 3;So the retention period is your recovery window. Choose it based on how long it takes your team to notice and fix mistakes.
Shortening retention
Delta refuses RETAIN values below the table's retention threshold. It raises an error unless you disable spark.databricks.delta.retentionDurationCheck.enabled. The check exists for a reason. A running query or a stream may still be reading an older file. If VACUUM deletes that file, the reader fails with a "file not found" error. Retention must be longer than your longest-running query and longer than the maximum lag of any stream or reader that uses the table.
To change the default for a table instead of overriding per command:
ALTER TABLE main.sales.orders SET TBLPROPERTIES (
'delta.deletedFileRetentionDuration' = 'interval 14 days',
'delta.logRetentionDuration' = 'interval 60 days'
);Keep the two values consistent. History that is retained in the log but vacuumed from storage is not queryable, and log entries that expire early shorten your time travel window anyway.
Running the commands from Python
You can run both commands from a notebook or job with spark.sql. This is handy when you loop over several tables.
tables = ["main.sales.orders", "main.sales.events"]
for t in tables:
spark.sql(f"OPTIMIZE {t}")
spark.sql(f"VACUUM {t}")The order matters. OPTIMIZE first creates unreferenced files. A VACUUM run afterward removes the ones that have passed retention. Files from today's OPTIMIZE will not be deleted by today's VACUUM, because they are younger than the retention period.
Automating maintenance
You do not always have to schedule these commands yourself.
- Predictive optimization. For Unity Catalog managed tables, Databricks can run
OPTIMIZEandVACUUMfor you based on table usage. It is controlled at the account, catalog or schema level. Check that it is enabled in your workspace before you add scheduled jobs. Running both would duplicate work. - Optimized writes. The table property
delta.autoOptimize.optimizeWritemakes each write produce larger files by shuffling data before writing. - Auto compaction. The property
delta.autoOptimize.autoCompacttriggers a small compaction after a write finishes when a partition has many small files.
ALTER TABLE main.sales.orders SET TBLPROPERTIES (
'delta.autoOptimize.optimizeWrite' = 'true',
'delta.autoOptimize.autoCompact' = 'true'
);These settings reduce small files at write time, but they add a little latency to each write. They do not replace VACUUM, and they do not do the clustering that a full OPTIMIZE performs.
Trade-offs and common mistakes
- Optimizing too often. Each run costs compute. On a table that receives one large batch per day, daily
OPTIMIZEis plenty. On a streaming table with constant small writes, run it more often, or use auto compaction. - Expecting storage to shrink after OPTIMIZE. It will not, until
VACUUMremoves the old files. - Vacuuming with a short retention on tables that have long readers. This causes failures in other people's queries.
- Forgetting that retention is your undo window. A shorter window saves storage and limits recovery.
- Optimizing everything. Very small tables gain nothing. Focus on large, frequently written tables.
- Unclustered large tables. If queries filter on a column, a layout keyed on that column (liquid clustering) gives
OPTIMIZEsomething useful to do beyond compaction.
Exercise
A table receives small appends every few minutes. You run OPTIMIZE at noon, and then VACUUM with the default retention at 12:05. Afterward, storage use has gone up and the small files are still there. Why, and what must happen before storage shrinks?
Show answer
OPTIMIZE adds the new compacted files and marks the small files as removed, but it does not delete them. VACUUM deletes only files that are unreferenced and older than the retention period, which is 7 days by default. At 12:05 the small files became unreferenced only minutes ago, so VACUUM keeps them. Storage shrinks after the retention period passes and VACUUM runs again, for example the following week.
Exercise
Your team wants to be able to RESTORE a table up to 30 days back. Which two table properties should you check, and what happens if only one is set to 30 days?
Show answer
Check delta.deletedFileRetentionDuration, which controls how long VACUUM keeps unreferenced data files, and delta.logRetentionDuration, which controls how long log history is kept. Both need to cover 30 days. If the file retention is shorter, VACUUM deletes the data files and RESTORE fails even though the history lists the version. If the log retention is shorter, the version disappears from the history, so you cannot target it.