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 5 of 6 · Lab · 30 min · revision 2

Lab: Evolve, Time-Travel and Compact an Iceberg Table

With PyIceberg and a local SQLite catalog, create a partitioned Iceberg table, append in several commits, add a column without rewriting files, move from monthly to daily partitions, read old snapshots, roll back a bad write, and compact a partition of small files in one commit.

Contentsand lesson path

What you will learn

  • Explain how object storage differs from a distributed file system such as HDFS, lay out data with partitioning, sorting and target file sizes so engines can prune it, and fix a small-files problem with compaction.
  • 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. Goal and setup

You will take a small Iceberg table through the life of a real one: create it partitioned by month, load it in several commits, add a column, switch to daily partitions, read earlier snapshots, roll back a bad write, and compact a partition that a frequent job filled with small files. After every step you check the table's own metadata to see what really changed.

You need: Python 3.12 and PyIceberg 0.12.0 with three extras: sql-sqlite (a catalog in a local SQLite file), pyarrow (Parquet reading and writing) and pyiceberg-core (compiled code that the month() and day() transforms need). Tested with PyIceberg 0.12.0, pyiceberg-core 0.10.1 and PyArrow 26.0.1 on Linux. The folder warehouse/ plays the bucket. Unlike Spark, Flink or Trino, PyIceberg needs no JVM.

Snapshot ids and file names are random, so the scripts print sequence numbers, operations and counts. The data comes from fixed seeds, so the counts match the outputs below.

Project layout at the end of the lab
iceberg-lab/
├── lab.py            helpers: catalog, seeded orders, history table
├── create_table.py   step 1
├── load.py           step 2
├── add_column.py     step 3
├── change_spec.py    step 4
├── time_travel.py    step 5
├── bad_write.py      step 6
├── rollback.py       step 6
├── compact.py        step 7
├── catalog.db        the SQLite catalog (created by step 1)
└── warehouse/        data and metadata files of the table
Terminal
mkdir iceberg-lab && cd iceberg-lab
python3.12 -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
python -m pip install "pyiceberg[sql-sqlite,pyarrow,pyiceberg-core]==0.12.0" \
    pyarrow==26.0.1

Every step imports these helpers: open_catalog() opens the SQLite catalog, make_orders() builds a seeded batch that matches the current schema, show_history() prints one line per snapshot (* marks the current one), and describe_files() counts files and rows per spec and partition.

Python · lab.py
"""Shared helpers for the Iceberg lab: catalog, seeded orders, history."""
import random
from datetime import datetime, timedelta, timezone
from pathlib import Path

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


def open_catalog():
    Path("warehouse").mkdir(exist_ok=True)
    return SqlCatalog("lab", uri="sqlite:///catalog.db",
                      warehouse=Path("warehouse").absolute().as_uri())


def make_orders(table, first_id, n, start, days, seed, channel=None):
    """n seeded orders between start and start + days, as an Arrow table."""
    rng = random.Random(seed)
    t0 = datetime.fromisoformat(start).replace(tzinfo=timezone.utc)
    rows = []
    for i in range(n):
        rows.append({
            "order_id": first_id + i,
            "order_ts": t0 + timedelta(seconds=rng.randrange(days * 86_400)),
            "country": rng.choice(["DE", "FR", "GB", "ES"]),
            "amount": round(rng.uniform(5, 200), 2),
            "channel": channel,
        })
    schema = table.schema().as_arrow()
    return pa.Table.from_pylist(rows, schema=schema)


def show_history(table):
    current = table.current_snapshot().snapshot_id
    print("seq  operation  added-files  total-files  total-rows")
    for snap in table.snapshots():
        s = snap.summary
        mark = "*" if snap.snapshot_id == current else " "
        added = s.get("added-data-files") or "0"
        print(f"{snap.sequence_number:>3}{mark} {s.operation.value:<10}{added:>11}"
              f"{s.get('total-data-files'):>13}{s.get('total-records'):>12}")


