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
On this page
- Goal and setup
- Step 1: Create a table partitioned by month
- Step 2: Load the table in three commits
- Step 3: Add a column without rewriting files
- Step 4: Change the partition spec from month to day
- Step 5: Time-travel to earlier snapshots
- Step 6: Recover from a bad write with a rollback
- Step 7: Compact the small files of one partition
- Troubleshooting
- Check your understanding
- Apply it: stretch tasks
- Review prompt
Lessons of File & Table Formats
- Row vs Columnar: Inside Avro and Parquet Concept · 25 min
- Lab: The Same Data as CSV, Avro and Parquet Lab · 25 min
- Object Storage, Partitioning and the Small-Files Problem Worked example · 30 min
- Table Formats: Snapshots, Manifests and Atomic Commits Concept · 25 min
- Lab: Evolve, Time-Travel and Compact an Iceberg Table Lab · 30 min
- Check: Review a Storage Layout Knowledge check · 6 questions
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.
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 tablemkdir 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.1Every 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.
"""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.
"""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()))python create_table.pyformat 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: 0The 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.
"""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)python load.pyseq 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 rowsEach 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.
"""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)python add_column.pynew 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: TrueAdding 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.
"""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")python change_spec.pyspec 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.
"""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}")python time_travel.pyseq 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.
"""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)python bad_write.pyrows on 1 March before: 161
rows on 1 March after: 5
rows in the table: 1544The 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.
"""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)python rollback.pysnapshots 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 1544The 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.
"""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)python compact.pyPyIceberg 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 1700The 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
11. Apply it: stretch tasks
These tasks complete the practice project of this skill:
- 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 withtable.scan(row_filter=...)and record files planned, rows and run time. - Evolve without rewriting. Add a column and change the partition spec, and prove with
inspect.files()that no existing file changed. - Time travel and rollback. Make a deliberately bad write, query the snapshot before it, roll back, and record the history before and after.
- 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:
- Why did adding a column create no snapshot and rewrite no file, and what do old files return for the new column?
- After the spec changed from month to day, how did planning handle the old and the new files for one query?
- What exactly did
rollback_to_snapshot()change, and what did it leave in place? - How does the PyIceberg compaction in step 7 differ from Spark's
rewrite_data_files, and why does compaction alone not free storage?
References
- PyIceberg: Python API (tables, schema and partition evolution, snapshots, maintenance)
- Apache Iceberg: Evolution
- Apache Iceberg: Partitioning
- Apache Iceberg: Spark procedures (rewrite_data_files, rollback_to_snapshot)
- Apache Iceberg: Maintenance
- Apache Iceberg Table Spec (snapshot operations, sequence numbers)
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.