Skip to content
Silver 8 min read · Delta 2 practice problems ↓

The Delta transaction log

A Delta table is a folder of Parquet files plus an ordered log that says which of those files make up the table right now. Everything Delta can do, from ACID writes to time travel, comes from that log.

Step 3 · Data lake & lakehouse · Silver · Delta day to day, lesson 1 of 4

Read first: Parquet and columnar storage · ACID on object storage (skip if you know them)

In plain words first

A bank ledger stores every deposit and withdrawal, not the balance: add them up in order and you get the balance, stop early and you get an old one. A Delta table works the same way:

Bank ledger

Entries: deposit, withdrawal. Balance = sum of entries. Past balance = stop at a date.

Delta log

Entries: add file, remove file. Table = replay of commits. Time traveltime travel: Reading a table as it was at an earlier version or time. Learn more → = stop at a version.

Why it exists

Picture a plain ParquetParquet: A columnar file format: values of each column are stored together, so queries read only the columns they need. Learn more → table: a folder, and "the table" is every file in it. That definition breaks in three ways.

  1. Half-finished writes are visible. A job that dies after 60 of 100 files leaves 60 behind, and readers see them.
  2. Updates are not atomic. A reader between deleting the old file and writing the new one sees missing or duplicate rows.
  3. Listing is slow. Listing millions of objects in S3 or ADLS takes minutes.

Delta changes the definition: the table is the set of files the log says are live, not whatever happens to be in the folder.

Inside _delta_log

Each commit is a JSON file named by its version, padded to 20 digits; every few commits Delta also writes a Parquet checkpointcheckpoint: 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..

events/
├── part-00000-….snappy.parquet
├── part-00001-….snappy.parquet
└── _delta_log/
    ├── 00000000000000000000.json      # version 0
    ├── 00000000000000000001.json      # version 1
    ├── …
    ├── 00000000000000000010.checkpoint.parquet  # full state at v10
    └── _last_checkpoint               # points to newest checkpoint

Each line of a commit file is one action:

ActionWhat it records
addA file joins the table, with its size, partition values and column statistics.
removeA file leaves the table but stays on storage until VACUUMVACUUM: The command that deletes data files no longer in the table, once they are older than the retention period. Learn more → (a tombstonetombstone: A record that a file was removed from the table. The file itself stays on storage until VACUUM deletes it. Learn more →).
metaDataSchema, partition columnspartition column: The column a table is split into folders by, such as one folder per date. Learn more → and table properties.
protocolReader and writer versions, and table features in use.
commitInfoWho ran what, when: what DESCRIBE HISTORY shows.
txnAn app id and version, so streaming writes apply exactly once.

Walk through four commits

Watch the files in the table and the files on storage as an events table changes:

v0 · Create

Creating the table writes two Parquet files and the first commit, which also records the protocol and the schema.

The command

df.write.format("delta").saveAsTable("events")
CREATE TABLE events USING delta
AS SELECT * FROM staging;

What it writes · 00000000000000000000.json

{"protocol":{"minReaderVersion":1,"minWriterVersion":2}}
{"metaData":{"schemaString":"…","partitionColumns":[]}}
{"add":{"path":"part-000.parquet","dataChange":true,"stats":"{\"numRecords\":5000,…}"}}
{"add":{"path":"part-001.parquet","dataChange":true,…}}
{"commitInfo":{"operation":"CREATE TABLE AS SELECT",…}}

In the table

part-000.parquetpart-001.parquet

On storage only (tombstoned)

None.

v1 · Append

An append only adds: one new file, one new commit, nothing removed. Readers on version 0 are unaffected.

The command

new_rows.write.format("delta").mode("append").saveAsTable("events")
INSERT INTO events SELECT * FROM staging_day2;

What it writes · 00000000000000000001.json

{"add":{"path":"part-002.parquet","dataChange":true,…}}
{"commitInfo":{"operation":"WRITE","operationParameters":{"mode":"Append"},…}}

In the table

part-000.parquetpart-001.parquetpart-002.parquet

On storage only (tombstoned)

None.

v2 · Delete

Parquet files cannot change, so Delta finds the file with French rows (part-001, from its statistics), writes part-003 with the other rows, and removes part-001 and adds part-003 in one commit. (With deletion vectorsdeletion vector: A small list of the deleted row positions in one data file, so a delete does not rewrite the file. Learn more → on, it marks the rows in a small side file instead.)

The command

DeltaTable.forName(spark, "events").delete("country = 'FR'")
DELETE FROM events WHERE country = 'FR';

What it writes · 00000000000000000002.json

