Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Concept · 25 min · revision 2

Table Formats: Snapshots, Manifests and Atomic Commits

Walk the Iceberg metadata tree from the catalog pointer through metadata.json, the manifest list and manifests down to data files, watch a compare-and-swap commit reject a concurrent writer, and see how Delta Lake reaches the same guarantees with a numbered transaction log.

Contentsand lesson path

What you will learn

  • Create an Iceberg or Delta Lake table, evolve its schema and partitioning, and use snapshots for time travel and rollback, explaining how metadata makes commits atomic.

01. Why it matters

In the previous lesson, a folder of Parquet files on object storage could not swap compacted files into place safely, because the store has no transaction across objects. The same gap breaks everyday work: a job that fails halfway leaves some files visible, a reader that lists the folder during a write sees a mixture, nobody can say what the table looked like yesterday, and every query starts by listing keys.

An open table format fixes this with metadata. Data files are written once and never changed; metadata files say which data files form the table at each moment; and one small atomic step makes a new set current. This lesson takes Apache Iceberg apart file by file, races two writers against it, and shows how Delta Lake reaches the same result with a transaction log. The examples use Python 3.12, PyIceberg 0.12.0 with a SQLite catalog, PyArrow 26.0.1 and fastavro 1.13.1.

Terminal
mkdir table-formats && cd table-formats
python3.12 -m venv .venv && source .venv/bin/activate
python -m pip install "pyiceberg[sql-sqlite,pyarrow]==0.12.0" pyarrow==26.0.1 \
    fastavro==1.13.1

02. The Iceberg metadata tree

An Iceberg table is a tree of files with one pointer at the top:

  1. The catalog stores, per table name, the location of the current metadata file. It can be a database, a Hive Metastore, a REST service or a cloud catalog; here it is a row in SQLite.
  2. The table metadata file (NNNNN-<uuid>.metadata.json) holds the schemas, partition specs, sort orders, properties and the list of snapshots, each the complete state of the table after one commit, and names the current one.
  3. Each snapshot points to one manifest list, an Avro file listing its manifests with summaries, such as the range of partition values each covers and how many files it adds or deletes.
  4. Each manifest is an Avro file with one entry per data file: path, partition values, row count, size, column statistics and a status (added, existing or deleted).
  5. Data files hold the rows, usually as Parquet.

Every file in the tree is immutable. A commit writes new data files, new manifests where needed, a new manifest list and a new metadata file; unchanged manifests are reused, so adding one file does not rewrite the table's metadata. Planning reads the tree from the top, skipping manifests by their summaries and data files by their statistics, without listing folders. This describes format versions 1 to 3, the adopted versions in November 2026. Version 4 is still a draft under active development; it restructures this metadata, but the idea of an immutable tree under one pointer stays.

The script creates a table, commits twice and walks the tree with plain file reads, printing counts because file names contain random UUIDs.

Python · tree.py
"""Create a small Iceberg table, commit twice, then walk its metadata tree."""
import json
import sqlite3
from pathlib import Path

import fastavro
import pyarrow as pa
from pyiceberg.catalog.sql import SqlCatalog

Path("warehouse").mkdir(exist_ok=True)
catalog = SqlCatalog("demo", uri="sqlite:///catalog.db",
                     warehouse=Path("warehouse").absolute().as_uri())
catalog.create_namespace("demo")
first = pa.table({"id": pa.array([1, 2, 3], pa.int64()),
                  "city": ["Lyon", "Graz", "Cork"]})
table = catalog.create_table("demo.cities", schema=first.schema)
table.append(first)                                      # commit 1
table.append(pa.table({"id": pa.array([4], pa.int64()),
                       "city": ["Brno"]}))               # commit 2


def local(uri):
    return uri.removeprefix("file://")


# 1. The catalog holds one pointer per table.
pointer = sqlite3.connect("catalog.db").execute(
    "SELECT metadata_location FROM iceberg_tables").fetchone()[0]
print("catalog pointer ->", Path(pointer).name[:6] + "<uuid>.metadata.json")

# 2. The metadata file lists schemas, specs and every snapshot.
meta = json.loads(Path(local(pointer)).read_text())
current = next(s for s in meta["snapshots"]
               if s["snapshot-id"] == meta["current-snapshot-id"])
print("metadata.json: format-version", meta["format-version"], "|",
      len(meta["snapshots"]), "snapshots | current sequence number",
      current["sequence-number"])

# 3. The current snapshot points to one manifest list.
with open(local(current["manifest-list"]), "rb") as f:
    manifests = list(fastavro.reader(f))
print("manifest list:", len(manifests), "manifests")

# 4. Each manifest lists data files with a status and a row count.
STATUS = {0: "EXISTING", 1: "ADDED", 2: "DELETED"}
for m in manifests:
    with open(local(m["manifest_path"]), "rb") as f:
        for entry in fastavro.reader(f):
            print(f"  manifest from sequence {m['sequence_number']}: "
                  f"{STATUS[entry['status']]} data file, "
                  f"{entry['data_file']['record_count']} rows")
