Sub topic 11
Cleaning up with VACUUM
This chapter assumes you can read basic SQL, know that a Delta table is Parquet data files plus a transaction log, and have run OPTIMIZE on a table. By the end you will know why OPTIMIZE leaves old files behind, how VACUUM removes them, and what you give up when you do.
Why OPTIMIZE does not shrink storage
OPTIMIZE never edits a Parquet file in place. It reads many small files, writes new larger files, and records the change in the transaction log. The log marks the old files as removed and the new files as added. The old files stay in cloud storage.
They stay for two reasons:
- Time travel. Queries such as
SELECT * FROM events VERSION AS OF 12need the files that belonged to version 12. - Concurrent readers. A query that started before the
OPTIMIZEfinished may still be reading the old files. Deleting them immediately would make that query fail.
So after a compaction, a table's storage use goes up, not down. The table holds both the compacted files and the files they replaced. The same happens after UPDATE, DELETE, and MERGE, which also rewrite files.
What VACUUM does
VACUUM deletes data files that meet both conditions:
- The current table version does not reference the file.
- The file is older than the retention threshold.
The default threshold is 7 days. You can state it explicitly:
VACUUM events RETAIN 168 HOURS;168 hours is 7 days. VACUUM does not touch files that the current version of the table uses, and it does not delete the transaction log. It also does not remove files from the log's history. It only removes the data files that the history points to.
Preview with DRY RUN
Before deleting anything, list what would be removed:
VACUUM events DRY RUN;The output is a list of file paths, capped at a limited number of rows. Use it to check that the scale of the deletion matches what you expect. A very long list on a table you compacted yesterday is normal. A long list on a table you have never changed is worth investigating.
The cost of VACUUM: time travel and long-running readers
After VACUUM, you cannot read versions that depended on the deleted files. The log still lists those versions, but a query against them fails with a file-not-found error.
The retention threshold is therefore a choice about how far back you need to read:
| Retention | Storage cost | Time travel window | Risk to long queries |
|---|---|---|---|
| Short (for example 1 day) | Lower | Short | Higher |
| Default (7 days) | Moderate | 7 days | Low |
| Long (for example 30 days) | Higher | 30 days | Very low |
Keep these points in mind when you pick a value:
- The retention period must be longer than your longest-running query or stream that reads the table. If a job runs for 10 hours, a 1-hour retention can delete files the job still needs.
- A streaming job that falls behind reads old versions. If it lags more than the retention period, it can fail.
VACUUMdoes not affectRESTOREto a version whose files were deleted. That restore will fail.
Retention properties
You can set retention on the table instead of passing it to each command. Two table properties control it:
ALTER TABLE events SET TBLPROPERTIES (
'delta.deletedFileRetentionDuration' = 'interval 14 days',
'delta.logRetentionDuration' = 'interval 30 days'
);delta.deletedFileRetentionDurationis the minimum age before an unreferenced data file may be deleted. A plainVACUUM events;uses it. The default is 7 days.delta.logRetentionDurationis how long the log keeps history entries. It is the upper bound on how far back time travel can go. The default is 30 days.
Time travel needs both the log entry and the data files. The shorter of the two settings sets your real window. If the log keeps 30 days but files survive only 7, you can read back about 7 days.
The safety check on short retention
Databricks refuses to run VACUUM with a retention below the configured minimum, which is 7 days by default. This guard exists because a short retention can corrupt a running query's view of the table.
If you only need to reduce storage quickly on a table nobody else is using, a short retention can be appropriate. On shared production tables, leave the check on.
Running VACUUM after OPTIMIZE
A common maintenance order is:
- Run
OPTIMIZEto compact files and apply Z-order or clustering. - Run
VACUUMlater, once the retention period has passed.
Running VACUUM right after OPTIMIZE frees nothing from that compaction, because the files it replaced are younger than the threshold. The space comes back only after the retention period ends. That is why a schedule works better than a single command. A daily or weekly VACUUM job reclaims files whose age has just passed the threshold.
You can see the effect with DESCRIBE DETAIL, which reports only the files in the current version:
DESCRIBE DETAIL events;Its numFiles and sizeInBytes values describe the active table, not the storage folder. After OPTIMIZE, numFiles drops at once. The cloud storage bill does not drop until VACUUM removes the old files. To compare the two, check the size of the table's storage location with your cloud provider's tools or a dbutils.fs.ls listing.
Running VACUUM from Python
The Delta Python API offers the same operation:
from delta.tables import DeltaTable
dt = DeltaTable.forName(spark, "events")
# Preview first, then delete
dt.vacuum(168)The argument is the retention in hours. Calling dt.vacuum() with no argument uses the table's configured retention.
Common errors and gotchas
- Expecting space back immediately. Files younger than the retention period are never deleted. Wait, or schedule the job.
- Lowering retention to save money. This silently shortens your time travel window and can break long-running readers. Check the longest job first.
- Vacuuming a table that other tools read directly. If an external engine reads the Parquet files by path, it does not use the log to find the current files. Deleting files it expects can break it.
- Running with a very short retention on a shared table. Disable the safety check only for isolated tables.
- Assuming VACUUM shrinks the log. It does not. Log cleanup follows
delta.logRetentionDurationand happens automatically when checkpoints are written. - Treating VACUUM as part of OPTIMIZE. They are separate commands.
OPTIMIZErewrites files.VACUUMdeletes them.
How this fits with predictive optimization
For Unity Catalog managed tables, predictive optimization can run VACUUM for you, along with OPTIMIZE. The next chapter covers it. Even then, the retention you configured still applies, so the trade-off in this chapter remains yours to decide.
Exercise
Your team runs OPTIMIZE on the events table every night. DESCRIBE DETAIL shows numFiles fell from 40,000 to 800, but your cloud storage bill for the table is higher than last month. You run VACUUM events RETAIN 168 HOURS right after the latest OPTIMIZE and see almost no space freed. Explain both observations and describe what to change.
Show answer
OPTIMIZE writes new compacted files and marks the old ones as removed in the log, but leaves them in storage. DESCRIBE DETAIL counts only files in the current version, so numFiles falls while total storage grows, because both old and new files exist. VACUUM frees almost nothing because the files replaced by the latest OPTIMIZE are younger than the 168-hour threshold. Only files that are both unreferenced and older than 7 days are deleted. Schedule VACUUM to run regularly (for example daily or weekly) so files are deleted as they cross the threshold. If a shorter time travel window is acceptable, and no reader runs longer than the new value, you can lower delta.deletedFileRetentionDuration, but avoid going below the 7-day safety minimum on shared tables.
Exercise
A table has delta.logRetentionDuration set to 60 days and delta.deletedFileRetentionDuration set to 3 days, and VACUUM runs daily. How far back can you reliably query with time travel, and why?
Show answer
About 3 days. The log keeps entries for 60 days, so versions still appear in the history, but VACUUM deletes unreferenced data files older than 3 days. Queries on older versions fail because their data files are gone. The shorter of the two settings sets the practical time travel window.