Time travel and RESTORE
Table formats keep old versions of a table around for a while. That lets you query yesterday's data, compare two versions, or undo a bad write in one command. This lesson shows time travel and RESTORE, and how retention limits how far back you can go.
Step 3 · Data lake & lakehouse · Silver · Delta day to day, lesson 2 of 4
On this page
Show code in
Every code block on the page follows this.
Read first: The Delta transaction log (skip if you know it)
In plain words first
A shared document with version history lets you see what it looked like last Tuesday, or restore that version if someone broke it. Old versions are kept only for a while, then cleaned up to save space.
Delta and Iceberg tables have the same history: every commitcommit: One atomic change to a table: a new version that lists which files were added and removed. Learn more → is a version you can read, compare or restore.
Reading the past
spark.read.option("versionAsOf", 12).table("sales") spark.read.option("timestampAsOf", "2025-03-01 00:00:00").table("sales")
SELECT * FROM sales VERSION AS OF 12; SELECT * FROM sales TIMESTAMP AS OF '2025-03-01 00:00:00';
spark.read.option("snapshot-id", 10963874102873).table("db.sales") spark.read.option("as-of-timestamp", 1740787200000).table("db.sales") # epoch millis
SELECT * FROM db.sales VERSION AS OF 10963874102873; SELECT * FROM db.sales TIMESTAMP AS OF '2025-03-01 00:00:00';
A timestamp query resolves to the latest version committed at or before that time. To find versions, use Delta's DESCRIBE HISTORY sales or Iceberg's metadata table SELECT * FROM db.sales.snapshots.
Rolling back
# Delta DeltaTable.forName(spark, "sales").restoreToVersion(12)
-- Delta RESTORE TABLE sales TO VERSION AS OF 12; -- Iceberg CALL catalog.system.rollback_to_snapshot('db.sales', 10963874102873);
A Delta RESTORE does not delete newer history. It writes a new commit whose actions bring back the old file list, so the bad versions are still visible in history and the restore itself can be undone. An Iceberg rollback moves the table's current snapshotsnapshot: A complete, consistent version of a table at one moment. Readers always see one snapshot, never a half-finished write. Learn more → pointer back; later snapshots remain until expired.
How far back you can go
| Format | Limit | Defaults |
|---|---|---|
| Delta | Log entries must exist (delta.logRetentionDuration) and data files must not be vacuumed (delta.deletedFileRetentionDuration) | 30 days of log; files removed more than 7 days ago may be vacuumed |
| Iceberg | The snapshot must not be expired (expire_snapshots, history.expire.max-snapshot-age-ms) | Snapshots older than 5 days are eligible when you run expiration |
What it is good for
- Undoing a bad write: a job loaded duplicates; restore to the version before it.
- Debugging: compare today's table with yesterday's:
EXCEPTbetween two versions shows exactly which rows changed. - Reproducible ML: record the table version used for training so the dataset can be rebuilt exactly.
- Audit: history shows who changed what and when.
- Consistent multi-step reads: pin all reads of a job to one version so concurrent writes do not change results mid-job.
spark.sql(""" SELECT * FROM sales EXCEPT SELECT * FROM sales TIMESTAMP AS OF date_sub(current_date(), 1) """)
SELECT * FROM sales EXCEPT SELECT * FROM sales TIMESTAMP AS OF date_sub(current_date(), 1);
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: Recover from a bad write: find the last good version in history, check it, and restore it.
import os from delta.tables import DeltaTable path = os.path.abspath("lab/time_travel/accounts") (spark.createDataFrame([(1, 100.0), (2, 250.0)], ["id", "balance"]) .write.format("delta").mode("overwrite").save(path)) # version 1 spark.sql(f"UPDATE delta.`{path}` SET balance = balance + 50 WHERE id = 1") # 2: the bad job spark.sql(f"DELETE FROM delta.`{path}`") table = DeltaTable.forPath(spark, path) table.history().select("version", "operation").orderBy("version").show() good = spark.read.format("delta").option("versionAsOf", 1).load(path) # check it first print("version 1 has", good.count(), "rows") # writes version 3 table.restoreToVersion(1) spark.read.format("delta").load(path).orderBy("id").show() latest = table.history(1).first() print("latest version:", latest["version"], latest["operation"])
Output from a real run
+-------+---------+ |version|operation| +-------+---------+ | 0| WRITE| | 1| UPDATE| | 2| DELETE| +-------+---------+ version 1 has 2 rows +---+-------+ | id|balance| +---+-------+ | 1| 150.0| | 2| 250.0| +---+-------+ latest version: 3 RESTORE
What to notice:
- History shows the bad job as version 2, a
DELETEof everything. - Version 1 still has both rows, so it is safe to restore.
- After the restore, both accounts are back (account 1 with its update, 150.0), and the restore itself is a new version:
3 RESTORE. Nothing was erased.
Common mistakes
- Treating time travel as backup — Retention is short and cleanup is permanent.
- Setting a short deletedFileRetentionDuration — Shortens readable history and can break long-running readers.
- Expecting RESTORE to remove history — It adds a commit; history stays.
Key takeaways
- Query old data with VERSION AS OF or TIMESTAMP AS OF.
- Delta RESTORE adds a commit; Iceberg rollback moves the current snapshot pointer.
- Retention settings and cleanup jobs limit how far back you can go.
- Time travel is great for recovery and debugging, but it is not a backup.
Interview prep
THE QUESTION
"A bad job overwrote yesterday's data in a Delta table. How do you recover?"
Avoid: "Delta keeps everything forever". Time travel only reaches versions whose files have not been VACUUMed and whose log entries are retained.
Follow-ups · answer out loud, then open
Follow-up"Does RESTORE delete the bad versions?"
Scenario"Auditors want to reproduce a report exactly as of the end of each quarter, for seven years. Is time travel enough?"
Trap"VERSION AS OF and TIMESTAMP AS OF are interchangeable."
Check yourself
3 questionsWhat does Delta RESTORE do to newer versions in history?
Show the answer
Keeps them and adds a new commit that restores the old file list. RESTORE is itself a commit, so history is preserved.
How do you find Iceberg snapshot ids?
Show the answer
Query the db.table.snapshots metadata table. Iceberg exposes snapshots through metadata tables.
Why is time travel not a backup?
Show the answer
Retention is limited and cleanup permanently deletes old files. Old versions disappear after vacuum or snapshot expiration.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · Delta day to day · lesson 3 of 4 · 6 min readSchema enforcement and evolution
What a table rejects on write, how mergeSchema adds columns, and which changes are safe.
Related lessons
The Delta transaction logData lake & lakehouse · 6 min read
VACUUM and retentionData lake & lakehouse · 6 min read
Iceberg metadata tree
Previous: The Delta transaction log
Primary sources: Delta: table utility commands · Iceberg: Spark queries