Terminal
python tree.py
Expected output
catalog pointer -> 00002-<uuid>.metadata.json
metadata.json: format-version 2 | 2 snapshots | current sequence number 2
manifest list: 2 manifests
  manifest from sequence 2: ADDED data file, 1 rows
  manifest from sequence 1: ADDED data file, 3 rows

Three metadata files exist now (00000 from the create, 00001 and 00002 from the appends), and the catalog points to the newest. The current snapshot has sequence number 2. Its manifest list names two manifests: the one written by commit 2 with the new file, and the one written by commit 1, reused unchanged. The sequence number is assigned to every successful commit and inherited by the files it adds, which lets Iceberg order changes, for example to decide which delete files apply to which data files.

03. How a commit becomes atomic

Readers find data only by walking down from the pointer, so nothing a writer stores is visible until the pointer moves; if the job dies first, its files stay invisible. The commit is one compare-and-swap (check-and-put): "point to my new metadata file, but only if you still point to the one my change is based on". The Iceberg specification calls this optimistic concurrency: writers take no locks and find out about conflicts at the swap.

PyIceberg's SQL catalog does the swap with one statement, UPDATE iceberg_tables SET metadata_location = :new WHERE ... AND metadata_location = :old, and treats zero updated rows as a conflict. REST catalogs and Hive Metastores make the same check their own way, and file systems with an atomic rename can use the rename. After a failed swap, the writer reloads, re-applies its change on top and tries again. An append can always be re-applied; a rewrite only if the files it replaces are still in the table.

Watch it happen: two writers load the same version, both append, and a logging handler counts PyIceberg's retries.

Python · conflict.py
"""Two writers load the same table version, then both try to commit."""
import logging
from pathlib import Path

import pyarrow as pa
from pyiceberg.catalog.sql import SqlCatalog


class CountRetries(logging.Handler):
    retries = 0

    def emit(self, record):
        if "concurrent update" in record.getMessage():
            CountRetries.retries += 1


logging.getLogger("pyiceberg").addHandler(CountRetries())
logging.getLogger("pyiceberg").propagate = False

catalog = SqlCatalog("demo", uri="sqlite:///catalog.db",
                     warehouse=Path("warehouse").absolute().as_uri())
writer_a = catalog.load_table("demo.cities")
writer_b = catalog.load_table("demo.cities")  # same base version as A
print("both start from sequence number",
      writer_a.current_snapshot().sequence_number)

row = pa.table({"id": pa.array([5], pa.int64()), "city": ["Ghent"]})
writer_a.append(row)
print("A committed sequence number", writer_a.current_snapshot().sequence_number)
writer_b.append(row)
print("B committed sequence number", writer_b.current_snapshot().sequence_number,
      "after", CountRetries.retries, "failed swap")

final = catalog.load_table("demo.cities")
print("snapshots:", len(final.snapshots()), "| rows:",
      final.scan().to_arrow().num_rows)
Terminal
python conflict.py
Expected output
both start from sequence number 2
A committed sequence number 3
B committed sequence number 4 after 1 failed swap
snapshots: 4 | rows: 6

Writer B's first swap failed, because the pointer had moved to A's metadata file. PyIceberg reloaded, re-applied B's append on top of A's snapshot and swapped again, so both rows arrived and the history stayed a single line: snapshots 3 and 4, one after the other. A reader that loaded the table before either commit keeps reading its own snapshot until it refreshes; it never sees half a commit and never takes a lock.

04. Delta Lake: the same idea as a numbered log

A Delta Lake table is a folder of data files plus _delta_log/. Each commit is one JSON file named by its version, zero-padded to 20 digits (00000000000000000000.json, then ...0001.json). Each line is an action: add and remove name data files, metaData carries the schema and partition columns, protocol lists required features, commitInfo records who did what. The table at version n is the replay of versions 0 to n. To keep replays short, writers periodically write a checkpoint, usually a Parquet file with the complete state at one version, and readers start from the newest one.

The atomic step is creating the next log file. The Delta protocol says writers must never overwrite an existing log entry and should use the storage's atomic primitives so that concurrent writers cannot overwrite each other: in practice, "put if absent". The loser of a race re-reads the log, checks for conflicts and tries the next number. Newer Delta versions also support catalog-managed tables, where a catalog ratifies commits, much like Iceberg's catalog. The model below shows the rule using the local file system's O_CREAT | O_EXCL; it models the protocol idea and is not the Delta library.

Python · delta_log_model.py
"""A model of Delta Lake's commit rule: each version is a new log file.

Not the Delta library: O_CREAT | O_EXCL on a local file system stands in
for the storage primitive "create this object only if it does not exist".
"""
import json
import os
from pathlib import Path

log = Path("mytable/_delta_log")
log.mkdir(parents=True, exist_ok=True)


