Delta Lake: the log and time travel
Part of the free LogicWiz Data Engineering course, Module 13: The lakehouse on Databricks. The SQL and Python run in the app, on real Postgres and real Python in the browser.
Tuesday, 9:10. A teammate meant to delete the cancelled orders from silver.orders, and typed DELETE ... WHERE status <> 'delivered'. 51 of the 80 orders are gone. Tess's finance report reads that table at 10:00. You open a terminal to reload everything, and Nora stops you: "Don't reload. Look in the table's folder first."
You'll learn to
- Read a Delta commit and say what each action does
- Explain how a reader rebuilds any version from the log
- Undo a mistake with time travel and RESTORE, and know the limits
- Explain how the protocol keeps old clients from misreading a table
Learn
The rows are gone. The files are not.
You list the folder and find two Parquet files. The newer one holds 29 orders. The older one still holds all 80.
That is the whole trick of Delta Lake, the table format every Databricks table uses. A Delta table never changes a data file. A delete writes a new file with the rows that survive. Then it writes a short note that says: from now on, read the new file, not the old one.
The old file stays where it was. So the 51 orders are not lost. You only need to change which note the readers follow.
Write twice, then look in the folder
import minidelta
t = minidelta.DeltaTable('lake/orders')
t.write("SELECT * FROM 'data/orders.csv' WHERE order_ts < '2025-06-08'")
t.write("SELECT * FROM 'data/orders.csv' WHERE order_ts >= '2025-06-08'")
for name in t.ls():
print(name)
print('version', t.version(), 'has', t.count(), 'rows')
Do what Nora said, on a small table of your own. Two writes left two Parquet files and a folder called _delta_log with two numbered files in it. (minidelta is a small Delta-like table written in plain Python with DuckDB. It is in your run folder as minidelta.py: open it and read how the log works.)
A logbook next to the files
The short notes live in that _delta_log/ folder. Together they are the transaction log.
Think of a bank statement. Nobody rubs out a line. Every deposit and withdrawal is a new line, and your balance is what you get by reading from the top.
A Delta table works the same way. Every change writes one new numbered JSON file to the log. The first is 00000000000000000000.json: that is version 0. The next change makes version 1. One such file is called a commit.
The log is the only truth about which files make up the table.
Open one commit
Open a commit and you find one small JSON object per line. Each line is called an action. Two of them do most of the work:
add: this data file now counts.remove: this data file no longer counts.
Run the next card. It writes 80 orders, deletes the cancelled ones, and prints every action of both commits.
Read every action of the first two commits
import minidelta
t = minidelta.DeltaTable('lake/orders')
t.write("SELECT * FROM 'data/orders.csv'") # version 0 creates the table
t.delete("status = 'cancelled'") # version 1
for v in [0, 1]:
for action in t.log(v):
kind = next(iter(action))
a = action[kind]
if kind == 'add':
detail = f"{a['path']} rows={a['stats']['numRecords']}"
elif kind == 'remove':
detail = a['path']
elif kind == 'metaData':
detail = f"{len(a['schema'])} columns"
elif kind == 'protocol':
detail = f"reader {a['minReaderVersion']}, writer {a['minWriterVersion']}"
else:
detail = f"{a['operation']}, readVersion {a['readVersion']}"
print(v, kind, detail)
Look at version 1. The delete did not edit part-00000.parquet: it wrote the 71 surviving rows to a new file and logged two facts, one remove and one add. The other kinds of line are explained in the table below. (minidelta stores the schema as a list; real Delta writes a schemaString of JSON.)
The six actions, in plain words
| Action | In plain words | Key fields |
|---|---|---|
| add | This data file now counts. Its stats let a reader skip it | path, size, partitionValues, dataChange, stats (numRecords, minValues, maxValues, nullCount), deletionVector |
| remove | This data file no longer counts. VACUUM uses this marker later | path, deletionTimestamp, dataChange |
| metaData | The columns (the schema) and the table properties | schemaString, partitionColumns, configuration |
| protocol | What a program must understand to read or write the table, so a client that cannot handle it is refused | minReaderVersion, minWriterVersion, readerFeatures, writerFeatures |
| commitInfo | What the operation was: the history DESCRIBE HISTORY shows, and what conflict checks use | operation, operationParameters, readVersion, isolationLevel, isBlindAppend |
| txn | How far an application, such as a stream, has written: exactly-once writes from streams and retried batches | appId, version, lastUpdated |
You printed five of the six just now. Version 0 carries protocol and metaData; later commits repeat them only when they change. Read the middle column; the field names on the right are from the Delta protocol specification, for when you open a real commit.
What a plain folder gets wrong
In Module 4 you wrote orders as Parquet files in a plain folder. A folder has no rules. The log adds four, known together as ACID:
- Atomic. A commit is one file: it appears whole or not at all. A job that dies half-way leaves Parquet files nobody reads, because its commit never appeared.
- Consistent. Every write is checked against the schema and protocol in the log.
- Isolated. A reader pins one version and reads only its files while writers prepare the next.
- Durable. Once the commit file exists, the change is saved.
And two writers at once? Both try to create the same numbered file, and a writer must never overwrite a log file. One wins. The other checks the winner's commit and retries with the next number (Lesson 13.8).
The 9:10 delete, as the folder saw it
A Delta table folder in three moments: after the first write of 80 orders, after the bad delete that leaves 29, and when a reader replays only the first commit and gets all 80 back.
Version 0: the first write. One Parquet file holds all 80 orders. One commit says: add
part-00000. A reader replays the log, reads that file and gets 80 rows.Version 1: the bad delete. Delta leaves
part-00000alone. It writes the 29 surviving orders to a new file, and a second commit that says: removepart-00000, addpart-00001. A reader now gets 29 rows.Ask for version 0. This reader stops after the first commit, so it never meets the
remove. It readspart-00000, which is still in the folder: 80 rows. That is time travel.
Watch the Parquet files box. No file ever changes or disappears: only its colour does, because the log decides which files count.
Remember: a change adds new files and one new log file. It never edits a data file. Even a delete adds a file.
How a reader rebuilds a version
You have seen the rule at work. Here it is in full.
To read version n, a reader replays the commits from 0 to n, in order. For each data file, its latest action wins: if that is an add, the file is read. The latest protocol and metaData win too.
A data file the log never mentions is invisible, even though it sits in the folder.
Replaying from zero gets slow after thousands of commits. So now and then Delta saves a checkpoint: the whole state of the table at one version, in one Parquet file. A reader starts from the newest checkpoint and replays only the commits after it.
Opening a table, step by step
Six steps from top to bottom: read the _last_checkpoint pointer, read that checkpoint, list and read the JSON commits after it, reconcile the actions, check the protocol, then plan the scan using file statistics.
Read it top to bottom. Without a checkpoint, the amber step starts at version 0, which is why a table with thousands of commits and no checkpoint is slow to open. Lesson 13.8 opens checkpoints.
Undo it: time travel and RESTORE
Because no data file is ever edited, every old version is still sitting in the folder. Reading one is called time travel: the reader replays the log only as far as the version you ask for.
RESTORE goes one step further and makes an old version the current one again. It copies nothing back. It writes a new commit that adds the old version's files and removes the newer ones. The bad version stays in the history.
Run the next card. It makes the 9:10 mistake, then undoes it.
Undo the bad delete
import minidelta
t = minidelta.DeltaTable('lake/orders')
t.write("SELECT * FROM 'data/orders.csv'") # version 0
t.delete("status <> 'delivered'") # version 1: the mistake
print('now:', t.count(), ' version 0:', t.count(version_as_of=0))
t.restore(0) # version 2
print('after restore:', t.count())
for h in t.history():
print(h['version'], h['operation'], h['operationMetrics'])
Three versions in the history, and the mistake is still one of them. The restore did not go back to version 0: it made version 2, which reads the same file as version 0.
Which files each version reads
| Version | Operation | Files it reads | Parquet files in the folder |
|---|---|---|---|
| 0 | WRITE, 80 rows | part-00000 | part-00000 |
| 1 | DELETE, 51 rows gone | part-00001 (the 29 delivered orders) | part-00000, part-00001 |
| 2 | RESTORE to version 0 | part-00000 again | part-00000, part-00001 |
Nothing was copied back: version 2's commit adds part-00000 again and removes part-00001. That is why RESTORE takes seconds even on a huge table, and why it fails if VACUUM has already deleted the old files.
The same three commands on Databricks
Runs on Databricks:
DESCRIBE HISTORY workspace.silver.orders;
SELECT COUNT(*) FROM workspace.silver.orders VERSION AS OF 0;
RESTORE TABLE workspace.silver.orders TO VERSION AS OF 0;
-- DESCRIBE HISTORY (3 of its columns)
version operation operationMetrics
1 DELETE {"numDeletedRows": "51", ...}
0 CREATE TABLE AS SELECT {"numOutputRows": "80", ...}
-- VERSION AS OF 0
80
-- RESTORE (2 of its columns)
num_removed_files num_restored_files
1 1
Look at the history first, check the old version second, restore last. You can also travel by time, TIMESTAMP AS OF '2025-06-10 09:00:00', or with the short form orders@v0. In Python: spark.read.option("versionAsOf", 0).table("workspace.silver.orders").
Play with the folder
A Delta table folder: numbered JSON commits in _delta_log, the Parquet files each version reads, with buttons to time travel to an old version, run OPTIMIZE and run VACUUM.
Click a version to see which files it reads. Files that a later commit removed stay in the folder until VACUUM deletes them.
How far back can you go?
Time travel needs two things for the version you want: its log files and its data files. Each has its own clock.
- Log files are kept for 30 days by default (
delta.logRetentionDuration). - Data files that a commit removed stay until VACUUM, a clean-up command you meet in Lesson 13.4, deletes those older than 7 days (
delta.deletedFileRetentionDuration).
The shorter clock wins. So by default you can rely on 7 days, not 30.
This morning's mistake was a few minutes old when you found it. A mistake found three weeks late would be a different story.
Two clocks, and the shorter one wins
Three bars in days: log entries are kept 30 days, removed data files 7 days, so the time travel you can rely on is 7 days.
Read the green bar: it is as long as the shorter blue one. Both numbers are the defaults.
The trap: treating time travel as a backup. It reaches back only as far as both clocks allow, and a dropped table or a lost storage account takes its history with it. Keep real backups, or a bronze layer you can replay, and use time travel as an undo button for recent mistakes. Raising delta.deletedFileRetentionDuration to 30 days buys a longer window, and you pay to store every rewritten file for 30 days.
The table decides who may read it
One more thing lives in the log: a guard. The protocol action lists what a program must understand before it touches the table.
Newer tables list table features by name, and they come in two kinds:
- A reader-writer feature changes how files are read, so every reader must know it:
deletionVectors,columnMapping,timestampNtz,v2Checkpoint. - A writer-only feature binds only writers:
changeDataFeed,checkConstraints,rowTracking,clustering,domainMetadata.
Switching a feature on upgrades the protocol for every client at once. An engine that does not know a listed reader feature refuses the table with Unsupported Delta read feature: table ... requires reader table feature(s) that are unsupported.
Switch on two features, watch the protocol
import minidelta
t = minidelta.DeltaTable('lake/orders')
t.write("SELECT * FROM 'data/orders.csv'")
print(t.protocol())
t.enable_feature('changeDataFeed') # writer-only
print(t.protocol())
t.enable_feature('deletionVectors') # reader-writer
print(t.protocol())
print([h['operation'] for h in t.history()])
Read the three printed lines in order. The writer-only feature moved only the writer version, to 7, and named the features writer version 2 implied (appendOnly, invariants). Only the reader-writer feature raised the reader version, to 3. On Databricks you rarely do this by hand: setting a property such as delta.enableDeletionVectors upgrades the protocol for you.
Numbers to remember
| Name | Value | What it means |
|---|---|---|
| delta.logRetentionDuration | 30 days | How long log entries are kept. They are cleaned up after checkpoints |
| delta.deletedFileRetentionDuration | 7 days | How long VACUUM leaves a removed data file alone |
| Databricks Runtime 18.0 and above | Time travel to a version older than the file retention is blocked even before VACUUM runs | |
| Log file name | 20 digits | The version, padded with zeros: 00000000000000000002.json is version 2 |
| Reader version 3, writer version 7 | From here on the protocol lists table features by name | |
| Writer version 2 | Append-only tables and invariants | |
| Writer version 3 | CHECK constraints | |
| Writer version 4 | Change data feed and generated columns | |
| Writer version 5 | Column mapping (with reader version 2) | |
| Writer version 6 | Identity columns | |
| dataChange: false | Marks an action that only rearranges data, as OPTIMIZE does, so a stream reading the table skips that commit | |
| Create-if-absent on S3 | S3 long lacked that guarantee, so open-source Delta allowed S3 writes from one Spark driver only, unless every writer used the DynamoDB-backed log store |
Delta Lake is open source and the default table format on Databricks: every saveAsTable in the last lesson made a Delta table. Apache Iceberg and Apache Hudi solve the same problem with their own metadata, and Lesson 13.7 compares Delta with Iceberg. Teams that share tables across engines check the protocol before switching on a feature: one ALTER TABLE can lock out every reader that does not support it.
What changed at SwiftKart
At 9:25 you run RESTORE on silver.orders. It takes seconds, because nothing is copied. The table is at version 2 and has 80 orders again. Tess's 10:00 report reads the right numbers and she never hears about it.
The bad delete is still in the history as version 1, with the time and the command. Nora adds one line to the team notes: check DESCRIBE HISTORY before you reload anything.
The delete rewrote a whole file to remove some rows. The nightly change file does the same thing every night, with a command called MERGE. Lesson 13.3 picks that up.
In one line
A Delta table is Parquet files plus a log that only grows; replaying the log gives any version whose log and data files are still kept, which is how you undo a bad delete, and the protocol stops old clients misreading it.
Interview corner
How does Delta Lake give ACID transactions on object storage?
Every change is one commit: a new numbered JSON file in _delta_log listing actions, mainly the data files added and removed. The file is created only if that version does not exist yet, so a crashed job changes nothing and two writers cannot both win a version; the loser checks the winner for conflicts and retries at the next number. Readers start from the latest checkpoint, replay the later commits and read only the files of their snapshot, so they never see a half-written change.
What is time travel, and what limits it?
Because a change never edits or deletes data files in place, any earlier version can be read by replaying the log to it: VERSION AS OF 3, TIMESTAMP AS OF, or table@v3. It needs both the log entries (delta.logRetentionDuration, 30 days by default) and the data files (delta.deletedFileRetentionDuration, 7 days, enforced by VACUUM), so the practical window is 7 days unless you raise the file retention and pay for the storage. RESTORE uses it to undo a mistake with a new commit.
What are reader and writer protocol versions, and what happens when you enable a table feature?
The protocol action holds the minimum reader and writer versions, and since reader 3 and writer 7 explicit lists of table features. A reader-writer feature such as deletion vectors or column mapping goes in both lists, so every reader must support it; a writer-only feature such as change data feed or CHECK constraints only binds writers. Enabling one upgrades the protocol for all clients at once, so an older engine fails with an unsupported feature error. On shared tables I check which engines read them before enabling anything.
What happens to the files when you DELETE rows from a Delta table?
Files with no matching rows are untouched. Without deletion vectors, each file with matching rows is rewritten without them (copy-on-write), and the commit logs remove for the old file and add for the new one; the old file stays for time travel until VACUUM. With deletion vectors, Delta instead writes a small bitmap of deleted row positions and re-adds the same file with it, and the rewrite is deferred to OPTIMIZE or REORG.