def describe_files(table):
    """Count data files and rows per (spec id, partition value)."""
    groups = {}
    for f in table.inspect.files().to_pylist():
        part = [f"{k}={v}" for k, v in f["partition"].items() if v is not None]
        key = (f["spec_id"], ", ".join(part))
        files, rows = groups.get(key, (0, 0))
        groups[key] = (files + 1, rows + f["record_count"])
    for (spec_id, part), (files, rows) in sorted(groups.items()):
        print(f"  spec {spec_id}  {part:<24}{files:>2} files {rows:>5} rows")

02. Step 1: Create a table partitioned by month

An Iceberg schema gives every column a permanent field id. Data files store those ids, and readers match columns by id, not by name, which makes renames and drops safe. The spec uses the month() transform on order_ts, so Iceberg derives the partition value from the timestamp and nobody stores or filters on a separate month column. This is hidden partitioning.

Python · create_table.py
"""Step 1: create an Iceberg table partitioned by month(order_ts)."""
from pyiceberg.partitioning import PartitionField, PartitionSpec
from pyiceberg.schema import Schema
from pyiceberg.transforms import MonthTransform
from pyiceberg.types import (DoubleType, LongType, NestedField, StringType,
                             TimestamptzType)

from lab import open_catalog

schema = Schema(
    NestedField(1, "order_id", LongType(), required=True),
    NestedField(2, "order_ts", TimestamptzType(), required=True),
    NestedField(3, "country", StringType(), required=True),
    NestedField(4, "amount", DoubleType(), required=True),
)
spec = PartitionSpec(PartitionField(source_id=2, field_id=1000,
                                    transform=MonthTransform(),
                                    name="order_month"))
catalog = open_catalog()
catalog.create_namespace("shop")
table = catalog.create_table("shop.orders", schema=schema, partition_spec=spec)
print("format version:", table.format_version)
print(table.schema())
print("partition spec:", table.spec())
print("snapshots:", len(table.snapshots()))
Terminal
python create_table.py
Expected output
format version: 2
table {
  1: order_id: required long
  2: order_ts: required timestamptz
  3: country: required string
  4: amount: required double
}
partition spec: [
  1000: order_month: month(2)
]
snapshots: 0

The table exists with format version 2, the PyIceberg default, and no snapshots yet. warehouse/shop/orders/metadata/ holds one 00000-<uuid>.metadata.json, and the catalog row points to it.

03. Step 2: Load the table in three commits

Three loads arrive, like three runs of a daily batch job. The second load spans the end of January and the start of February, so it writes one file into each month partition. Each append() is one commit and creates one snapshot.

Python · load.py
"""Step 2: three appends, three snapshots."""
from lab import describe_files, make_orders, open_catalog, show_history

table = open_catalog().load_table("shop.orders")
table.append(make_orders(table, 1, 400, "2026-01-01", 31, seed=1))
table.append(make_orders(table, 401, 400, "2026-01-20", 31, seed=2))
table.append(make_orders(table, 801, 400, "2026-02-01", 28, seed=3))
show_history(table)
describe_files(table)
Terminal
python load.py
Expected output
seq  operation  added-files  total-files  total-rows
  1  append              1            1         400
  2  append              2            3         800
  3* append              1            4        1200
  spec 0  order_month=672          2 files   573 rows
  spec 0  order_month=673          2 files   627 rows

Each snapshot got the next sequence number, and the summaries keep running totals. The partition value 672 is months since January 1970, so 672 is January 2026 and 673 February. Iceberg stores this value in each file's manifest entry; the folder names under warehouse/ are only a convenience.

04. Step 3: Add a column without rewriting files

The shop starts recording the sales channel. Add an optional channel column and check whether a snapshot was created, whether any file was rewritten, and what old rows return.

