About Skills Projects Blog Contact View my CV ↗ Español
Apache Iceberg hands-on: the lakehouse you can actually query

Apache Iceberg hands-on: the lakehouse you can actually query

A hands-on Apache Iceberg guide: catalogs, tables, partitions, time travel, and schema evolution with PyIceberg and DuckDB, no Spark required.

By Omar Flores
Table of Contents

It is nine in the morning and two people are staring at the same S3 bucket. One sees yesterday’s sales. The other sees the day before, because their Spark job has not finished writing. A third team opened a CSV exported last week and swears the total matches. Nobody is lying: the bucket has no single idea of which version of the data is valid.

Apache Iceberg solves that problem. It is not a query engine or a warehouse. It is a table layer that turns a pile of Parquet files into something with transactions, schema, and versions. It lets Spark, Trino, DuckDB, and PyIceberg read the same data without each tool inventing its own truth.

The guide is hands-on. We will create a table, read it without Spark, partition it, travel to the past, and evolve the schema. We will also look at when Iceberg is the wrong answer.


The lake that became a junkyard

An object bucket is great at storing bytes. It knows nothing about tables. If you write sales/2026-12-05/part-000.parquet, the storage layer will not tell you whether that file is complete, whether it replaces another one, or whether it belongs to the same version as its neighbors.

Teams compensate with conventions: folders by date, a _SUCCESS marker, a JSON manifest, a script that deletes old files. That works until two jobs write at the same time, a backfill leaves orphan files behind, or someone renames a column. Then the lake becomes archaeology.

Iceberg adds a transactional layer on top. Every write produces a new immutable snapshot. Readers see a complete snapshot, not a half-written mix of files. And the catalog decides which snapshot is current.

What an Iceberg table is, in three layers

An Iceberg table is not a folder of Parquet. It is a metadata tree:

  • Metadata JSON: schema, partition spec, snapshots, and the pointer to the current snapshot.
  • Manifest list: the manifests that make up a snapshot.
  • Manifest files: Avro files listing data files and statistics such as min/max values, null counts, and row counts.
  • Data files: ordinary Parquet.

The catalog stores the location of the current metadata JSON. When a writer commits, it creates new metadata and moves the pointer atomically. Old files are left untouched.

warehouse/analytics/events/
  metadata/
    00000-abc.metadata.json
    00001-def.metadata.json
    snap-123.avro          # manifest list
  data/
    event_time_day=2026-12-05/
      part-000.parquet
      part-001.parquet

That is the decoupling: storage holds the bytes, the catalog defines the table, and the compute engine comes and goes without migrating data. Spark writes, DuckDB reads, Trino queries: the same snapshot.

That design explains the three properties people love: consistent reads, time travel, and evolution without rewriting data. It also explains the cost: more metadata to maintain.

Catalogs: who decides which version is valid

The catalog is the piece many teams underestimate. It is not a directory; it is the service that resolves names, applies permissions, and coordinates commits. When two writers race, the catalog lets one win and the other retry against the latest version.

There are several families:

  • REST: the interoperable standard. It connects any engine to any catalog that speaks the protocol.
  • AWS Glue: common on AWS, with native integration to data services.
  • Hive Metastore: frequent in existing installations, though it carries operational baggage.
  • JDBC: a relational database as the source of truth; useful for small teams.
  • Nessie: adds Git-style branches and commits, handy for test environments.
  • HadoopCatalog: filesystem-based. Fine for a lab, risky for production with concurrent writers.

PyIceberg also ships a SQL catalog backed by SQLite or PostgreSQL. It is perfect for learning and integration tests. Do not treat it as a company-wide catalog without thinking about concurrency and backups.

First contact: a table with PyIceberg

We will set up a local warehouse. No Spark, no Java, no external service.

pip install "pyiceberg[sql-sqlite,pyarrow,duckdb]"
mkdir -p /tmp/warehouse

The SQL catalog stores metadata in SQLite and data on the filesystem. It is the setup the official documentation uses for demos.

from datetime import datetime
from decimal import Decimal

from pyiceberg.catalog import load_catalog
import pyarrow as pa

warehouse = "/tmp/warehouse"
catalog = load_catalog(
    "local",
    type="sql",
    uri=f"sqlite:///{warehouse}/catalog.db",
    warehouse=f"file://{warehouse}",
)

catalog.create_namespace_if_not_exists("analytics")

schema = pa.schema([
    pa.field("event_id", pa.int64(), nullable=False),
    pa.field("user_id", pa.int32()),
    pa.field("event_time", pa.timestamp("us"), nullable=False),
    pa.field("event_type", pa.string()),
    pa.field("amount", pa.decimal128(12, 2)),
])