{"remove":{"path":"part-001.parquet","dataChange":true,"deletionTimestamp":…}}
{"add":{"path":"part-003.parquet","dataChange":true,…}}
{"commitInfo":{"operation":"DELETE",…}}

In the table

part-000.parquetpart-002.parquetpart-003.parquet

On storage only (tombstoned)

part-001.parquet

v3 · Optimize

Compactioncompaction: Rewriting many small files into fewer large ones, without changing the rows. Learn more → merges three small files into one. The rows do not change, so the actions say dataChange=false. The old files stay on storage, so version 2 is still readable, until VACUUM.

The command

DeltaTable.forName(spark, "events").optimize().executeCompaction()
OPTIMIZE events;

What it writes · 00000000000000000003.json

{"remove":{"path":"part-000.parquet","dataChange":false,…}}
{"remove":{"path":"part-002.parquet","dataChange":false,…}}
{"remove":{"path":"part-003.parquet","dataChange":false,…}}
{"add":{"path":"part-004.parquet","dataChange":false,…}}
{"commitInfo":{"operation":"OPTIMIZE",…}}

In the table

part-004.parquet

On storage only (tombstoned)

part-000.parquetpart-001.parquetpart-002.parquetpart-003.parquet

How a read works

Replaying every commit since version 0 would get slower forever; checkpoints cap the work. A reader:

  1. 1
    Reads _last_checkpoint to find the newest checkpoint, say version 40.
  2. 2
    Loads that checkpoint: the full list of live files at version 40.
  3. 3
    Applies the JSON commits after 40, in order.
  4. 4
    Uses the min and max statistics on each add to skip files that cannot match the filter.

Step 4 is why Delta often reads far less than a plain Parquet folder: it skips files using statistics already in the log.

Why this matters: statistics cover the first 32 columns by default (delta.dataSkippingNumIndexedCols): filter on column 40 and nothing is skipped. Put filter columns first.

How writers avoid conflicts

Writers do not lock the table (optimistic concurrency). A writer reads version 7, writes its new Parquet files (invisible, since no commit lists them yet), then tries to create …08.json with a "create only if it does not exist" write. If someone else made version 8 first, it checks for a conflict: none, retry as 9; a clash, fail. That create-if-absent step is where atomicity comes from, and why a crash before it is harmless. Concurrency and conflicts goes deeper.

Time travel

Old commits stay in the log and removed files stay on storage, so reading an older version just replays fewer commits (Time travel and RESTORE):

PySparkSpark SQL
# Read version 1
spark.read.option("versionAsOf", 1).table("events")

# See every commit
DeltaTable.forName(spark, "events").history().show()

# Roll the table back (this writes a new commit)
DeltaTable.forName(spark, "events").restoreToVersion(1)
-- Read version 1
SELECT * FROM events VERSION AS OF 1;

-- See every commit
DESCRIBE HISTORY events;

-- Roll the table back (this writes a new commit)
RESTORE TABLE events TO VERSION AS OF 1;

Retention: two clocks

Time travel needs both the commit files and the data files. Commits are kept 30 days (delta.logRetentionDuration), but VACUUM may delete removed data files after 7 (delta.deletedFileRetentionDuration), so after a VACUUM only about a week of versions stays readable. VACUUM and retention covers both.

The same idea in Iceberg and Hudi

Iceberg keeps a tree of metadata files and commits by swapping one pointer in the catalogcatalog: The service that maps table names to their current metadata and controls who can access them. Learn more → (Iceberg metadata tree); Hudi keeps a timeline of instants in .hoodie/ (Apache Hudi). Same idea: the table is what the metadata says, and a commit is one atomic step.

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: Audit a table from its history: what each commit did, and to how many rows.

Production patternPySpark · Audit a table from its history: what changed, and how much
import os

path = os.path.abspath("lab/txlog/orders")
(spark.range(0, 1000).selectExpr("id", "id % 3 AS status")
      .write.format("delta").mode("overwrite").save(path))
spark.sql(f"UPDATE delta.`{path}` SET status = 9 WHERE id < 10")
spark.sql(f"DELETE FROM delta.`{path}` WHERE status = 2")

(spark.sql(f"DESCRIBE HISTORY delta.`{path}`")
    .selectExpr("version", "operation",
                "operationMetrics['numOutputRows'] AS rows_written",
                "operationMetrics['numUpdatedRows'] AS rows_updated",
                "operationMetrics['numDeletedRows'] AS rows_deleted")
    .orderBy("version")
    .show())

Output from a real run