Python · add_column.py
"""Step 3: schema evolution is a metadata change."""
import pyarrow.compute as pc
from pyiceberg.types import StringType

from lab import make_orders, open_catalog

table = open_catalog().load_table("shop.orders")
files_before = set(table.inspect.files()["file_path"].to_pylist())
snapshots_before = len(table.snapshots())

with table.update_schema() as update:
    update.add_column("channel", StringType(), doc="web, app or store")

files_after = set(table.inspect.files()["file_path"].to_pylist())
print("new column field id:", table.schema().find_field("channel").field_id)
print("snapshots before/after the change:", snapshots_before,
      len(table.snapshots()))
print("data files rewritten:", len(files_before - files_after), "of",
      len(files_before))

table.append(make_orders(table, 1201, 200, "2026-02-15", 14, seed=4,
                         channel="app"))
channel = table.scan(selected_fields=("channel",)).to_arrow()["channel"]
print("rows with channel = null (old files):", channel.null_count)
print("rows with channel = app (new file): ",
      pc.sum(pc.equal(channel, "app")).as_py())
still_there = files_before <= set(table.inspect.files()["file_path"].to_pylist())
print("old files still in the table:", still_there)
Terminal
python add_column.py
Expected output
new column field id: 5
snapshots before/after the change: 3 3
data files rewritten: 0 of 4
rows with channel = null (old files): 1200
rows with channel = app (new file):  200
old files still in the table: True

Adding the column wrote a new metadata file with a new schema, but no snapshot and no data file, because the data did not change. The new column got field id 5. An old Parquet file has no column with id 5, so readers return null for it: 1,200 old rows read as null, the 200 new rows as app. Because columns are matched by id, renaming channel later is also a metadata change.

05. Step 4: Change the partition spec from month to day

Most queries now look at single days, so new data should be partitioned by day(order_ts). With hidden partitioning that is a metadata change: the new spec gets a new spec id, old files keep the spec they were written with, and new files use the new one. The script then simulates a job that runs every few hours, appending six batches of 50 orders for 1 and 2 March, and plans three queries to count the files each would read.

Python · change_spec.py
"""Step 4: partition evolution, then six small appends under the new spec."""
from pyiceberg.expressions import And, GreaterThanOrEqual, LessThan
from pyiceberg.transforms import DayTransform

from lab import describe_files, make_orders, open_catalog

table = open_catalog().load_table("shop.orders")
with table.update_spec() as update:
    update.remove_field("order_month")
    update.add_field("order_ts", DayTransform(), "order_day")
for spec_id, spec in sorted(table.specs().items()):
    print("spec", spec_id, [f"{f.name}={f.transform}" for f in spec.fields])

for k in range(6):  # a job that runs every few hours
    table.append(make_orders(table, 1401 + 50 * k, 50, "2026-03-01", 2,
                             seed=10 + k, channel="web"))
describe_files(table)


def planned(start, end):
    expr = And(GreaterThanOrEqual("order_ts", start), LessThan("order_ts", end))
    tasks = list(table.scan(row_filter=expr).plan_files())
    specs = sorted({t.file.spec_id for t in tasks})
    print(f"  {start[:10]} .. {end[:10]}: {len(tasks)} files, specs {specs}")


print("files planned for a query on order_ts:")
planned("2026-01-10T00:00:00+00:00", "2026-01-12T00:00:00+00:00")
planned("2026-03-02T00:00:00+00:00", "2026-03-03T00:00:00+00:00")
planned("2026-02-27T00:00:00+00:00", "2026-03-02T00:00:00+00:00")
Terminal
python change_spec.py
Expected output
spec 0 ['order_month=month']
spec 1 ['order_day=day']
  spec 0  order_month=672          2 files   573 rows
  spec 0  order_month=673          3 files   827 rows
  spec 1  order_day=2026-03-01     6 files   161 rows
  spec 1  order_day=2026-03-02     6 files   139 rows
