Inside table formats
Part of the free LogicWiz Data Engineering course, Module 4: Storage and file formats. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 2:00 a.m. The nightly MERGE and a privacy DELETE reach SwiftKart's Delta orders table in the same minute, and the DELETE dies with ConcurrentDeleteReadException. On the Iceberg copy of the same table, a simple query spends 40 seconds planning before it reads a row. At 9:00 Nora says: "Both answers are in the small files next to the data. Open the log."
You'll learn to
- Read a Delta log and say which files a reader opens
- Explain how two writers commit safely without locking the table
- Follow Iceberg's metadata tree from the catalog to a data file
- Compare copy-on-write with merge-on-read, with numbers
Learn
The log is the table
Nora starts with the Delta table. Next to its Parquet files is a folder, _delta_log/, holding one small JSON file per commit: 00000000000000000000.json, then ...01.json, and so on. Lesson 4.4 built a toy version. This is the real one.
Each line of a commit file is one action. Two matter most.
add: this data file joins the table. It carries the file's path, size and statistics (row count, min and max per column), which let readers skip files.remove: this file leaves the table. It stays on storage untilVACUUM.
A reader builds the table by replaying the commits in order: the live files are every add not later removed. The table at one version is called a snapshot.
A Delta table folder: buttons append, update, delete, merge, optimize and vacuum; each adds a JSON commit to _delta_log listing add and remove actions, the Parquet files light up for the version picked on a time-travel slider, and vacuumed files disappear for good.
Press Append, Update and Delete and read each new commit: every change is a list of add and remove actions. Then run OPTIMIZE (its actions carry dataChange: false, because no rows changed), then VACUUM, and try to time-travel back to version 0.
Do not replay 50,000 files
Replaying works, but a busy table gets a new commit every few minutes. Before long that is 50,000 small files to read before every query.
So every so often Delta writes a checkpoint: one Parquet file that holds the whole state at one version, every live add included. A tiny file called _last_checkpoint says where the newest one is. Open-source Delta writes a checkpoint every 10 commits.
A reader then needs three things: _last_checkpoint, the checkpoint it points to, and the few commits written after it. To read version 1,234 that is the checkpoint for 1,230 and commits 1,231 to 1,234. Six files, not 1,235.
A reader opens the latest version
A folder tree of a Delta table after 13 commits. The reader opens the _last_checkpoint file, then the version-10 checkpoint, then commits 11 and 12, and never opens commits 0 to 10.
The folder after 13 commits. Versions 0 to 12, a checkpoint written at version 10, and the data files beside the log.
Find the checkpoint. The reader opens
_last_checkpointfirst. It says: the newest checkpoint is at version 10.Load the state at version 10. One Parquet file lists the 10 data files that were live then. Commits 0 to 10 are never opened.
Replay what came after. Commits 11 and 12 each add one file. The table at version 12 has 12 live files, and the reader opened 4 small files to learn that.
Watch the files in _delta_log/ turn green in the order the reader opens them. The example below builds this exact folder.
Build a log and a checkpoint, then read it like Delta
import duckdb, json, os
os.makedirs("orders/_delta_log", exist_ok=True)
def log_path(v, ext="json"):
return f"orders/_delta_log/{v:020d}.{ext}"
def commit(v, adds=(), removes=()):
actions = [{"commitInfo": {"operation": "DELETE" if removes else "WRITE"}}]
actions += [{"add": {"path": p, "dataChange": True}} for p in adds]
actions += [{"remove": {"path": p, "dataChange": True}} for p in removes]
with open(log_path(v), "x") as f: # put-if-absent
f.write("".join(json.dumps(a) + "\n" for a in actions))
for v in range(13): # 13 commits; commit 7 rewrites part-3 to drop a cancelled order
commit(v, adds=[f"part-{v}.parquet"], removes=["part-3.parquet"] if v == 7 else [])
print(open(log_path(7)).read())
def replay(versions, live=()):
live = set(live)
for v in versions:
for line in open(log_path(v)):
action = json.loads(line)
if "add" in action:
live.add(action["add"]["path"])
if "remove" in action:
live.discard(action["remove"]["path"])
return live
# Checkpoint at version 10: the reconciled state of commits 0 to 10, as Parquet.
state = sorted(replay(range(11)))
values = ", ".join(f"('{p}')" for p in state)
duckdb.sql(f"COPY (SELECT * FROM (VALUES {values}) AS t(path)) TO '{log_path(10, 'checkpoint.parquet')}' (FORMAT PARQUET)")
with open("orders/_delta_log/_last_checkpoint", "w") as f:
json.dump({"version": 10, "size": len(state)}, f)
# A reader: _last_checkpoint, then the checkpoint, then only the commits after it.
last = json.load(open("orders/_delta_log/_last_checkpoint"))
checkpoint = log_path(last["version"], "checkpoint.parquet")
from_checkpoint = [r[0] for r in duckdb.sql(f"SELECT path FROM '{checkpoint}'").fetchall()]
live = replay(range(last["version"] + 1, 13), from_checkpoint)
opened = ["_last_checkpoint", os.path.basename(checkpoint)] + [os.path.basename(log_path(v)) for v in range(11, 13)]
print("reader opened:", opened)
print(len(live), "live files; same as replaying all 13 commits:", live == replay(range(13)))
Look at the printed commit 7 first: one commit adds a new file and removes an old one. That is the shape of every change. A real checkpoint also stores statistics, metaData and protocol; the reading rule is the same.
Two writers at 2:00 a.m.
Now the failure. Delta writers never lock the table: every job would wait for every other job. They work optimistically. Assume nobody gets in the way, and check at the end.
Each writer notes the version it read, say 7, and does its work. To commit, it tries to create ...08.json with put-if-absent: the create succeeds only if no such file exists. Exactly one writer can win version 8.
The loser does not give up at once. It reads what version 8 changed and asks one question: did that change anything I read? If not, it retries as version 9 without redoing its work. If yes, it must fail, because its result was worked out from data that is no longer the table. This scheme is called optimistic concurrency.
Two writers, one Delta table
A MERGE job and a DELETE job both read version 7 and both rewrite part-3. The MERGE creates commit 8 first; the DELETE finds commit 8 already exists, sees that it removed part-3, which the DELETE had read, and fails with ConcurrentDeleteReadException.
Both read version 7. Neither job knows about the other.
Both do their work. Each writes a new data file, off to the side where no reader looks. Both started from
part-3.The MERGE commits first. Its put-if-absent of
8.jsonsucceeds. Version 8 says: remove part-3, add part-20.The DELETE tries version 8 too. The file already exists, so the create is refused. Nothing is overwritten.
The check. The DELETE reads commit 8 and finds that part-3, a file it read, has been removed. It fails with
ConcurrentDeleteReadException. This is the 2:00 a.m. error.
Read each step top to bottom: the newest arrows are at the bottom. Had the DELETE read only part-5, version 8 would not clash and it would commit as version 9 at once. Narrow what each job reads (a partition filter in the MERGE condition) and conflicts become rare.
What Delta calls each conflict
| Exception | What the other writer did |
|---|---|
| ConcurrentAppendException | Added files to a partition you read. Blind appends are exempt, so plain INSERTs never conflict |
| ConcurrentDeleteReadException | Removed a file you read |
| ConcurrentDeleteDeleteException | Removed a file you are removing too, for example two compactions |
| MetadataChangedException | Changed the schema or the table properties |
Databricks runs Delta at the WriteSerializable isolation level by default. The stricter Serializable also fails when a concurrent append touches what you read.
Put-if-absent and a conflict check
import json, os
os.makedirs("t/_delta_log", exist_ok=True)
def path(v):
return f"t/_delta_log/{v:020d}.json"
def try_commit(v, actions):
"""Put-if-absent: mode "x" creates the file only if it does not exist yet."""
try:
with open(path(v), "x") as f:
json.dump(actions, f)
return True
except FileExistsError:
return False
def conflicts(read_files, winner):
"""Files the winner removed that this transaction read: Delta's ConcurrentDeleteReadException."""
return sorted(set(read_files) & set(winner["remove"]))
# Both jobs read version 7.
merge = {"read": ["part-3.parquet"], "add": ["part-20.parquet"], "remove": ["part-3.parquet"]}
delete = {"read": ["part-5.parquet", "part-6.parquet"], "add": ["part-21.parquet"], "remove": ["part-5.parquet"]}
print("MERGE commits version 8:", try_commit(8, merge))
print("DELETE commits version 8:", try_commit(8, delete))
winner = json.load(open(path(8)))
print("DELETE checks version 8, conflicts on:", conflicts(delete["read"], winner))
print("DELETE commits version 9:", try_commit(9, delete))
late = {"read": ["part-3.parquet"], "add": ["part-22.parquet"], "remove": ["part-3.parquet"]}
print("A third job that read part-3 at version 7 conflicts on:", conflicts(late["read"], winner))
Mode "x" creates the file only if it does not exist: put-if-absent on a local disk, the same promise S3's If-None-Match: * gives. The loser checks the winner's commit against the files it read and, with no overlap, takes the next version without redoing its work.
Remember: write the data files first, then race for one small file. The loser checks what the winner changed, and either retries or fails.
Iceberg keeps a tree, not a list
The Iceberg copy answers the same question (which files are the table?) with a different shape: a tree, read from the top.
- The catalog says where the table's current
metadata.jsonis. metadata.jsonholds the schema, the partition scheme and the list of snapshots.- Each snapshot points to one manifest list: one entry per manifest, with the range of partition values inside it.
- Each manifest lists data files, with every file's partition value and its min and max per column.
- The data files are Parquet.
A query prunes at every level: the manifest list skips whole manifests, a manifest skips files, a footer skips row groups. A commit writes new files at each level, then asks the catalog to move its pointer.
One Iceberg table after three snapshots
A tree: the catalog entry points to v3.metadata.json, whose current snapshot has a manifest list with three manifests: two listing data files for June days, and one listing a position-delete file; an older manifest list is kept for time travel.
Read it from the top: each level points to the one below. Snapshot 3 wrote one manifest and one manifest list and reused m1 and m2. A query for 3 June skips m1 by its range of days and reads m2, m3, one data file and its delete file. (The red file is a note of deleted rows; a later section explains it.)
An Iceberg commit, refused once
A sequence: a writer loads the table at snapshot 41, writes new data and metadata files, and posts a commit asserting snapshot 41; another writer has already moved the table to 42, so the catalog answers 409; the writer re-applies its change on snapshot 42 and posts again, and the catalog accepts it.
Read it top to bottom. The writer asks the catalog to move the pointer only if the table is still at snapshot 41: a compare-and-swap. Another writer got there first, so the answer is 409. The retry rewrites only the manifest list and the metadata file; the data files and the new manifest are reused.
Three formats, three kinds of log
| Delta Lake | Apache Iceberg | Apache Hudi | |
|---|---|---|---|
| Where the history lives | JSON commits in deltalog/, plus Parquet checkpoints | metadata.json, manifest lists and manifests; the catalog points at the current one | A timeline in .hoodie/timeline/: one small file per action and state |
| The step that publishes | Create the next commit file, put-if-absent | The catalog swaps its pointer, compare-and-swap | The action's file goes from requested to inflight to completed |
| What a reader trusts | Commits in order, from the last checkpoint | The current snapshot's tree | Completed instants only; an inflight one left by a crash is rolled back |
All three keep the data in Parquet files that are never edited. A Hudi action (commit, deltacommit, compaction, clean, rollback, replacecommit) starts as <requested time>.<action>.requested, becomes .inflight, and when complete is named <requested time>_<completed time>.<action> in Hudi 1.0.
Rewrite the file, or leave a note
The privacy DELETE raises one more question. Parquet files cannot be edited. So how do you remove one customer's rows from a 512 MB file? There are two ways.
Copy-on-write writes a whole new file without those rows and swaps it in. One row in a 512 MB file means a new 512 MB file. Readers have nothing extra to do.
Merge-on-read leaves the file alone and writes a small note beside it: "rows 1 and 5 of this file are deleted". Readers apply the note as they read. Delta calls its note a deletion vector; Iceberg has position delete files and equality delete files. Writes get cheap and reads pay a little, until a compaction rewrites the file and drops the note.
One deleted row, two strategies
Two groups of boxes. Copy-on-write replaces a 512 MB file with a new 512 MB copy without the row. Merge-on-read keeps the 512 MB file and adds a deletion vector of a few bytes.
Compare what is newly written on each side: a 512 MB file on the left, a few bytes on the right.
An UPDATE of 1,000 orders spread over 1,000 files of 512 MB
| Copy-on-write | Merge-on-read (deletion vectors) | |
|---|---|---|
| Data written | 1,000 new files: about 500 GB | one small file with the 1,000 updated rows |
| Delete markers | none: the old files leave the table | 1,000 small bitmaps, one per touched file |
| Commit | 1,000 removes + 1,000 adds | each touched file re-added with its DV, plus 1 add |
| Reads afterwards | no extra work | load 1,000 DVs and skip those rows; one more file |
| Later | VACUUM removes the old files after retention | compaction rewrites the files and drops the DVs, then VACUUM |
DV is short for deletion vector. Merge-on-read wins on scattered updates (change feeds, privacy deletes): 1,000 x 512 MB is 512,000 MB of rewrite for 1,000 rows. Copy-on-write wins on heavily read tables with rare, clustered updates.
A deletion vector by hand
import duckdb
duckdb.sql("COPY (SELECT order_id, status FROM 'data/orders.csv' WHERE order_id <= 1008 ORDER BY order_id) TO 'part-0.parquet' (FORMAT PARQUET)")
deletion_vector = {1, 5} # row positions 1 and 5 were deleted by a later commit
rows = duckdb.sql("SELECT file_row_number, order_id, status FROM read_parquet('part-0.parquet', file_row_number = true) ORDER BY 1").fetchall()
for pos, order_id, status in rows:
print(f"{pos} {order_id} {status}{' <- deleted' if pos in deletion_vector else ''}")
live = [order_id for pos, order_id, _ in rows if pos not in deletion_vector]
print(len(rows), "rows in the file,", len(live), "visible:", live)
file_row_number is a row's position in its file, which is what a deletion vector or a position delete stores. Orders 1002 and 1006 are still inside the untouched file. They are only hidden.
Why planning took 40 seconds
Each format stays fast only if someone tidies its metadata. Left alone, something grows.
- Iceberg: every commit adds a manifest. Frequent small appends leave thousands, and planning has to open them. That is the 40 seconds.
rewrite_manifestsmerges them, and old snapshots should be expired. - Delta: the checkpoint has one row per live file. Two million files means a two-million-row checkpoint for every new reader, and
VACUUMhas to list the whole folder. - Merge-on-read: the notes pile up, and every read applies them. Equality deletes cost most. Compact on a schedule.
- Many writers: optimistic commits are cheap when jobs touch different files. Twenty jobs merging into the same partitions every minute spend their time retrying.
Maintenance by format
| Job | Delta Lake | Iceberg | Hudi |
|---|---|---|---|
| Compact small files | OPTIMIZE (or liquid clustering) | rewritedatafiles | clustering; compaction on MOR |
| Delete unreferenced data files | VACUUM (7-day default retention) | expiresnapshots, then removeorphanfiles | the cleaner |
| Keep metadata small | checkpoints; log entries over 30 days dropped | rewritemanifests; drop old metadata.json files (write.metadata.delete-after-commit.enabled) | timeline archiving |
| Purge soft deletes | REORG TABLE ... APPLY (PURGE) | rewritepositiondeletefiles, rewritedatafiles | compaction |
MOR is short for merge-on-read.
The trap: a delete is not an erase. With copy-on-write the old files stay until VACUUM or expire_snapshots removes them. With deletion vectors or delete files the rows are still inside the live data files, only masked. For a privacy request you must purge (rewrite the files; on Delta, REORG ... APPLY (PURGE)) and then vacuum past the retention period. And never shorten VACUUM retention below your longest-running job or stream: it can delete files a reader is still using.
Databricks can switch deletion vectors on for new tables (a workspace setting) and runs predictive optimization (scheduled OPTIMIZE and VACUUM) on Unity Catalog managed tables. Iceberg teams schedule rewrite_data_files, rewrite_manifests and expire_snapshots. Delta's UniForm writes Iceberg metadata for the same Parquet files. Hudi is often picked for tables with heavy upserts from change feeds.
Numbers to remember
| What | Number or name | Good to know |
|---|---|---|
| Delta commit file | the version, zero-padded to 20 digits, .json | One JSON action per line. An add holds the path, partition values, size, dataChange and stats |
| Other Delta actions | metaData, protocol, commitInfo, txn, cdc | Schema, partition columns and properties; reader and writer versions and table features; txn holds a stream's last batch id, for idempotent writes. In a replay the latest metaData and protocol win |
| Checkpoint | every 10 commits (delta.checkpointInterval = 10) | Named like 00000000000000000010.checkpoint.parquet. V2 checkpoints split huge file lists into sidecar files |
| Delta log retention | 30 days (delta.logRetentionDuration) | Older log entries are deleted when checkpoints are written, so time travel is limited by the log as well as by VACUUM's 7-day file retention |
| Put-if-absent on S3 | since August 2024 (If-None-Match: , else 412) | ADLS and GCS have long offered it. Before, Delta on S3 allowed one writing cluster per table unless every writer used a DynamoDB-backed log store (S3DynamoDBLogStore) |
| Iceberg pointer swap | REST catalog: 409 if the commit's requirements fail | A Hive metastore takes a lock; Glue does a conditional update. A failed swap is retried 4 times by default (commit.retry.num-retries) |
| Iceberg manifest merge | once 100 accumulate (commit.manifest.min-count-to-merge) | Every metadata.json lists all snapshots, so expire them |
| Iceberg write modes | copy-on-write by default | write.delete.mode, write.update.mode, write.merge.mode. Hudi has a copy-on-write table type too |
| Iceberg delete files | v2: position deletes and equality deletes | A position delete is a data file's path plus row positions; an equality delete is column values such as orderid = 1042. v3 replaces position deletes with deletion vectors, bitmaps stored in Puffin files |
| Delta deletion vector | a RoaringBitmap of deleted row positions per data file | Inline in the log or in a deletionvector<uuid.bin file. A table feature needing reader version 3, writer version 7 |
| Hudi merge-on-read table | base Parquet files plus log files | Merged by compaction |
What changed at SwiftKart
The DELETE failed for a good reason: the MERGE had rewritten a file it read. SwiftKart adds a partition filter to both jobs, so each reads only the days it needs, and runs the privacy DELETE after the MERGE. Privacy deletes are now followed by a purge and a vacuum, because a delete alone hides rows without erasing them. On the Iceberg copy, a scheduled rewrite_manifests and expire_snapshots take the 40 seconds of planning away.
Module 4 went from bytes on a page to tables with commits. You know where data lives and what it costs to read. Module 5 asks what the tables should look like, and Lesson 5.1 starts with one question: what does one row mean?
In one line
A table format is a record of which files count: Delta replays commits from a checkpoint, Iceberg walks a tree from the catalog, one small atomic write publishes each change, and a delete either rewrites the file or leaves a note for readers.
Interview corner
How does Delta guarantee that two writers cannot both commit version 8, and how does that differ on S3?
Each writer writes its data files first under unique names, then tries to create _delta_log/00000000000000000008.json. The log store must give mutual exclusion: exactly one creation succeeds. On ADLS and GCS that is a native conditional create; on S3 it was missing until conditional writes (If-None-Match) arrived in August 2024, so Delta on S3 allowed one writing cluster per table unless all writers used the DynamoDB-backed S3DynamoDBLogStore. The loser reads version 8, checks it against its own read set and either retries as 9 or fails with an exception such as ConcurrentDeleteReadException.
Walk me through how Iceberg plans a query.
The engine asks the catalog for the table's current metadata.json, reads the current snapshot and its manifest list, and uses each manifest's partition-value ranges to skip whole manifests. It reads the surviving manifests and keeps the data and delete files whose partition values and column lower and upper bounds can match the filter. Then it reads the Parquet footers of those files and skips row groups. Planning cost grows with the number of manifests and entries, so frequent small commits without manifest merging slow it down.
Copy-on-write or merge-on-read for a CDC table where 1% of rows change every hour?
Changed keys are scattered, so copy-on-write would rewrite most files every hour: if 1% of 100 million rows touch most of the 512 MB files, that is close to rewriting the table. Merge-on-read writes deletion vectors or position deletes plus small files of new rows, so writes stay proportional to the change. The price is read-time merging and growing delete files, so I would schedule compaction (OPTIMIZE or rewrite_data_files) daily or by delete-file count, and keep copy-on-write for tables that are updated rarely and read heavily.
An Iceberg table takes 40 seconds to plan a simple query. How do you diagnose and fix it?
Look at the metadata tables: count manifests and their sizes (the manifests and all_manifests tables), snapshots, and delete files. Typical causes are thousands of tiny manifests from streaming or frequent appends, a huge snapshot history in metadata.json, and many position or equality delete files. Fixes: rewrite_manifests, expire_snapshots with a sensible retention, rewrite_data_files to compact data and fold in deletes, and make sure manifest merging is on for writers. Then compare planning time before and after.