def latest_version():
    return max((int(p.stem) for p in log.glob("*.json")), default=-1)


def put_if_absent(version, actions):
    path = log / f"{version:020d}.json"
    try:
        fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
    except FileExistsError:
        return False
    with os.fdopen(fd, "w") as f:
        f.write("".join(json.dumps(a) + "\n" for a in actions))
    return True


def commit(writer, base, actions):
    version = base + 1
    while not put_if_absent(version, actions):
        print(f"  {writer}: version {version} exists, re-reading the log")
        version = latest_version() + 1  # a real writer checks conflicts here
    print(f"  {writer}: committed version {version}")


def add(path):
    return {"add": {"path": path, "dataChange": True}}


commit("setup", -1, [add("part-000.parquet")])
commit("setup", 0, [add("part-001.parquet")])
base = latest_version()  # writers A and B both read version 1
commit("A", base, [add("part-002.parquet")])
commit("B", base, [add("part-003.parquet")])
commit("compactor", latest_version(), [
    {"remove": {"path": "part-000.parquet", "dataChange": False}},
    {"remove": {"path": "part-001.parquet", "dataChange": False}},
    {"add": {"path": "part-004.parquet", "dataChange": False}},
])

live = set()
for path in sorted(log.glob("*.json")):  # replay the log in version order
    for line in path.read_text().splitlines():
        action = json.loads(line)
        if "add" in action:
            live.add(action["add"]["path"])
        if "remove" in action:
            live.discard(action["remove"]["path"])
print("latest log file:", max(p.name for p in log.glob("*.json")))
print("live files:", sorted(live))
Terminal
python delta_log_model.py
Expected output
  setup: committed version 0
  setup: committed version 1
  A: committed version 2
  B: version 2 exists, re-reading the log
  B: committed version 3
  compactor: committed version 4
latest log file: 00000000000000000004.json
live files: ['part-002.parquet', 'part-003.parquet', 'part-004.parquet']

The compaction is one version that removes two files and adds one, so no reader can see the new file next to the old ones: the swap that plain folders could not do. Its actions carry dataChange: false, which the protocol defines as "this only rearranges existing data", so streaming readers can ignore it. Iceberg records the same intent with the snapshot operation replace, as opposed to append, overwrite or delete.

05. What snapshots and metadata give you

Because old snapshots and their files stay until someone removes them, a table format gives you several features almost for free:

  • Time travel: read the table as of an older snapshot id or timestamp, for audits, debugging or reproducible training data.
  • Rollback: make an older snapshot current again. Only metadata changes; no data file is copied.
  • Schema evolution: Iceberg gives every column a permanent field id stored in the data files, so adding, dropping or renaming a column changes only metadata, and an old file without a new column reads as null for it (or its initial default in format v3).
  • Hidden partitioning and partition evolution: a spec such as day(order_ts) derives partition values from a column, so queries filter on order_ts and the engine prunes. The spec can change later; each data file remembers its spec.

The cost is maintenance: expiring old snapshots (Iceberg) or vacuuming unreferenced files (Delta keeps them 7 days by default), removing orphan files from failed jobs, and compacting small files and manifests. Expiring a snapshot ends time travel to it, so retention is a business decision too. The next lab does all of this hands-on.

06. Check your understanding

Practice check · 3 questions

Snapshots, manifests and commits

Apply the ideas of this lesson to three new situations. Each question has one best answer.

Q1. A report loads an Iceberg table at snapshot 12 and starts a scan that takes 20 minutes. Five minutes in, a compaction commits snapshot 13, which replaces many of the files that snapshot 12 lists. What happens to the report?
Q2. Two Delta writers both read version 41 and try to create `_delta_log/00000000000000000042.json` on storage that supports put-if-absent. What happens?
Q3. An Iceberg table has 2,000 manifests, and a query filters on one day. How does planning avoid opening all 2,000 manifests?
Practice only: not graded, not saved, not evidence.

07. Apply it

For the practice project of this skill, write a one-page design note before you build the Iceberg table:

  1. Choose the catalog you would use in production (for example a REST catalog, AWS Glue or a Hive Metastore) and say how it performs the atomic pointer swap.
  2. Choose a partition spec that uses a transform such as day(...) and explain which queries it lets the planner prune.
  3. Decide how long snapshots must be kept for time travel and rollback in your use case, and how often compaction and snapshot expiry should run.

Then run tree.py against your own table after three appends and check that the manifest count and statuses match what you expect.

08. Review prompt

Without looking back:

  1. Name the five levels of the Iceberg metadata tree, from the catalog to the data, and one thing each level stores.
  2. Why are new data files invisible to readers until the commit, and what single step makes them visible?
  3. What does a writer do when its compare-and-swap fails, and which kinds of change can it re-apply?
  4. How does a Delta Lake commit become atomic, and what is a checkpoint for?
  5. Which maintenance tasks does a table format need, and what do you lose when you expire a snapshot?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check