table = catalog.create_table_if_not_exists("analytics.events", schema=schema)

batch = pa.table({
    "event_id": [1, 2, 3],
    "user_id": [10, 10, 11],
    "event_time": [
        datetime(2026, 12, 5, 9, 0),
        datetime(2026, 12, 5, 9, 5),
        datetime(2026, 12, 5, 9, 10),
    ],
    "event_type": ["view", "purchase", "view"],
    "amount": [None, Decimal("49.90"), None],
}, schema=schema)

table.append(batch)
print(table.scan().to_arrow().num_rows)

create_table_if_not_exists creates the table and registers the first metadata. append writes a new Parquet file and commits a snapshot. scan().to_arrow() reads the current snapshot and returns an Arrow table.

Notice what you did not do: create folders, write a manifest, or delete anything. Iceberg handled it.

Reading without Spark: DuckDB as a window into the lakehouse

DuckDB has an Iceberg extension that installs and loads itself on first use. The most direct path is to give it the metadata PyIceberg already knows.

import duckdb

metadata = table.metadata_location.removeprefix("file://")
duckdb.sql(f"""
    SELECT event_type, count(*) AS events, sum(amount) AS total
    FROM iceberg_scan('{metadata}')
    GROUP BY event_type
    ORDER BY events DESC
""").show()

Direct reads are read-only. DuckDB uses manifest statistics to skip files that cannot match the filter, and reads only the columns you request.

Writing requires a catalog. With a REST catalog, the flow looks like this:

CREATE SECRET iceberg_secret (
    TYPE iceberg,
    CLIENT_ID 'admin',
    CLIENT_SECRET 'password',
    OAUTH2_SERVER_URI 'https://catalog.example.com/v1/oauth/tokens'
);

ATTACH 'warehouse' AS lake (
    TYPE iceberg,
    SECRET iceberg_secret,
    URI 'https://catalog.example.com'
);

SELECT * FROM lake.analytics.events LIMIT 10;

Once attached, it behaves like any other database: INSERT, UPDATE, DELETE, MERGE INTO, and ALTER TABLE work with regular SQL. That is the lakehouse promise: one table, many engines.

Invisible partitions and an evolving layout

In Hive, partitioning means creating a physical event_date column and remembering to write it on every insert. In Iceberg, the partition is a hidden transformation. You declare day(event_time) and the engine computes the value.

CREATE TABLE lake.analytics.events (
    event_id BIGINT,
    user_id INT,
    event_time TIMESTAMP,
    event_type VARCHAR,
    amount DECIMAL(12, 2)
)
PARTITIONED BY (day(event_time), bucket(16, user_id));

Available transforms include identity, year, month, day, hour, bucket(n, column), and truncate(w, column). Queries still filter by event_time; you do not need to know the physical partition.

The interesting part comes when volume changes. You can change the layout without rewriting the table:

ALTER TABLE lake.analytics.events
SET PARTITIONED BY (month(event_time));

Old files keep their partition spec. New files use the new one. Iceberg plans each layout separately and prunes files in both. It is a metadata operation, not a terabyte migration.

The practical limit is the usual one: do not partition by user_id when you have millions of users. That creates millions of tiny files. Partition by time and, if needed, use bucket with a bounded number.

Time travel: the undo button that actually exists

Every commit creates a snapshot. That lets you read yesterday’s exact state, compare versions, or investigate a bad backfill.

table = catalog.load_table("analytics.events")
snapshots = list(table.snapshots())

for snap in snapshots:
    print(snap.snapshot_id, snap.timestamp_ms)

if len(snapshots) > 1:
    previous = snapshots[-2].snapshot_id
    old = table.scan(snapshot_id=previous).to_arrow()
    print(old.num_rows)

In DuckDB, with the table attached to the catalog:

SELECT count(*) FROM lake.analytics.events
AT (VERSION => 1234567890123456789);

SELECT count(*) FROM lake.analytics.events
AT (TIMESTAMP => TIMESTAMP '2026-12-04 18:00:00');

Time travel is not a backup. Snapshots expire, and files no longer referenced by any snapshot can be deleted. If you need disaster recovery, combine snapshot retention with bucket versioning or external copies. Iceberg gives you history, not immortality.

Schema evolution without breaking readers

Adding a column, renaming it, or widening a type are metadata operations. Iceberg identifies each column by a stable ID, not by position or name. That avoids the classic disaster of reading a new column with values from another one.

ALTER TABLE lake.analytics.events ADD COLUMN country VARCHAR;
ALTER TABLE lake.analytics.events RENAME COLUMN amount TO total_amount;
ALTER TABLE lake.analytics.events ALTER COLUMN user_id TYPE BIGINT;

