Lab: One Lakehouse Table, Two Query Engines
Create an Iceberg table in a local catalog, query it with PyIceberg and with DuckDB and get the same answer, then see why every engine must find the table through the catalog: a stale metadata pointer and an uncommitted file both give wrong results otherwise.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Create the table and commit two batches
- Step 2: Engine 1, PyIceberg and PyArrow
- Step 3: Look inside the catalog
- Step 4: Engine 2, DuckDB
- Step 5: Commit again and read through an old pointer
- Step 6: An uncommitted file in the table folder
- Step 7: When this architecture fits
- Check your understanding
- Apply it
- Review prompt
Lessons of Warehouses & Lakehouses
- Inside a Cloud Warehouse: Storage, Compute, Billing Concept · 25 min
- Lakes, Warehouses and Lakehouses Side by Side Concept · 25 min
- Raw, Clean, Modeled: Designing the Layers Worked example · 25 min
- Lab: One Lakehouse Table, Two Query Engines Lab · 30 min
- Lab: Pruning, Clustering and Cost per Query Lab · 25 min
- Check: Platform Choice and Tuning Review Knowledge check · 8 questions
What you will learn
- Compare warehouse, data lake and lakehouse architectures (catalog plus open table formats on object storage) and choose one for stated requirements.
01. Goal and setup
The promise of a lakehouse is one copy of the data that many engines can use: Spark for heavy jobs, a SQL engine for analysts, Python for data science. Two things make that possible. An open table format, here Apache Iceberg, describes which Parquet files belong to the table in metadata files that any engine can read. A catalog maps a table name such as shop.orders to the current metadata file and changes that mapping atomically on every commit.
In this lab you build both on your laptop. A SQLite file plays the catalog, a local folder plays object storage, PyIceberg writes and reads the table, and DuckDB reads it independently. Then you break the rules on purpose to see what the catalog protects you from. If snapshots and manifests are new to you, read Table Formats: Snapshots, Manifests and Atomic Commits first.
You need Python 3.10 or later and an internet connection the first time, because DuckDB downloads its iceberg extension. The lab was tested with Python 3.12, PyIceberg 0.12.0 (with pyiceberg-core 0.10.1) and DuckDB 1.5.6.
mkdir lakehouse-lab && cd lakehouse-lab
python3 -m venv .venv && source .venv/bin/activate
pip install "pyiceberg[sql-sqlite,pyarrow,pyiceberg-core]==0.12.0" "duckdb==1.5.6"02. Step 1: Create the table and commit two batches
SqlCatalog stores the catalog in catalog.db and puts table files under warehouse/. The table is partitioned by the day of order_date, so each day gets its own folder of data files. Each append() writes Parquet files and then commits a new snapshot, a complete description of the table at that moment. The data is generated with arithmetic, so your numbers will match the ones below.
"""Create an Iceberg table in a local catalog and commit two batches of orders."""
from datetime import date, timedelta
from pathlib import Path
import pyarrow as pa
from pyiceberg.catalog.sql import SqlCatalog
from pyiceberg.partitioning import PartitionField, PartitionSpec
from pyiceberg.schema import Schema
from pyiceberg.transforms import DayTransform
from pyiceberg.types import DateType, DecimalType, LongType, NestedField, StringType
Path("warehouse").mkdir(exist_ok=True)
catalog = SqlCatalog("lab", uri="sqlite:///catalog.db",
warehouse=f"file://{Path('warehouse').resolve()}")
catalog.create_namespace_if_not_exists("shop")
schema = Schema(
NestedField(1, "order_id", LongType(), required=True),
NestedField(2, "order_date", DateType(), required=True),
NestedField(3, "country", StringType(), required=True),
NestedField(4, "amount", DecimalType(10, 2), required=True),
)
spec = PartitionSpec(PartitionField(2, 1000, DayTransform(), "order_date_day"))
table = catalog.create_table("shop.orders", schema, partition_spec=spec)
def batch(first_id, days):
rows = [(first_id + i, date(2026, 11, 1) + timedelta(i % days),
["DE", "FR", "VN", "BR"][i % 4], (i * 37 % 9000) / 100)
for i in range(400)]
ids, dates, countries, amounts = zip(*rows)
return pa.table({"order_id": ids, "order_date": dates, "country": countries,
"amount": pa.array(amounts).cast(pa.decimal128(10, 2))},
schema=table.schema().as_arrow())
table.append(batch(1, days=2)) # commit 1: 1 and 2 November
table.append(batch(401, days=3)) # commit 2: 1 to 3 November
for snap in table.snapshots():
print("snapshot", snap.sequence_number, snap.summary["operation"].value,
"added-records", snap.summary["added-records"])
print("metadata:", Path(table.metadata_location).name[:6] + "...metadata.json")python create_table.py
find warehouse/shop/orders/data -name '*.parquet' | cut -d/ -f5 | sort | uniq -c
ls warehouse/shop/orders/metadata | wc -lsnapshot 1 append added-records 400
snapshot 2 append added-records 400
metadata: 00002-...metadata.json
2 order_date_day=2026-11-01
2 order_date_day=2026-11-02
1 order_date_day=2026-11-03
7Five data files: commit 1 wrote one file for each of 1 and 2 November, commit 2 one for each of 1, 2 and 3 November. The seven metadata files are three *.metadata.json versions (empty table, after commit 1, after commit 2), two manifest lists (snap-*.avro, one per snapshot) and two manifests that list the data files with their row counts and column statistics.
03. Step 2: Engine 1, PyIceberg and PyArrow
PyIceberg asks the catalog for the table, reads its metadata, and plans the scan: it uses the partition values and file statistics in the manifests to choose only the files that can contain matching rows. PyArrow then reads those files and computes revenue per country from 2 November onwards.
"""Engine 1: PyIceberg plans the scan, PyArrow computes the answer."""
import pyarrow.compute as pc
from pyiceberg.catalog.sql import SqlCatalog
catalog = SqlCatalog("lab", uri="sqlite:///catalog.db")
table = catalog.load_table("shop.orders")
scan = table.scan(row_filter="order_date >= '2026-11-02'",
selected_fields=("country", "amount"))
print("files planned:", len(list(scan.plan_files())))
result = (scan.to_arrow()
.group_by("country")
.aggregate([("amount", "count"), ("amount", "sum")])
.sort_by("country"))
for row in result.to_pylist():
print(f"{row['country']} orders={row['amount_count']:>3}"
f" revenue={row['amount_sum']}")python engine_pyiceberg.pyfiles planned: 3
BR orders=166 revenue=6495.42
DE orders= 66 revenue=2495.16
FR orders=167 revenue=6421.79
VN orders= 67 revenue=2642.42Three of the five files were planned: the two 1 November files were skipped without being opened, because the manifest records each file's partition value.
04. Step 3: Look inside the catalog
A catalog sounds abstract, but this one is a single SQLite table. Each row maps a namespace and table name to a metadata_location. Production catalogs (an Iceberg REST catalog service, AWS Glue, Hive Metastore, or the catalog built into a managed platform) add access control and an API, but they keep the same core job: hold the pointer, and replace it only if nobody else replaced it first. That check-and-replace is what makes a commit atomic, and it lets two writers notice when they conflict instead of silently overwriting each other. The script below prints the pointer in a shortened form and saves the full path in current_pointer.txt, because DuckDB cannot talk to this SQLite catalog directly.
"""The catalog is a small database: table name -> current metadata file."""
import sqlite3
con = sqlite3.connect("catalog.db")
row = con.execute("SELECT table_namespace, table_name, metadata_location"
" FROM iceberg_tables").fetchone()
namespace, name, location = row
print(f"{namespace}.{name} -> .../{location.rsplit('/', 2)[-2]}/"
f"{location.rsplit('/', 1)[-1][:6]}...metadata.json")
open("current_pointer.txt", "w").write(location)python where_is_the_table.pyshop.orders -> .../metadata/00002-...metadata.json05. Step 4: Engine 2, DuckDB
DuckDB has its own Iceberg reader, written in C++ and sharing no code with PyIceberg. iceberg_scan() takes the metadata file, follows it to the manifest list, the manifests and the data files, and runs ordinary SQL on the result. The first run downloads the extension.
"""Engine 2: DuckDB reads the same table through its Iceberg extension."""
import sys
import duckdb
location = open(sys.argv[1] if len(sys.argv) > 1 else "current_pointer.txt").read()
con = duckdb.connect()
con.execute("INSTALL iceberg")
con.execute("LOAD iceberg")
print(con.sql(f"""
SELECT country, count(*) AS orders, sum(amount) AS revenue
FROM iceberg_scan('{location}')
WHERE order_date >= DATE '2026-11-02'
GROUP BY country ORDER BY country"""))python engine_duckdb.py┌─────────┬────────┬───────────────┐
│ country │ orders │ revenue │
│ varchar │ int64 │ decimal(38,2) │
├─────────┼────────┼───────────────┤
│ BR │ 166 │ 6495.42 │
│ DE │ 66 │ 2495.16 │
│ FR │ 167 │ 6421.79 │
│ VN │ 67 │ 2642.42 │
└─────────┴────────┴───────────────┘Two independent engines, one set of files, the same answer to the cent, and nobody exported or copied anything. With a warehouse that stores data in its own internal format, the second engine would usually need an export job and a second copy of the data that can drift out of date.
06. Step 5: Commit again and read through an old pointer
Keep a copy of the current pointer, as a dashboard might if someone pasted the metadata path into its configuration. Then let PyIceberg commit 100 orders for 4 November, and run the DuckDB query once with the old pointer and once with the new one.
"""Engine 1 writes again: 100 orders for 4 November become snapshot 3."""
from datetime import date
from decimal import Decimal
import pyarrow as pa
from pyiceberg.catalog.sql import SqlCatalog
table = SqlCatalog("lab", uri="sqlite:///catalog.db").load_table("shop.orders")
rows = pa.table({
"order_id": list(range(801, 901)),
"order_date": [date(2026, 11, 4)] * 100,
"country": ["VN"] * 100,
"amount": pa.array([Decimal("25.00")] * 100, pa.decimal128(10, 2)),
}, schema=table.schema().as_arrow())
table.append(rows)
print("current snapshot:", table.current_snapshot().sequence_number)cp current_pointer.txt old_pointer.txt
python commit_more.py
python where_is_the_table.py
python engine_duckdb.py old_pointer.txt
python engine_duckdb.pycurrent snapshot: 3
shop.orders -> .../metadata/00003-...metadata.json┌─────────┬────────┬───────────────┐
│ country │ orders │ revenue │
│ varchar │ int64 │ decimal(38,2) │
├─────────┼────────┼───────────────┤
│ BR │ 166 │ 6495.42 │
│ DE │ 66 │ 2495.16 │
│ FR │ 167 │ 6421.79 │
│ VN │ 67 │ 2642.42 │
└─────────┴────────┴───────────────┘┌─────────┬────────┬───────────────┐
│ country │ orders │ revenue │
│ varchar │ int64 │ decimal(38,2) │
├─────────┼────────┼───────────────┤
│ BR │ 166 │ 6495.42 │
│ DE │ 66 │ 2495.16 │
│ FR │ 167 │ 6421.79 │
│ VN │ 167 │ 5142.42 │
└─────────┴────────┴───────────────┘The old metadata file still exists and still describes snapshot 2, so the query through it runs without any error and returns 67 VN orders: a silently stale answer. Through the current pointer, VN has the 100 new orders. Metadata files are immutable, which is what makes time travel possible, so an engine that wants the latest data must ask the catalog every time. In production, configure every engine with the catalog (for example DuckDB can ATTACH an Iceberg REST catalog), never with a metadata path.
07. Step 6: An uncommitted file in the table folder
Now simulate a writer that crashed after writing a data file but before committing. The file sits in the 3 November folder, but no manifest lists it. Count the table twice: by globbing every Parquet file in the folder, as a plain data lake reader would, and through the Iceberg metadata.
"""A job writes a Parquet file into the table folder but crashes before committing."""
from datetime import date
from decimal import Decimal
import pyarrow as pa
import pyarrow.parquet as pq
stray = pa.table({"order_id": [9001, 9002], "order_date": [date(2026, 11, 3)] * 2,
"country": ["DE", "DE"],
"amount": pa.array([Decimal("500.00")] * 2, pa.decimal128(10, 2))})
path = "warehouse/shop/orders/data/order_date_day=2026-11-03/uncommitted.parquet"
pq.write_table(stray, path)
print("wrote", path)"""Count rows by globbing the folder, and through the table metadata."""
import duckdb
location = open("current_pointer.txt").read()
con = duckdb.connect()
con.execute("LOAD iceberg")
folder = con.sql("SELECT count(*), sum(amount) FROM read_parquet("
"'warehouse/shop/orders/data/*/*.parquet')").fetchone()
table = con.sql("SELECT count(*), sum(amount) FROM iceberg_scan("
f"'{location}')").fetchone()
print(f"glob over the folder: {folder[0]} rows, total {folder[1]}")
print(f"Iceberg table: {table[0]} rows, total {table[1]}")python stray_file.py
python count_both_ways.pywrote warehouse/shop/orders/data/order_date_day=2026-11-03/uncommitted.parquet
glob over the folder: 902 rows, total 34472.00
Iceberg table: 900 rows, total 33472.00The glob counts two orders that were never committed and adds €1,000 of revenue. The Iceberg read is correct, because a file belongs to the table only if committed metadata lists it. This is the main difference between a data lake and a lakehouse: in a lake, the folder is the table, so half-finished writes and leftover files leak into results; in a lakehouse, the metadata is the table. Iceberg maintenance (remove_orphan_files in Spark) deletes such files later.
08. Step 7: When this architecture fits
You have now seen what a lakehouse gives you: several engines on one copy, atomic commits, and storage you control. It also gives you work: you choose and run the catalog, keep engine versions compatible with the table format, and schedule maintenance such as compaction and snapshot expiry. A managed warehouse hides all of that, at the price of one vendor's engine and storage format. Choose the lakehouse when several engines must share the data or when open storage is a requirement; choose the warehouse when one SQL engine is enough and nobody wants to run a platform.
09. Check your understanding
10. Apply it
For the skill practice, load your fact table into an Iceberg table like this one and into a warehouse (a free tier, or DuckDB as a local stand-in). Run the same fixed query set on both and record the answers, run time and files or bytes read. Add a third engine if you can, for example Polars with pl.scan_iceberg(table), and confirm it returns identical results.
11. Review prompt
Without looking back, explain: what the catalog stores and why every commit goes through it; how two engines with no shared code can return the same answer; why an old metadata path gives a stale answer without an error; and why globbing the table folder is not the same as reading the table.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.