files planned for a query on order_ts:
  2026-01-10 .. 2026-01-12: 1 files, specs [0]
  2026-03-02 .. 2026-03-03: 6 files, specs [1]
  2026-02-27 .. 2026-03-02: 8 files, specs [0, 1]

Spec 0 still describes the five monthly files, untouched, and spec 1 the twelve new daily files. Queries keep filtering on order_ts, and planning handles each spec separately. The January query reads one file: the January partition holds two, but column statistics show that the second load's January file starts on 20 January. The 2 March query reads only that day's six files, and the last query crosses the boundary and plans files from both specs. Each March day now holds six files of about 25 rows; step 7 fixes that.

06. Step 5: Time-travel to earlier snapshots

Every snapshot is still in the metadata, together with the schema that was current when it was written. Reading with snapshot_id= plans the scan from that snapshot's manifest list. The script reads every snapshot in order and prints how many rows and columns it shows.

Python · time_travel.py
"""Step 5: read the table as of every snapshot."""
from lab import open_catalog, show_history

table = open_catalog().load_table("shop.orders")
show_history(table)
print("seq  rows  columns as of that snapshot")
for snap in table.snapshots():
    data = table.scan(snapshot_id=snap.snapshot_id).to_arrow()
    print(f"{snap.sequence_number:>3}  {data.num_rows:>4}  {data.column_names}")
Terminal
python time_travel.py
Expected output
seq  operation  added-files  total-files  total-rows
  1  append              1            1         400
  2  append              2            3         800
  3  append              1            4        1200
  4  append              1            5        1400
  5  append              2            7        1450
  6  append              2            9        1500
  7  append              2           11        1550
  8  append              2           13        1600
  9  append              2           15        1650
 10* append              2           17        1700
seq  rows  columns as of that snapshot
  1   400  ['order_id', 'order_ts', 'country', 'amount']
  2   800  ['order_id', 'order_ts', 'country', 'amount']
  3  1200  ['order_id', 'order_ts', 'country', 'amount']
  4  1400  ['order_id', 'order_ts', 'country', 'amount', 'channel']
  5  1450  ['order_id', 'order_ts', 'country', 'amount', 'channel']
  6  1500  ['order_id', 'order_ts', 'country', 'amount', 'channel']
  7  1550  ['order_id', 'order_ts', 'country', 'amount', 'channel']
  8  1600  ['order_id', 'order_ts', 'country', 'amount', 'channel']
  9  1650  ['order_id', 'order_ts', 'country', 'amount', 'channel']
 10  1700  ['order_id', 'order_ts', 'country', 'amount', 'channel']

The first three snapshots show four columns, because they predate channel; from snapshot 4 on there are five. Time travel only reads: it does not change the current snapshot. PyIceberg can also pick a snapshot by time with table.snapshot_as_of_timestamp(ms), and Spark and Trino offer SQL such as FOR VERSION AS OF.

07. Step 6: Recover from a bad write with a rollback

A backfill job re-loads 1 March, but its input file was truncated, so it replaces 161 good orders with 5. The job tags its commit with a snapshot property, as a well-behaved job should, so the rollback script can find it without anyone copying snapshot ids around.

Python · bad_write.py
"""Step 6a: a buggy backfill overwrites 1 March with only 5 orders."""
from pyiceberg.expressions import And, GreaterThanOrEqual, LessThan

from lab import make_orders, open_catalog

MARCH_1 = And(GreaterThanOrEqual("order_ts", "2026-03-01T00:00:00+00:00"),
              LessThan("order_ts", "2026-03-02T00:00:00+00:00"))
table = open_catalog().load_table("shop.orders")
print("rows on 1 March before:", table.scan(row_filter=MARCH_1).to_arrow().num_rows)
bad = make_orders(table, 9001, 5, "2026-03-01", 1, seed=99, channel="web")
table.overwrite(bad, overwrite_filter=MARCH_1,
                snapshot_properties={"job": "backfill-2026-03-01"})
