VACUUM and retention
Every update, delete and compaction leaves old files behind, because time travel and running readers may still need them. VACUUM deletes them once they are old enough. This lesson shows how to do that safely, without breaking running queries or the time travel you rely on.
Step 3 · Data lake & lakehouse · Silver · Keeping tables fast, lesson 3 of 3
On this page
Show code in
Every code block on the page follows this.
Read first: The Delta transaction log · Time travel and RESTORE (skip if you know them)
In plain words first
A shared document keeps old versions so anyone can look back. But storage is not free, so versions older than a month are deleted. If someone is reading a two-month-old version at that moment, their page vanishes.
VACUUM is that clean-up for a table, and the retention period is how old a file must be before it can go.
Why old files pile up
Every UPDATE, DELETE, MERGE and OPTIMIZE removes files from the table by writing remove actions, but the files themselves stay on storage. That is what makes time traveltime travel: Reading a table as it was at an earlier version or time. Learn more → and snapshotsnapshot: A complete, consistent version of a table at one moment. Readers always see one snapshot, never a half-finished write. Learn more → isolation work. Without cleanup, storage grows forever: a table that is compactedcompaction: Rewriting many small files into fewer large ones, without changing the rows. Learn more → daily can easily hold several times its live size in old files.
What VACUUM deletes
- Files that are not referenced by the current version of the table, and
- were removed (or written by failed jobs) longer ago than the retention threshold:
delta.deletedFileRetentionDuration, 7 days by default. - It never deletes files the current version uses, and it does not touch the transaction logtransaction log: The ordered list of commits that defines which files make up a Delta table at each version. Learn more →; log cleanup happens separately at checkpointscheckpoint: In Delta Lake, a Parquet file in _delta_log that summarises every commit up to one version, so readers load it instead of replaying all the JSON commits before it. Learn more →.
from delta.tables import DeltaTable DeltaTable.forName(spark, "events").vacuum() # default retention DeltaTable.forName(spark, "events").vacuum(240) # keep 240 hours (10 days)
VACUUM events DRY RUN; -- list what would be deleted VACUUM events; -- default 7 days VACUUM events RETAIN 240 HOURS; -- 10 days
Why the threshold matters
09:00 · long query starts
09:20 · OPTIMIZE
09:25 · VACUUM RETAIN 0
09:30 · failure
Delta refuses retention below the default unless you disable spark.databricks.delta.retentionDurationCheck.enabled. Keep the threshold longer than your longest running query, your slowest streaming consumer, and the time travel window you promise users.
In Iceberg
# Remove old snapshots and the files only they reference spark.sql(""" CALL catalog.system.expire_snapshots( table => 'db.events', older_than => TIMESTAMP '2025-03-01 00:00:00', retain_last => 10 ) """) # Remove files no metadata references at all (failed writes) spark.sql("CALL catalog.system.remove_orphan_files(table => 'db.events')")
-- Remove old snapshots and the files only they reference CALL catalog.system.expire_snapshots( table => 'db.events', older_than => TIMESTAMP '2025-03-01 00:00:00', retain_last => 10 ); -- Remove files no metadata references at all (failed writes) CALL catalog.system.remove_orphan_files(table => 'db.events');
Iceberg splits the job in two: expiring snapshots deletes files that only expired snapshots used; removing orphan files cleans up files no snapshot ever committed. Orphan removal defaults to files older than 3 days, for the same reason as Delta's threshold: an in-progress write's files look like orphans until it commits.
Running it in production
- Schedule it (daily or weekly), after compaction jobs.
- Run
DRY RUNthe first time and after changing retention. - VACUUM must list the table's files, which can be slow on huge tables; newer Delta versions offer a lighter mode that uses the log instead of a full listing.
- Coordinate with compliance: deleting a person's rows with DELETE does not remove the data from storage until VACUUM runs after retention.
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: Run routine maintenance: compact the files, then delete old ones with a safe retention period.
import os path = os.path.abspath("lab/vacuum/events") for i in range(5): batch = spark.range(i * 1000, (i + 1) * 1000) batch.write.format("delta").mode("append").save(path) # the old small files are now unused spark.sql(f"OPTIMIZE delta.`{path}`") def maintain(table_path, retain_hours=168): # 7 days, the default vacuum = f"VACUUM delta.`{table_path}` RETAIN {retain_hours} HOURS" print(spark.sql(vacuum + " DRY RUN").count(), "files would be deleted") spark.sql(vacuum) maintain(path)
Output from a real run
0 files would be deleted
What to notice:
0 files would be deleted: the filesOPTIMIZEreplaced are only seconds old, so the 7-day retention protects them.- That margin is deliberate: keep retention longer than your longest query, your stream lag and your time-travel needs.
Goal: See what VACUUM with no retention does to time travel.
import os, re path = os.path.abspath("lab/vacuum/t") spark.range(0, 1000).write.format("delta").mode("overwrite").save(path) # replaces every file spark.range(0, 500).write.format("delta").mode("overwrite").save(path) try: spark.sql(f"VACUUM delta.`{path}` RETAIN 0 HOURS") except Exception as e: print("RETAIN 0 HOURS is refused:", str(e).split(".")[0][:80]) # never in prod spark.conf.set("spark.databricks.delta.retentionDurationCheck.enabled", "false") spark.sql(f"VACUUM delta.`{path}` RETAIN 0 HOURS") try: # collect(), not count(): Delta answers count() from the log alone spark.read.format("delta").option("versionAsOf", 0).load(path).collect() except Exception as e: error = re.search(r"\[[A-Z_.]+\]", str(e)) reason = error.group() if error else type(e).__name__ print("time travel to version 0 after vacuum:", reason)
Output from a real run
RETAIN 0 HOURS is refused: [DELTA_VACUUM_RETENTION_PERIOD_TOO_SHORT] The specified VACUUM retention period time travel to version 0 after vacuum: [FAILED_READ_FILE.FILE_NOT_EXIST]
What to notice:
- Delta first refuses
RETAIN 0 HOURS: a safety check. - With the check turned off, VACUUM deleted version 0's files, and reading version 0 failed:
FILE_NOT_EXIST. - The log still lists version 0; only its files are gone. A plain
count()would still answer, from the row counts in the log, which is why the lab reads the rows.
Common mistakes
- VACUUM RETAIN 0 HOURS — Breaks running queries, streams and time travel.
- Never vacuuming — Storage grows with every rewrite.
- Assuming DELETE removes data physically — For GDPR erasure, the old files must also be vacuumed.
Key takeaways
- Removed files stay on storage until VACUUM, enabling time travel and snapshot reads.
- VACUUM deletes unreferenced files older than the retention threshold (7 days).
- Never set retention shorter than your longest reader or time-travel needs.
- Iceberg uses expire_snapshots and remove_orphan_files.
Interview prep
THE QUESTION
"Storage costs for our Delta tables doubled although data volume is flat. Why?"
Avoid: "run VACUUM RETAIN 0 HOURS". It deletes files that running queries, streams and time travel still need.
Follow-ups · answer out loud, then open
Follow-up"What is the default retention for VACUUM, and why that number?"
delta.deletedFileRetentionDuration). It must exceed your longest-running query or stream and any time travel you rely on. Shorter retention requires disabling a safety check.Scenario"After VACUUM, a streaming job reading the table fails with FileNotFoundException. Why?"
Trap"VACUUM also cleans up old _delta_log files."
Check yourself
3 questionsWhich files can VACUUM delete?
Show the answer
Files not referenced by the current version and removed longer ago than the retention. Both conditions must hold.
Why can VACUUM RETAIN 0 HOURS break a running query?
Show the answer
It deletes files that an older snapshot the query is reading still needs. Running queries read a fixed version whose files may have just been removed from the current one.
Iceberg equivalent for deleting files used only by old versions?
Show the answer
expire_snapshots. Expiring snapshots deletes files that only those snapshots referenced.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · new module: Iceberg and Hudi · 6 min readIceberg metadata tree
Metadata files, snapshots, manifest lists and manifests, and how query planning uses them.
Related lessons
Time travel and RESTOREData lake & lakehouse · 5 min read
Compaction, OPTIMIZE and Z-orderData lake & lakehouse · 8 min read
The Delta transaction log
Previous: Compaction, OPTIMIZE and Z-order
Primary sources: Delta: VACUUM · Iceberg: maintenance