Old files are not rewritten. When read, Iceberg projects the current schema: columns that did not exist return NULL or their default value. Dropped columns disappear from queries, but their bytes remain in files until maintenance cleans them up.

PyIceberg can also evolve through table.update_schema(). The union_by_name operation is useful when a DataFrame brings new columns:

with table.update_schema() as update:
    update.union_by_name(batch.schema)

The rule you must not break: do not reuse column names for different semantics. Iceberg protects you from many mistakes, but it cannot guess what you meant.

Writing in production: append, overwrite, and MERGE

append adds data. In PyIceberg, overwrite replaces the entire table, not a partition: use it carefully. For point updates, the pattern is MERGE INTO.

MERGE INTO lake.analytics.events AS target
USING (
    VALUES
      (1, 10, TIMESTAMP '2026-12-05 09:00:00', 'purchase', 49.90),
      (4, 12, TIMESTAMP '2026-12-05 09:15:00', 'view', NULL)
) AS source(event_id, user_id, event_time, event_type, total_amount)
ON target.event_id = source.event_id
WHEN MATCHED THEN UPDATE
WHEN NOT MATCHED THEN INSERT;

DuckDB writes positional deletes with merge-on-read semantics; compact afterward.

In Spark the pattern is the same, with the advantage of writing whole partitions in parallel. Two production rules: never run overlapping overwrite operations on the same table, and do not mistake the catalog for a lock service. Iceberg uses optimistic concurrency; on conflict, the writer must retry.

Watch your file sizes, too. A streaming job that commits every minute produces thousands of tiny Parquet files. That is fixed by compaction, not by reading faster.

Performance: what actually moves the needle

Iceberg does not make S3 fast by itself. It lets the engine know which files to avoid. Performance comes from four things: fewer files, better statistics, partitions aligned with queries, and fewer columns read.

Symptom Action
Thousands of small files Compact with rewrite_data_files
Slow planning Rewrite manifests
Huge metadata Expire old snapshots
Queries scan everything Review partitions and filters
High S3 costs Larger files and fewer commits

In Spark, maintenance actions are catalog procedures:

CALL lake.system.rewrite_data_files(
  table => 'analytics.events',
  strategy => 'binpack',
  options => map('target-file-size-bytes', '134217728')
);

CALL lake.system.rewrite_manifests('analytics.events');

CALL lake.system.expire_snapshots(
  table => 'analytics.events',
  older_than => TIMESTAMP '2026-11-01 00:00:00',
  retain_last => 10
);

Do not run these every hour by reflex. Measure files, planning time, and bytes read; compaction competes with queries for I/O.

Iceberg vs Delta vs Hudi: the honest decision

All three formats solve the same core problem: adding transactions and metadata to files in object storage. The difference is the ecosystem and the workload.

Format Strong at Typical friction Use it if
Iceberg Cross-engine interoperability, evolving partitions, REST catalog You need a catalog and maintenance Multiple engines read the same table
Delta Lake Deep Spark and Databricks integration, mature transaction log The ecosystem pulls toward Databricks Your home is Spark/Databricks
Hudi Upserts, incremental ingestion, copy-on-write and merge-on-read More operational complexity, Spark-heavy Your pipeline is CDC with frequent changes

Iceberg is not faster than Delta or Hudi by decree. The right choice depends on who reads, how often rows change, and how much operations you can sustain. If you have one Spark job and nobody else queries the table, any of the three works; pick the one your team already knows how to run.

Common mistakes, when NOT to use Iceberg, and a checklist

The mistakes I see most:

  • Treating the bucket like a database and writing files outside the catalog.
  • Never compacting, then wondering why queries are slow.
  • Partitioning by a very high-cardinality column.
  • Running HadoopCatalog in production with multiple writers.
  • Expiring snapshots without knowing which jobs depend on them.
  • Expecting uniqueness constraints, foreign keys, or OLTP transactions.
  • Assuming overwrite replaces only the partition you are looking at.

Do not use Iceberg if your problem is OLTP, if you need single-row updates at millisecond latency, if the dataset fits on one machine and is not shared by several engines, or if nobody will own compaction and retention. Iceberg is infrastructure; someone has to operate it.

Checklist for the first deployment:

  • A real catalog, not a shared folder.
  • Time-based partitions, not user-based ones.
  • Reasonable file sizes before scaling.
  • A concurrent-write and retry test.
  • A snapshot expiration policy.
  • Scheduled, measured compaction.
  • Data access through catalog permissions, not loose credentials.
  • A recovery plan that does not rely on time travel alone.

Iceberg does not turn S3 into a database. It gives your files back something the lake had lost: one version of the truth that every engine can read.