print("rows on 1 March after: ", table.scan(row_filter=MARCH_1).to_arrow().num_rows)
print("rows in the table:     ", table.scan().to_arrow().num_rows)
Terminal
python bad_write.py
Expected output
rows on 1 March before: 161
rows on 1 March after:  5
rows in the table:      1544

The rollback script finds the first snapshot that the backfill wrote, takes its parent (the last good snapshot) and calls manage_snapshots().rollback_to_snapshot(). Rollback requires the target to be an ancestor of the current snapshot, which protects you from jumping to an unrelated branch of history by mistake.

Python · rollback.py
"""Step 6b: roll back to the snapshot before the bad backfill."""
from lab import open_catalog, show_history

table = open_catalog().load_table("shop.orders")
bad = [s for s in table.snapshots()
       if s.summary.get("job") == "backfill-2026-03-01"]
print("snapshots written by the backfill:",
      [s.summary.operation.value for s in bad])
good_id = bad[0].parent_snapshot_id
table.manage_snapshots().rollback_to_snapshot(good_id).commit()
print("rows in the table:", table.scan().to_arrow().num_rows)
show_history(table)
Terminal
python rollback.py
Expected output
snapshots written by the backfill: ['delete', 'append']
rows in the table: 1700
seq  operation  added-files  total-files  total-rows
  1  append              1            1         400
  2  append              2            3         800
  3  append              1            4        1200
  4  append              1            5        1400
  5  append              2            7        1450
  6  append              2            9        1500
  7  append              2           11        1550
  8  append              2           13        1600
  9  append              2           15        1650
 10* append              2           17        1700
 11  delete              0           11        1539
 12  append              1           12        1544

The overwrite produced two snapshots in one commit: a delete (sequence 11) that dropped the six files of 1 March, and an append (12) with the five bad rows. After the rollback, snapshot 10 is current again and the table has 1,700 rows. Nothing was restored from a backup: the rollback wrote a new metadata file that names an older snapshot as current. Deleting the bad file by hand instead would be wrong, because snapshot 12's metadata still lists it. Snapshots 11 and 12 stay until you expire them, so set_current_snapshot() could even move forward to them again.

08. Step 7: Compact the small files of one partition

The usual compaction tool is the Spark procedure rewrite_data_files, for example CALL catalog.system.rewrite_data_files(table => 'shop.orders', where => ...). It bin-packs or sorts small files into files near the target size (512 MB by default) and commits a snapshot with the operation replace, which tells readers that the rows did not change. PyIceberg 0.12 has no such call; its maintenance API offers only snapshot expiry, as the script checks first.

The honest local equivalent reads every row of one partition and writes them back with overwrite() in one transaction whose filter matches exactly that partition. Unlike Spark's procedure, it records a delete plus an append, so incremental readers see a data change; it does not check for files that another writer added in the meantime; and it holds the partition in memory, so it suits modest partitions only.

Python · compact.py
"""Step 7: compact the files of the 2 March partition into one file."""
import pyarrow.compute as pc
from pyiceberg.expressions import And, GreaterThanOrEqual, LessThan

from lab import open_catalog, show_history

catalog = open_catalog()
table = catalog.load_table("shop.orders")
print("PyIceberg has rewrite_data_files:",
      hasattr(table.maintenance, "rewrite_data_files"))
print("maintenance offers:",
      [m for m in dir(table.maintenance)
       if not m.startswith("_") and callable(getattr(table.maintenance, m))])

DAY = And(GreaterThanOrEqual("order_ts", "2026-03-02T00:00:00+00:00"),
          LessThan("order_ts", "2026-03-03T00:00:00+00:00"))


def partition_state(tbl, snapshot_id=None):
    scan = tbl.scan(row_filter=DAY, snapshot_id=snapshot_id)
    data = scan.to_arrow()
    total = round(pc.sum(data["amount"]).as_py(), 2)
    return len(list(scan.plan_files())), data.num_rows, total