+-------+---------+------------+------------+------------+
|version|operation|rows_written|rows_updated|rows_deleted|
+-------+---------+------------+------------+------------+
|      0|    WRITE|        1000|        NULL|        NULL|
|      1|   UPDATE|        NULL|          10|        NULL|
|      2|   DELETE|        NULL|        NULL|         330|
+-------+---------+------------+------------+------------+

What to notice:

  • Version 0 wrote 1,000 rows, version 1 updated 10, version 2 deleted 330 (the rows with status 2).
  • History also records who ran each commit, from which job and engine (userName, job, engineInfo): what an incident review needs.

Goal: Read Delta's log as a table, and watch a checkpoint file appear.

ExplorePySpark · Read the log as a table, and watch a checkpoint appear
import glob

path = "lab/txlog/events"
spark.range(0, 100).write.format("delta").mode("overwrite").save(path)
for i in range(11):                                   # 12 commits in total
    spark.range(i * 10, i * 10 + 10).write.format("delta").mode("append").save(path)

print(sorted(f.split("/")[-1] for f in glob.glob(f"{path}/_delta_log/*.parquet")))
log = spark.read.json(f"{path}/_delta_log/*.json")
(log.where("commitInfo IS NOT NULL")
    .groupBy("commitInfo.operation").count()
    .show())

Output from a real run

['00000000000000000010.checkpoint.parquet']
+---------+-----+
|operation|count|
+---------+-----+
|    WRITE|   12|
+---------+-----+

What to notice:

  • After 12 commits there is one checkpoint, …010.checkpoint.parquet: Delta writes one every 10 commits.
  • The log itself is JSON you can query: 12 WRITE commits.
  • A reader of version 11 loads the checkpoint at 10 and replays only commit 11, instead of all 12.

Common mistakes

  • Running VACUUM with a retention of 0 hours — It deletes files that running queries and streams may still read, and ends time travel. Delta blocks it unless you turn off a safety check, which exists for a reason.
  • Deleting data files directly in S3 or ADLS — The log still lists them, so reads fail with a missing file error. Change data through Delta.
  • Reading a Delta folder as plain Parquet — spark.read.parquet(path) ignores the log and reads removed files too: duplicates and deleted rows come back.
  • Thinking OPTIMIZE changes the data — It rewrites files with dataChange=false: the rows are identical, and streams skip the commit.

Key takeaways

  • The table is the set of files the log says are live, not what is in the folder.
  • A commit is one numbered JSON file of add and remove actions; creating it is the atomic step.
  • Readers load the newest checkpoint and replay the commits after it; writers commit last and retry or fail on conflict.
  • Time travel needs both the log (30 days) and the files (7 days after VACUUM).

Interview prep

THE QUESTION

"How does Delta give you ACID on top of S3?"

Atomicity from creating one commit file, consistency from schema enforcement, isolation from optimistic concurrency (serializable writes, snapshot reads), durability from the object store. Readers see only complete versions, because they trust only files the log lists.

Avoid: "Delta writes a log file" without how a commit is made atomic and how conflicts are detected.

Follow-ups · answer out loud, then open

Follow-up"What is a checkpoint in the Delta log, and why does it exist?"
Every 10 commits by default, a Parquet file with the full table state, so readers replay only the commits after it, not thousands of JSON files.
Scenario"Listing a Delta table takes minutes, and _delta_log has 2 million files. What happened?"
Log cleanup is not running, or retention is very long. Old commits go after delta.logRetentionDuration (30 days), when a checkpoint is written: check that property and that checkpoints are created.
Trap"Deleting rows with DELETE removes them from storage."
DELETE commits a remove action (or a deletion vector); the files stay on storage for time travel until VACUUM.

Check yourself

3 questions

A writer crashes after writing two Parquet files but before creating 00000000000000000006.json. What do readers see?

Show the answer

The table as of version 5; the new files are ignored. Readers only trust files listed in the log; the two files are orphans until VACUUM deletes them.

A table is at version 47 with default settings. What does a reader load to get the current state?

Show the answer

The checkpoint at version 40, then commits 41 to 47. Checkpoints come every 10 commits by default; the reader starts at 40 and replays 41 to 47.

You run VACUUM with the default retention, then query a version from 10 days ago. What happens?

Show the answer

It can fail, because files only that version needed may have been deleted. The log still describes it, but VACUUM deleted files removed more than 7 days ago; if the version needs one, the read fails.

Practise this

Problems that use this, graded on hidden tests

Keep going

Up next · Delta day to day · lesson 2 of 4 · 5 min read
Time travel and RESTORE
Query or roll back to any earlier version of a table, and what retention does to that promise.

Related lessons

Previous: The medallion architecture

Primary sources: Delta transaction log protocol · Delta Lake documentation