Zero Labs
Industry News / AI

Part XX — Delta Lake’s Transaction Log: Time Travel, VACUUM, and the Files That Never Die

Source · Towards AI By chakshu_salgotra

From the publisher’s feed, collected in the ZeroLabs newsroom.

Your table never deletes anything. The Delta log is an append-only ledger, and every file you “removed” is still sitting on S3 until the log’s retention rules, the checkpoint cadence, and your VACUUM discipline all agree it can die. Misunderstand any one of the three and you get a $41,000-a-month storage bill — or worse, a restore that points at files which no longer exist.Part I | Part II | Part III | Part IV | Part V | Part VI | Part VII | Part VIII | Part IX | Part X | Part XI | Part XII | Part XIII | Part XIV | Part XV | Part XVI | Part XVII | Part XVIII | Part XIX | Part XXThe $41,000-a-Month DELETE That Deleted NothingThe page came at 2:58 AM on a Tuesday, and it wasn’t from a pipeline. It was from FinOps, in Slack, with a screenshot: our S3 spend had crossed $41,000 for the month, up from $9,400 five months earlier, and the line was still climbing. The accused was bronze.clickstream — 412 terabytes, fourteen months of raw click events, roughly 2.1 billion rows a day landing through a Structured Streaming MERGE.Six months before that night, we had deleted 238 terabytes from that table. A GDPR erasure request had forced us to purge nine months of history containing raw PII. The DELETE ran for eleven hours, the row counts confirmed it, the auditors signed off. And the storage bill did not move. Not by a gigabyte.We did what every team does: we blamed VACUUM. Then we checked, and VACUUM had been running green every Sunday for a year. VACUUM bronze.clickstream RETAIN 168 HOURS, dry-run clean, a few hundred gigabytes reclaimed each time, job healthy. The 238 terabytes were simply still there, on S3, billing us $0.023 per GB-month, while the table insisted they were gone.At 3:40 AM, running on caffeine and indignation, the on-call engineer did the obvious thing. He disabled the retention safety check and ran the nuclear option:-- the 3:40 AM version of "have you tried turning it off and on again"VACUUM bronze.clickstream RETAIN 0 HOURSIt worked. Forty-one thousand dollars a month of dead files evaporated in ninety minutes. We went back to sleep feeling like heroes.At 9:04 AM, finance ran the month-end close. Their reconciliation query reads the table TIMESTAMP AS OF the last day of the month — a time-travel read, thirty-one days back. It failed instantly with FileNotFoundException: a file referenced in the transaction log could not be found. The version they needed had been vacuumed out from under them at 4 AM. So had the training snapshot the ML team had pinned for a model refresh. Two teams, two broken reads, one very long incident review.So: what does DELETE actually delete in Delta Lake, what is VACUUM legally allowed to remove, and why did 238 terabytes of "deleted" data survive six months of weekly vacuums — while thirty-one-day-old files died the moment we got impatient?The Mechanic Underneath: The Table Is a Ledger, Not a DirectoryForget the parquet files for a minute. A Delta table is not a directory of data files. A Delta table is _delta_log/ — a directory of JSON files, each one a commit, each commit a list of actions. The data files are just the payload the ledger points at.Every commit appends one file: 00000000000000000000.json, 00000000000000000001.json, and so on. Inside, the actions that matter:add: this parquet file is now part of the table (path, size, partition values, file statistics).remove: this parquet file is no longer part of the table — with a deletionTimestamp and a dataChange flag. The file itself is untouched. It becomes a tombstone.protocol: the minimum reader/writer versions this table requires.metaData: schema, partition columns, table properties.txn: the streaming application ID and version, for idempotent micro-batch commits.commitInfo: who committed, when, with what operation.The state of the table at version N is the replay of every action from 0 to N. Nothing is ever mutated in place. A DELETE doesn't delete rows — it writes new parquet files without those rows and logs remove actions against the old ones. An UPDATE, a MERGE, an OPTIMIZE: all rewrites, all tombstones. The old files sit on S3, fully intact, until something with the authority to forget them comes along.Because replaying millions of JSON files on every read would be absurd, Delta writes a checkpoint every 10 commits (controlled by delta.checkpointInterval): a parquet file summarizing the complete table state at that version, with _last_checkpoint pointing at the newest one. Reading version N means loading the nearest checkpoint at or below N and replaying only the JSON tail after it. That tail — the checkpoint cadence, the JSON retention, the replay cost — is where our second bill was hiding, as we'll see.This is the whole mental model: the log is the table, the files are just evidence, and forgetting is a scheduled, retention-gated operation — never an immediate one.Optimistic Concurrency: Every Commit Is a Conditional Write on a Version NumberWriters don’t take locks. A writer reads the current version V, does its (possibly enormous) work against that snapshot, then attempts to write V+1.json as an atomic conditional put — it succeeds only if V is still the latest version. If another writer got there first, Delta runs conflict detection: two blind appends to different partitions can both commit (the loser retries against V+1); two MERGEs touching overlapping files cannot, and the loser gets a ConcurrentAppendException.This is why the streaming MERGE into bronze.clickstream and the Sunday OPTIMIZE could coexist without corrupting anything — and also why our incident had a blast radius instead of a corruption. The 4 AM vacuum didn't corrupt the log; it deleted evidence the log still referenced. The ledger was perfect. The files were gone. Optimistic concurrency protects the log's integrity, not the physical files' existence. Those are two different durability promises, and we had confused them.The protocol action deserves a paranoid glance too. minReaderVersion and minWriterVersion gate which engine versions may touch the table, and modern Delta adds named table features — deletion vectors, column mapping, liquid clustering, v2 checkpoints. Bumping the protocol is a one-way door: old readers are locked out permanently. It has nothing to do with our incident, but it's the same class of mistake — a metadata decision with physical consequences that you only discover at 9:04 AM.Time Travel Is Log Replay, Not a BackupTIMESTAMP AS OF and VERSION AS OF feel like backups. They are not. There is no snapshot stored anywhere. A time-travel read resolves your timestamp to a version number, loads the nearest checkpoint at or below it, and replays the JSON tail — the exact same machinery as a current read, just stopping earlier.The consequence is absolute: a time-travel read is only as durable as the log entries and the data files they reference. Keep the log for 30 days and you can time-travel 30 days — provided nobody vacuumed the files those old versions point at. Our finance query needed version history 31 days deep. Our vacuum at RETAIN 0 HOURS had deleted every file unreferenced by the current version, including every file the 31-day-old version needed. The ledger still described a table that could be reconstructed; the reconstruction was impossible. FileNotFoundException is the log telling the truth about files that no longer exist.VACUUM Can Only Delete What the Log Has Already ForgottenHere is the actual deletion pipeline, in order:A DELETE/MERGE/UPDATE logs remove actions with a deletionTimestamp. The files are now tombstones — logically dead, physically alive.Tombstones are protected for delta.deletedFileRetentionDuration (default: 7 days). This is not a suggestion; it's the table property VACUUM consults.VACUUM ... RETAIN N HOURS deletes data files that are referenced by no table version within the retention window — and only if they're older than the threshold. It also refuses RETAIN under 168 hours unless you explicitly disable spark.databricks.delta.retentionDurationCheck.enabled, because a query or a streaming micro-batch can legitimately take longer than you think.Now the root cause of the $41,000 bill: eighteen months earlier, a well-meaning predecessor had set two table properties “for audit safety”:'delta.deletedFileRetentionDuration' = 'interval 365 days','delta.logRetentionDuration' = 'interval 365 days'Every tombstone the GDPR delete created was legally protected for a year. Our weekly VACUUM RETAIN 168 HOURS would list the 238 terabytes of dead files, check each one's deletionTimestamp against the one-year tombstone retention, and walk away. It ran green because it was doing exactly what the table told it to do: nothing. The retention property outranks your urgency. VACUUM obeys the log, not your FinOps dashboard.And the 3:40 AM RETAIN 0 HOURS? It bypassed the only guardrail standing between "delete unreferenced files" and "delete files that old-but-legitimate versions still reference." The default 168-hour floor exists precisely because time-travel readers, long-running queries, and concurrent writers can hold a logical reference to a version for days. Zero hours means zero patience for anyone reading the past.The Log Files Themselves Are the Second BillWhile we were staring at the 238 terabytes, the _delta_log directory was running its own scam. bronze.clickstream commits roughly 3,400 times a day — streaming micro-batches, hourly OPTIMIZE runs, the occasional MERGE. With delta.logRetentionDuration set to 365 days, that is:3,400 commits/day × 365 days ≈ 1.24 million JSON files sitting in _delta_log/.Every single read of that table — every dashboard refresh, every ad-hoc query — starts by listing _delta_log, reading _last_checkpoint, loading the checkpoint parquet, and replaying the JSON tail since the last checkpoint. Our tail was thousands of files long on a bad day. Query planning alone took 47 seconds before a single byte of data was touched, and S3 LIST requests — $0.005 per thousand — were a line item of their own. The ledger had become heavier than some of the tables it described.Checkpoints cap the replay, but they don’t cap the listing or the retention. The checkpoint interval (10) was fine; the 365-day log retention was the disease. A ledger you’re legally required to keep for a year is an archive, not a live table — and we were paying live-table prices to replay it on every query.The Fix, and What It CostThe naive fix is what we did at 3:40 AM. The engine-aware fix starts from the actual SLAs — how far back anyone is contractually allowed to read — and tiers every retention knob to match:# Naive: nuke everything unreferenced RIGHT NOW.# spark.conf.set(# "spark.databricks.delta.retentionDurationCheck.enabled", "false"# ) # disables the 7-day guardrail — the guardrail exists for time-travel readers# spark.sql("VACUUM bronze.clickstream RETAIN 0 HOURS")# Result: 238TB freed, then FileNotFoundException on every read older than "now".# Optimized: tier retention to the real SLAs, then vacuum honestly.spark.sql(""" ALTER TABLE bronze.clickstream SET TBLPROPERTIES ( 'delta.deletedFileRetentionDuration' = 'interval 7 days', 'delta.logRetentionDuration' = 'interval 30 days' )""") # finance needs 30-day time travel; GDPR needs 7-day tombstone expiry, not 365# Always DRY RUN first, and read what it plans to delete:# spark.sql("VACUUM bronze.clickstream RETAIN 168 HOURS DRY RUN")spark.sql("VACUUM bronze.clickstream RETAIN 168 HOURS")Two companion decisions, both non-optional:Audit history moved out of the live table. The “audit safety” requirement was real, so we gave it a real answer: a monthly archived copy of the table in cheap storage, instead of a 365-day retention property strangling the production table.RESTORE discipline. RESTORE TABLE ... TO VERSION AS OF is metadata-only — it appends a new version re-adding old removed files. It can only resurrect files that still exist. Our runbook now states the restore horizon explicitly: 30 days, matching logRetentionDuration, verified by a monthly restore drill against a clone.The quantified results, thirty days later:S3 spend: $41,000/month → $12,400/month. The 238TB of GDPR tombstones plus ~40TB of orphaned log and compaction debris, gone — legally this time._delta_log file count: 1.24M JSON files → ~102k. Thirty days of history at 3,400 commits/day.Query planning time: 47s → 3s on the standard dashboard queries. Same data, same cluster.Month-end close time-travel query: green, and covered by the monthly restore drill.The Catch: Retention Is a One-Way Door, and the Vacuum Doesn’t Know Your SLAsThe honest counterweight, because the fix has sharp edges:Lowering retention is irreversible for old versions. The moment tombstones age past the new threshold and VACUUM runs, those versions are unrecoverable — RESTORE becomes a FileNotFoundException factory. We lowered 365 days to 30 only after the archive copy existed and the stakeholders signed the horizon in writing.VACUUM cannot delete files referenced within retention, full stop. A 30-day time-travel SLA means a minimum of 30 days of dead files sitting on S3. That is the price of the feature, not a bug in the tool. Budget for it.Never point S3 lifecycle rules at Delta data directories. Lifecycle policies delete by object age with no knowledge of the log. A lifecycle rule expiring “old” parquet files will happily delete files the current version references, and the table will corrupt silently until the next read. Retention belongs in Delta properties, not in bucket policies.The 168-hour floor is load-bearing. We now treat any request to vacuum below 7 days the way we’d treat a request to delete the backups: possible, documented, and requiring two sign-offs. A streaming MERGE micro-batch retrying against a transient failure can legitimately need files older than your impatience.TakeawaysThe log is the table: _delta_log/ defines every version; the parquet files are just evidence the ledger points at. Protect the ledger's integrity and the files' existence as two separate promises.DELETE is a rewrite, not an erasure: every DELETE, UPDATE, and MERGE writes new files and tombstones the old ones. Storage is freed only when retention expires and VACUUM runs.VACUUM obeys the log, not your urgency: deletedFileRetentionDuration outranks your RETAIN clause. A 365-day tombstone retention makes weekly vacuums a ceremonial no-op.RETAIN 0 HOURS is a loaded gun: it deletes files that old-but-legitimate versions still reference. The 7-day guardrail exists because time-travel readers and long-running queries hold logical references for days.Time travel is only as durable as your retention: a 31-day-old read needs 31 days of log and 31 days of un-vacuumed files. Set logRetentionDuration from the restore SLA, not from vibes.The _delta_log is a cost center too: commit-heavy tables with long log retention accumulate millions of JSON files, and every reader pays the LIST-and-replay tax. Size logRetentionDuration to the readership, not the auditors — archive separately.In Delta Lake, nothing is ever deleted — it is only forgotten on a schedule. Make sure you’re the one writing the schedule.If this saved you a 3 AM pager incident, follow me on Medium for Twice a week for the next 3 Months of Advanced Data Engineering & AI. Let’s connect on LinkedIn and X.Part XX — Delta Lake’s Transaction Log: Time Travel, VACUUM, and the Files That Never Die was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.