before_id = table.current_snapshot().snapshot_id
commits_before = len(table.metadata.metadata_log)
print("before: files, rows, sum(amount) =", partition_state(table))

rows = table.scan(row_filter=DAY).to_arrow().sort_by("order_id")
with table.transaction() as tx:
    tx.overwrite(rows, overwrite_filter=DAY,
                 snapshot_properties={"job": "compact-2026-03-02"})

table = catalog.load_table("shop.orders")
print("after:  files, rows, sum(amount) =", partition_state(table))
print("metadata commits for the compaction:",
      len(table.metadata.metadata_log) - commits_before)
print("old snapshot still readable:", partition_state(table, before_id))
show_history(table)
Terminal
python compact.py
Expected output
PyIceberg has rewrite_data_files: False
maintenance offers: ['expire_snapshots']
before: files, rows, sum(amount) = (6, 139, 14147.96)
after:  files, rows, sum(amount) = (1, 139, 14147.96)
metadata commits for the compaction: 1
old snapshot still readable: (6, 139, 14147.96)
seq  operation  added-files  total-files  total-rows
  1  append              1            1         400
  2  append              2            3         800
  3  append              1            4        1200
  4  append              1            5        1400
  5  append              2            7        1450
  6  append              2            9        1500
  7  append              2           11        1550
  8  append              2           13        1600
  9  append              2           15        1650
 10  append              2           17        1700
 11  delete              0           11        1539
 12  append              1           12        1544
 13  delete              0           11        1561
 14* append              1           12        1700

The six small files of 2 March became one, with the same row count and total, in a single metadata commit, so no reader could see the partition empty or doubled. The new snapshots got sequence numbers 13 and 14, after the abandoned backfill, because sequence numbers only move forward. Time travel to the snapshot before the compaction still finds the six old files, which is why compaction alone frees no storage. To reclaim it, expire old snapshots with table.maintenance.expire_snapshots() once you no longer need them, and remove orphan files left by failed jobs (for example with Spark's remove_orphan_files).

09. Troubleshooting

10. Check your understanding

Practice check · 3 questions

Evolution, time travel and compaction

Use what you saw in the lab. Each question has one best answer.

Q1. After the lab, you rename `channel` to `sales_channel` with `update_schema().rename_column(...)`. What happens to the data files and to `len(table.snapshots())`?
Q2. Right after `rollback.py`, a colleague asks where the five bad rows of snapshot 12 went. What is true?
Q3. A teammate writes a compaction for 2 March but reads the rows with `table.scan().to_arrow()` (no filter) and passes them to `overwrite(rows, overwrite_filter=DAY)`. What does the table contain afterwards?
Practice only: not graded, not saved, not evidence.

11. Apply it: stretch tasks

These tasks complete the practice project of this skill:

  1. Your dataset as an Iceberg table. Load the Parquet version of your practice dataset into a table partitioned by day() of its main timestamp, in at least three commits. Run your three practice queries with table.scan(row_filter=...) and record files planned, rows and run time.
  2. Evolve without rewriting. Add a column and change the partition spec, and prove with inspect.files() that no existing file changed.
  3. Time travel and rollback. Make a deliberately bad write, query the snapshot before it, roll back, and record the history before and after.
  4. Expire. Run table.maintenance.expire_snapshots().older_than(...) with a cut-off after the bad write, then check which snapshots you can still read.

12. Review prompt

Without looking back:

  1. Why did adding a column create no snapshot and rewrite no file, and what do old files return for the new column?
  2. After the spec changed from month to day, how did planning handle the old and the new files for one query?
  3. What exactly did rollback_to_snapshot() change, and what did it leave in place?
  4. How does the PyIceberg compaction in step 7 differ from Spark's rewrite_data_files, and why does compaction alone not free storage?

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