200+ Apache Iceberg Interview Questions and Answers (2026)
200+ Apache Iceberg interview questions and answers for data engineer, senior engineer and architect roles: fundamentals, table design, commits, maintenance, streaming, catalogs, migration and recovery, with Spark SQL.
- Five ideas to remember
- Run the examples
- Fundamentals
- Table design and schema evolution
- Writes, commits and concurrency
- Maintenance and performance
- Streaming, change data capture and ingestion
- Catalogs, engines and integrations
- Migration, recovery, governance and operations
- Internals, comparisons and architecture
- References
- Trademarks
TL;DR
An Iceberg table is read through a metadata root that references snapshots, manifests, and data or delete files; a catalog publishes the current metadata location through its commit mechanism.**
- Queries can avoid scanning irrelevant files — manifests carry file-level metadata that engines can use during planning and pruning.
- A table update does not mean rewriting the whole table — a commit can publish new metadata that references newly written files alongside existing files.
- Readers can reason about committed table states — snapshots identify table states, enabling time travel and snapshot-based operations when the required metadata and files remain available.
- Schema changes need not rewrite every data file — Iceberg tracks schema and field identity in metadata, allowing supported schema evolution to be represented separately from the physical layout of older files.
- Partitioning can evolve independently of the logical table schema — partition specs and transforms are metadata, so a table can move to a new layout while retaining files written under older specs.
- Concurrent writers need conflict handling — optimistic concurrency allows writers to prepare changes independently, but a commit must still validate against the table state and handle conflicts.
- Deletes are not all the same operation — position deletes, equality deletes, and deletion vectors have different representations and read implications; format version and engine support matter.
- A successful write is not the end of the job — orphan cleanup, snapshot expiration, file compaction, and manifest rewriting must be managed without removing resources still needed by readers or other workflows.
- Cross-engine compatibility is a deployment concern — Iceberg defines table metadata and file semantics, while Spark, Flink, and Trino provide different execution paths, integrations, and support matrices.
This guide has 200+ Apache Iceberg interview questions with worked answers for data engineer, senior engineer and architect roles. Interviews usually go beyond “what is a snapshot” and ask what happens when two jobs commit at once, why storage keeps growing after a compaction, or how you would undo a bad load at 2 a.m. The questions run from basics to internals, so start at part 1 or jump to the part that matches the role.
From the catalog pointer down to the data and delete files.
| Part | Questions | Level | What it covers |
|---|---|---|---|
| Fundamentals | 1-25 | Beginner | What Iceberg is, the metadata tree, everyday SQL |
| Table design and schema evolution | 26-46 | Senior | Planning, statistics, partitioning, sorting, evolution |
| Writes, commits and concurrency | 47-73 | Senior, then architect | Row-level writes, delete files, format versions, the commit protocol, conflicts |
| Maintenance and performance | 74-106 | Senior | Compaction, cleanup, slow queries, tuning, monitoring |
| Streaming, change data capture and ingestion | 107-125 | Senior, then architect | Spark and Flink sinks, exactly-once, CDC, late data, ingestion design |
| Catalogs, engines and integrations | 126-152 | Architect | Catalog choice and safety, engines, security, cloud platforms |
| Migration, recovery, governance and operations | 153-185 | Architect | Migrations, restores, audits, erasure, cost, platform rules |
| Internals, comparisons and architecture | 186-200 | PMC and architect | Spec details, the Java code, other formats, large-scale design |
Five ideas to remember
Most answers follow from these five.
| When a question is about | Start from | Say this |
|---|---|---|
| Reading and speed | The list of files | Skip manifests, then files, then row groups |
| Concurrency and failure | The pointer swap | Readers see the old version or the new one |
| Updates and deletes | Files never change | Rewrite now (copy-on-write) or mark now and rewrite later (merge-on-read) |
| Storage and cleanup | Snapshots hold references | Compaction adds files; only expiry releases old ones |
| Evolution | IDs and specs | Old files keep what they were written with |
Four maintenance jobs, four different targets.
Interviewers often ask for defaults. These are the table property and procedure defaults in Iceberg 1.12.0.
| Think of | Default | Setting |
|---|---|---|
| Target data file size | 512 MB | write.target-file-size-bytes |
| Parquet row group | 128 MB | write.parquet.row-group-size-bytes |
| Read split size | 128 MB | read.split.target-size |
| Minimum cost of opening a file | 4 MB | read.split.open-file-cost |
| Commit retries | 4 | commit.retry.num-retries |
| Manifests before merging | 100 | commit.manifest.min-count-to-merge |
| Manifest target size | 8 MB | commit.manifest.target-size-bytes |
| Columns with automatic metrics | 100 | write.metadata.metrics.max-inferred-column-defaults |
| Metrics mode | truncate(16) |
write.metadata.metrics.default |
| Snapshot age kept by expiry | 5 days | history.expire.max-snapshot-age-ms |
| Snapshots always kept | 1 | history.expire.min-snapshots-to-keep |
| Old metadata files tracked | 100 | write.metadata.previous-versions-max |
| Orphan file age | 3 days | older_than of remove_orphan_files |
| Files that trigger compaction of a group | 5 | min-input-files |
| Row-level isolation | serializable | write.merge.isolation-level and its siblings |
Run the examples
The SQL in the answers runs on Spark 3.5.9 with Iceberg 1.12.0 and a Java 17
JVM. Start a shell with a local Hadoop catalog named demo:
spark-sql \
--packages org.apache.iceberg:iceberg-spark-runtime-3.5_2.12:1.12.0 \
--conf spark.sql.extensions=org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions \
--conf spark.serializer=org.apache.spark.serializer.KryoSerializer \
--conf spark.sql.catalog.demo=org.apache.iceberg.spark.SparkCatalog \
--conf spark.sql.catalog.demo.type=hadoop \
--conf spark.sql.catalog.demo.warehouse=file:///tmp/iceberg-interview \
--conf spark.sql.session.timeZone=UTC
The two Python examples need a pyspark shell started with the same
--packages and --conf options. The Java program, in question 192,
compiles against the same Iceberg runtime jar and Spark’s own jars.
Then create the table the examples use. A Hadoop catalog is fine for a laptop and wrong for shared storage, for the reason given in question 133.
CREATE NAMESPACE IF NOT EXISTS demo.shop;
DROP TABLE IF EXISTS demo.shop.orders PURGE;
CREATE TABLE demo.shop.orders (
order_id BIGINT,
customer_id BIGINT,
amount DECIMAL(10,2),
status STRING,
order_ts TIMESTAMP
) USING iceberg
PARTITIONED BY (days(order_ts));
INSERT INTO demo.shop.orders
SELECT id, id % 100, CAST(id % 500 AS DECIMAL(10,2)), 'NEW',
TIMESTAMP '2026-11-01 00:00:00' + make_interval(0, 0, 0, CAST(id % 5 AS INT))
FROM range(1000);
Fundamentals
1. What is Apache Iceberg?
Apache Iceberg is an open table format for large analytic datasets. It is a specification, plus libraries that engines embed, that says which data files and metadata files make up a table and how that set may safely change. It was created at Netflix and is now a top-level Apache project.
To see why that is needed, think about what a pile of Parquet files in object storage can’t tell you. Which of them belong to the table right now? Did the last job finish, or did it die halfway? What happens if two jobs write at once? Iceberg answers these by writing its own metadata next to the data, recording the live files, the columns, the partitioning and the deleted rows. There is no Iceberg server in the data path: Spark, Flink or Trino read that metadata themselves, and a catalog remembers which metadata file is current.
The statements below create a table, add two rows and read them back.
DROP TABLE IF EXISTS demo.shop.hello PURGE;
CREATE TABLE demo.shop.hello (id BIGINT, name STRING) USING iceberg;
INSERT INTO demo.shop.hello VALUES (1, 'first'), (2, 'second');
SELECT * FROM demo.shop.hello ORDER BY id;
The table’s directory then looks like this, with long file names shortened. The two data files come from two write tasks.
hello/data/00000-...-00001.parquet row files
hello/data/00001-...-00001.parquet
hello/metadata/v1.metadata.json the empty table
hello/metadata/v2.metadata.json the table after the insert
hello/metadata/snap-...avro manifest list of that snapshot
hello/metadata/...-m0.avro manifest naming the two data files
hello/metadata/version-hint.text Hadoop catalog: current version
That extra metadata is what gives plain files atomic commits, snapshot isolation, schema and partition evolution, row-level DELETE, UPDATE and MERGE, and a history you can query or roll back to. It doesn’t maintain itself, though. Compacting small files and expiring old snapshots remain jobs you schedule.
2. What are the key features of Apache Iceberg?
Iceberg’s key features are ACID transactions, schema evolution, partition evolution, hidden partitioning, time travel, support for many engines and metadata that makes planning efficient.
| Feature | What it gives you | Everyday example |
|---|---|---|
| ACID transactions | Readers see all of a commit or none; concurrent writers are checked | A report never reads a half-finished load |
| Schema evolution | Add, rename or drop columns without rewriting data | Renaming a column on a huge table is instant |
| Partition evolution | Change the layout for new data | Move from monthly to daily partitions as volume grows |
| Hidden partitioning | Filter on ordinary columns | No separate date column to maintain |
| Time travel and rollback | Query or restore earlier snapshots | Undo a bad load |
| Many engines | Spark, Flink, Trino, Presto, Hive and others share tables | Ingest with Flink, query with Trino |
| Metadata-based planning | Skip data without listing directories | Fast planning on very large tables |
Most of the table can be shown on one tiny table. It is partitioned by day through a transform on an ordinary column, gets a column added and another renamed, and is tagged after the first load:
CREATE TABLE demo.kf.orders (order_id BIGINT, amount DECIMAL(10,2), order_ts TIMESTAMP)
USING iceberg PARTITIONED BY (days(order_ts));
INSERT INTO demo.kf.orders VALUES
(1, 10.00, TIMESTAMP '2026-11-01 09:00:00'), (2, 20.00, TIMESTAMP '2026-11-02 09:00:00');
ALTER TABLE demo.kf.orders CREATE TAG after_load;
ALTER TABLE demo.kf.orders ADD COLUMN channel STRING;
ALTER TABLE demo.kf.orders RENAME COLUMN amount TO total;
INSERT INTO demo.kf.orders VALUES (3, 30.00, TIMESTAMP '2026-11-03 09:00:00', 'web');
SELECT * FROM demo.kf.orders ORDER BY order_id;
SELECT * FROM demo.kf.orders VERSION AS OF 'after_load' ORDER BY order_id;
current table as of the tag
order_id total order_ts channel order_id amount order_ts
1 10.00 2026-11-01 09:00:00 NULL 1 10.00 2026-11-01 09:00:00
2 20.00 2026-11-02 09:00:00 NULL 2 20.00 2026-11-02 09:00:00
3 30.00 2026-11-03 09:00:00 web
Five features show up in that output. The schema changes ran instantly and rewrote nothing, the old rows read NULL for the new column, the tag returns the table with its old column name and without channel, a filter on order_ts needed no extra partition column, and each statement was one atomic commit.
Row-level UPDATE, DELETE and MERGE, plus branches and tags, round out the set.
Two caveats make an answer sound experienced. Every feature needs support from each engine you use, so check before relying on one. And Iceberg doesn’t maintain itself: compaction and snapshot expiry remain jobs you have to run.
3. What problems with Hive tables does Iceberg solve?
A Hive table is a directory, and its partitions are subdirectories. The metastore knows which partitions exist, the file system knows which files they contain, and nothing updates the two as one step. Most of Hive’s familiar problems come from that gap.
The metadata tree that replaces directory listing.
Take a job that rewrites thirty daily partitions. While it runs, some directories hold new files and some hold old ones, and a query that lands in the middle reads a mix. If the job fails, the table stays in that mixed state until someone repairs it. Planning has the same root: to find the files, the engine lists every partition directory it needs, which on object storage means many separate requests.
Iceberg stops treating directories as the table. Each commit records an explicit list of files, called a snapshot, and publishes it by swapping one pointer.
| Problem in Hive | What Iceberg does instead |
|---|---|
| Readers can see a job that has written only some partitions | A commit swaps one pointer, so the whole write appears at once |
| Concurrent writers need user coordination or Hive locks | The catalog rejects a commit built on stale metadata |
| Planning lists every partition directory | Planning reads manifests and skips most of them |
| Queries must filter on a separate partition column | Filters on the real column prune partitions |
| Changing partitioning means rewriting the table | The new layout applies to new data; old data stays readable |
| Renaming a column can make old files read wrongly | Columns are matched by a permanent ID, not by name |
Hive’s transactional tables address part of this, but they are tied to ORC and to Hive’s transaction manager, so other engines support them unevenly. Iceberg’s guarantees come from the table metadata and the catalog, which any engine implementing the specification can use.
4. What is a data lakehouse, and where does Iceberg fit?
A lakehouse runs warehouse-style workloads, with transactions, managed schemas and fast SQL, directly on files in cheap open storage, without copying them into a separate warehouse. Iceberg provides its table layer.
| Warehouse | Plain data lake | Lakehouse | |
|---|---|---|---|
| Storage | Managed by the warehouse | Open files | Open files |
| Guarantees | Strong, mainly for its own engine | Few | Provided by a table format and catalog |
| Engines | Mostly one | Many, loosely coordinated | Many, coordinated through the catalog |
Where the table format sits in a lakehouse.
Iceberg’s share of this stack is specific. It records which files make up each table and how that can change safely. It doesn’t store the bytes, run queries or enforce permissions.
That boundary is worth stating in an interview, because adopting a table format doesn’t produce a good platform by itself. Data modeling, quality checks, access control and maintenance are still needed; without them you have reliably transactional but messy data. Nor does a lakehouse have to replace the warehouse. Many platforms keep one for low-latency, high-concurrency serving and feed it from lakehouse tables.
5. What is the difference between a table format, a file format, a catalog and a query engine?
None of these is the others. The file format (Parquet, ORC, Avro) encodes rows inside one file. The table format defines which files make up a table and how it may change. The catalog resolves a table name to the current metadata. The query engine runs the SQL and reads and writes the data.
| Part | Responsibility | Examples |
|---|---|---|
| File format | How rows are encoded, compressed and laid out inside one file | Parquet, ORC, Avro |
| Table format | The rules for which files make up a table, its schema, partitioning, snapshots and how it may change | Apache Iceberg |
| Catalog | Maps a table name to its current metadata file and swaps that pointer atomically on commit | AWS Glue, Hive Metastore, JDBC catalog, REST catalog |
| Query engine | Parses and plans SQL, filters, joins and aggregates, and reads and writes the files | Apache Spark, Trino, Flink |
Here is how they connect during a query.
SQL application
|
v
Query engine
|
v
Table format library (Iceberg)
|
+--------> Catalog
|
+--------> Object storage
Take SELECT * FROM prod.sales.orders WHERE order_date = '2026-11-01' in Spark. Spark asks the catalog for the table, and the catalog returns the location of the current metadata file. The Iceberg library, which runs inside Spark, reads that metadata and works out which files can match the filter. Spark then reads those files from object storage and does the rest of the work.
The Iceberg library is part of the engine’s process, and the table format is the specification it implements. That is why Spark, Flink and Trino can all use one table: each has its own planner, but all follow the same format.
The usual mix-ups are worth stating. A catalog doesn’t normally execute SQL or read data files. Spark doesn’t define the Iceberg table format; it only implements it. And Iceberg isn’t a catalog either, although the Iceberg project defines the catalog interface and ships several implementations, such as the REST, JDBC and Hive ones.
Iceberg sits between the engine and the files.
Keeping the layers separate lets you change one without touching the others. You can add Trino beside Spark, or move from Hive Metastore to a REST catalog, and the tables stay as they are. It also tells you where to look when something is slow: small row groups are a file format problem, thousands of tiny files are a table maintenance problem, a bad join order belongs to the engine and throttled requests belong to storage. Identify the layer first, because the fix differs in each.
There is no Iceberg server in the data path. Spark, Flink and Trino each embed the Iceberg library and walk the metadata themselves.
6. Which file formats can an Iceberg table use?
Data files and delete files can be Parquet, ORC or Avro. Parquet is the default, set by write.format.default, and new tables compress it with zstd.
The metadata has its own fixed formats. The table metadata file is JSON, so that it is simple to read and inspect. Manifest lists and manifests are Avro, a row-based format that suits planning, which processes one file description after another and needs most of each description.
| Format | Layout | Where it fits |
|---|---|---|
| Parquet | Columnar | The usual choice for analytics, with the widest engine support |
| ORC | Columnar | Estates already built around ORC |
| Avro | Row based | Landing data that is read whole |
The manifest records the format of every file individually, so one table can hold a mix. That happens after migrating a Hive table that used several formats, or after you change the default: old files stay as they are, new files use the new setting, and compaction rewrites files in whatever format is configured when it runs.
The format is chosen per table with a property, and each file records its own format. Two tables with the same rows but different defaults show it in the files metadata table:
CREATE TABLE demo.q.f_orc (id BIGINT, v STRING) USING iceberg
TBLPROPERTIES ('write.format.default' = 'orc');
INSERT INTO demo.q.f_orc VALUES (1, 'a'), (2, 'b');
SELECT file_format, record_count FROM demo.q.f_orc.files;
f_orc ORC (a table created with the property)
f_pq PARQUET (the same insert into a default table)
Files written by Iceberg also carry column IDs, which is how readers map an old file to the current schema after a rename. Imported files without IDs need a name mapping. Don’t assume every feature behaves the same in all three formats. Support varies by engine and reader, so test the exact combination you plan to use, such as deletes on ORC.
7. What is a snapshot?
A snapshot is the complete state of a table at one commit: the exact set of data and delete files that were live at that moment.
Every write adds a new snapshot and leaves earlier ones untouched. A snapshot records a random ID, its parent’s ID, a sequence number, a timestamp, the path to a manifest list and a summary of what changed. The summary names the operation:
| Operation | Meaning |
|---|---|
append |
Files were added |
overwrite |
Data was added and removed |
delete |
Data was removed |
replace |
Files were rewritten, for example by compaction, with unchanged results |
SELECT snapshot_id, operation, committed_at
FROM demo.shop.orders.snapshots
ORDER BY committed_at;
Right after the setup insert there is one row. Your ID and time will differ.
snapshot_id operation committed_at
6573600511505774579 append 2026-11-30 15:28:20.834
A snapshot is a list of references, not a copy of the data. If a table has 10,000 files and a commit adds one, the new snapshot points at the same 10,000 files plus the new one. That is why keeping history is cheap until files get replaced, and why time travel and rollback need no data movement.
Two habits avoid mistakes. Order snapshots by committed_at, never by ID, because IDs are random. And use history when you need to know which snapshot was current at a given time: snapshots lists what exists, while history also records rollbacks.
8. How does Iceberg provide ACID guarantees on object storage?
Iceberg makes every change in two stages: first it writes new files that nobody can see, then it publishes them with a single atomic step in which the catalog moves the table’s pointer from the old metadata file to the new one.
The pointer swap is the only step that makes a write visible.
Say the table is at version 7 with files A and B, and a writer adds file C. Until the swap, every reader follows the pointer to version 7 and sees only A and B: file C exists in storage, but nothing a reader follows mentions it. After the swap to version 8, new queries see all three. There is no moment in between.
That one step carries all four guarantees:
| Property | How the commit provides it |
|---|---|
| Atomicity | The pointer either moves or it doesn’t |
| Consistency | A commit is accepted only against the version it was built on, after checking for conflicting changes |
| Isolation | A query loads one metadata file and reads that snapshot from start to finish |
| Durability | Files are in durable storage before anything references them |
Object storage therefore needs no transactions of its own, because Iceberg never modifies a file in place and never relies on a directory listing. It does need a catalog that can compare and swap the pointer correctly.
Know the boundaries. The guarantee covers one table per commit, so two statements are two commits and a reader can see the state between them. A writer that crashes before the swap leaves orphan files behind. They are harmless to queries, take up space and stay there until remove_orphan_files deletes them. Reads have a limit too: if expire_snapshots removes a snapshot while a slow query is still reading it, that query fails with a missing file, so keep retention longer than your longest query.
9. What is a catalog and why does Iceberg need one?
A catalog maps a table name to the location of its current metadata file, and replaces that location atomically when a writer commits.
You might wonder why storage can’t do this alone. A table’s metadata directory holds many metadata files, one for each change, and some may come from commits that failed. Nothing in a listing says reliably which one is current. Something has to hold that single fact and update it safely.
A commit is therefore a conditional request: “replace metadata file X with Y, but only if X is still current”. Imagine two writers that both start from version 7. The first asks to move from 7 to 8 and succeeds. The second asks the same and is refused, because the current version is now 8. It reloads, checks that its change is still valid and tries to commit version 9. Without the condition, the second writer would silently erase the first writer’s work.
The catalog returns the location of the current metadata file and swaps the pointer on commit.
Depending on the product, a catalog also manages namespaces, creates and renames tables, enforces access control, issues storage credentials or stores views. Rows don’t pass through it; engines read and write files in storage directly.
Because correctness rests on that swap, two tables that look identical in storage can offer different guarantees under different catalogs. Availability matters too. If the catalog is down, queries and commits can’t resolve the table even though every file is intact, except in a session that still holds a cached copy. Plan for its uptime and back it up.
10. Describe the layers of Iceberg metadata.
Iceberg metadata is a tree. The catalog points to a metadata JSON file, which lists snapshots. Each snapshot has a manifest list, the manifest list names manifests, and the manifests name the data and delete files.
The three tiers of a table.
| Layer | What it holds |
|---|---|
| Catalog entry | The location of the current metadata file |
| Metadata file | Table UUID, every schema and partition spec used so far, sort orders, properties, snapshot and metadata logs, branches and tags |
| Manifest list, one per snapshot | One row per manifest, with partition ranges and counts |
| Manifest | One row per file, with partition values and column statistics |
| Data and delete files | The rows, and which rows are gone |
After the setup insert, the orders table has one of almost everything above the data layer: two metadata files (the empty table and the table after the insert), one manifest list, one manifest and five data files, one for each day. The query shows the chain of metadata files.
SELECT timestamp, file, latest_snapshot_id
FROM demo.shop.orders.metadata_log_entries
ORDER BY timestamp DESC LIMIT 3;
file latest_snapshot_id
.../v2.metadata.json 6573600511505774579
.../v1.metadata.json NULL
v1 has no snapshot because creating a table writes no data. Everything below the catalog is immutable. A commit that creates a snapshot writes a new metadata file and manifest list, while a change such as adding a column writes only a new metadata file.
The levels pay off in two ways. Each one summarises the level below, so planning can skip whole branches, and a commit reuses unchanged branches instead of rewriting them. The cost is that old metadata files, manifest lists and manifests accumulate, and different settings and procedures clean up each kind.
11. What is the difference between a manifest and a manifest list?
A manifest lists files, one entry per data file or delete file. A manifest list belongs to a single snapshot and lists the manifests that make up that snapshot.
| Manifest list | Manifest | |
|---|---|---|
| One per | Snapshot | Group of files, shared between snapshots |
| One row per | Manifest | Data file or delete file |
| Records | Partition value ranges, file and row counts, sequence numbers | Partition values, record count, size, per-column counts and bounds |
SELECT path, partition_spec_id, added_data_files_count, existing_data_files_count
FROM demo.shop.orders.manifests;
The setup insert produced a single manifest that added five files: added_data_files_count is 5 and existing_data_files_count is 0. Its entry in the manifest list says the partition values range from 2026-11-01 to 2026-11-05.
The reuse is visible in the all_manifests metadata table. Take a table with two inserts followed by a copy-on-write UPDATE, which gives three snapshots:
SELECT reference_snapshot_id, substring_index(path, '/', -1) AS manifest
FROM demo.b5.t.all_manifests ORDER BY reference_snapshot_id, path;
snapshot manifests its manifest list names
8451... f091...-m0
6231... 78ef...-m0 f091...-m0 <- f091...-m0 is reused, not rewritten
4161... 47b7...-m0 47b7...-m1 f091...-m0
The manifest f091...-m0 is named by all three snapshots, and each snapshot has its own manifest list. The UPDATE wrote two new manifests, one for the file it added and one recording the file it removed. They took the place of 78ef...-m0, the manifest that held the replaced file, while the oldest manifest was left untouched.
Planning uses the two levels in order. For a query on 2026-12-15, the range in the manifest list proves this manifest can’t match, so it is never opened. For a query on 2026-11-02, the range overlaps, so the manifest is read and its per-file partition values narrow the five files to one.
The split also keeps commits cheap. Adding one file writes one small manifest and a new manifest list that points at it and at the existing manifests. Each file entry is marked added, existing or deleted, which is how an incremental read finds what a commit added. A manifest covers one partition spec and holds either data files or delete files, never both. Pruning weakens when every manifest spans many partitions, and rewrite_manifests regroups the entries.
12. What is immutable data in Iceberg?
Iceberg never edits a data file or a metadata file once it is written. To change a table, a writer creates new files and publishes a new snapshot that references them.
Take an UPDATE that changes rows held in one data file, with copy-on-write.
Before the UPDATE: snapshot 101 -> A.parquet, B.parquet
After the UPDATE: snapshot 102 -> A-new.parquet, B.parquet
The writer reads A.parquet, writes A-new.parquet with the changed rows and leaves A.parquet where it is. B.parquet doesn’t change, so both snapshots share it. The commit then swaps the catalog pointer to a metadata file that lists snapshot 102.
This is easy to check. A table has three data files, and a copy-on-write UPDATE changes the row in one of them. Only that file is replaced:
before after
00000-0-31dc...-00001.parquet 00000-0-31dc...-00001.parquet (unchanged)
00000-2-761a...-00001.parquet <- holds id = 3 00000-15-ce8f...-00001.parquet (the rewritten file)
00001-1-31dc...-00001.parquet 00001-1-31dc...-00001.parquet (unchanged)
snapshots: append, append, overwrite
The old file 00000-2-761a... is no longer in the current snapshot, but it is still on disk and still readable through the earlier snapshots.
Immutability is what makes the rest of the design safe:
- A reader that started on snapshot 101 keeps reading
A.parquet, because nothing deletes or rewrites it. New readers see snapshot 102. - A writer that crashes before the swap leaves new files that no snapshot mentions, so the table doesn’t change.
- Time travel and rollback work because the old files are still there.
- Concurrent commits can be checked against each other, because each one is a fixed list of files.
Merge-on-read follows the same rule. It writes a small delete file next to the untouched data file, instead of a replacement for it.
The cost is that files pile up. A.parquet stays in storage until no retained snapshot references it, so you have to run expire_snapshots to remove old snapshots and their files, and remove_orphan_files for the leftovers of failed writes. Compaction also writes new files rather than editing old ones.
13. What is hidden partitioning?
Hidden partitioning means the table declares its partition as a transform of an ordinary column, such as days(order_ts), and Iceberg derives the partition value itself. Writers supply no extra column, and readers filter on the real one.
Compare that with Hive. There you add a column such as dt, every writer has to compute it correctly, and every reader has to remember to filter on it. A query with WHERE order_ts >= ... but no dt filter returns the right answer after scanning the entire table, which is easy to miss until the bill arrives.
EXPLAIN SELECT order_id, amount FROM demo.shop.orders
WHERE order_ts >= TIMESTAMP '2026-11-02 00:00:00'
AND order_ts < TIMESTAMP '2026-11-03 00:00:00';
The query mentions only order_ts, and the filter reaches the Iceberg scan:
BatchScan demo.shop.orders[...]
[filters=order_ts IS NOT NULL, order_ts >= 1793577600000000,
order_ts < 1793664000000000, ...]
The two numbers are the literal timestamps in microseconds. During planning, Iceberg projects that row filter onto each partition transform, turning a range on order_ts into a range on its day, and skips files from other days. The projection is inclusive: it may keep a partition that turns out to hold no matching row, but never drops one that does. A bucket transform can use equality and IN filters but not ranges, because hashing destroys order.
Because queries never mention the partition layout, you can later change it, say from days to hours, without rewriting any SQL. One caution: wrapping the column in an arbitrary function can stop the filter from being pushed down, so compare the raw column with literal bounds.
14. Which partition transforms does Iceberg support?
A partition transform turns a column value into a partition value. The specification defines identity, year, month, day, hour, bucket, truncate and void.
A transform maps a value to its partition.
| Transform | Result | Example | Typical use |
|---|---|---|---|
| identity | The value itself | region |
Low-cardinality columns |
| year, month, day, hour | Time unit since 1970 | days(order_ts) |
Time-series data |
| bucket[N] | Hash of the value modulo N | bucket(16, customer_id) |
High-cardinality keys, joins |
| truncate[W] | Value cut to width W | truncate(4, sku) |
String prefixes, numeric ranges |
| void | Always null | Removed fields in version 1 tables |
Spark exposes the transforms as functions, which lets you see what a value turns into.
SELECT demo.system.bucket(16, 34L) AS bucket_of_34,
demo.system.truncate(100, 250L) AS truncate_number,
demo.system.truncate(4, 'iceberg') AS truncate_string;
bucket_of_34 truncate_number truncate_string
3 200 iceb
bucket applies a 32-bit Murmur3 hash and takes the result modulo N. The specification fixes the hash, so every engine puts key 34 in the same one of 16 buckets, which is what lets bucketed tables be joined bucket by bucket. truncate(100, ...) rounds a number down to a multiple of 100, grouping 200 to 299 together, and truncate(4, ...) keeps the first four characters of a string.
Choose the transform by how queries filter. Date ranges suit time transforms, and lookups on a key with millions of values suit bucket. You can combine fields, as in days(order_ts), bucket(4, customer_id), but the partition count multiplies, so check that each combination still receives enough data to fill reasonably sized files. Partitioning on a raw timestamp does the opposite and creates a tiny file for each distinct value. Changing N in a bucket applies only to new data.
15. What schema changes can you make without rewriting data?
You can add, drop, rename and reorder columns, including fields inside structs, widen some types and make a required column optional. All of these change metadata only.
ALTER TABLE demo.shop.orders ADD COLUMN channel STRING;
ALTER TABLE demo.shop.orders RENAME COLUMN channel TO sales_channel;
ALTER TABLE demo.shop.orders ALTER COLUMN amount TYPE DECIMAL(12,2);
ALTER TABLE demo.shop.orders DROP COLUMN sales_channel;
After these four statements the table still has the same single snapshot and the same five data files. Each statement wrote a new metadata file with a new schema, and no data file was opened.
Old files stay readable because every column has a permanent ID that data files record. When Iceberg reads a file written under an earlier schema, it matches columns by ID:
| Change since the file was written | What a query sees |
|---|---|
| Column renamed | The same values under the new name |
| Column dropped | The values are ignored |
| Column added | Null, or the declared default on format version 3 |
| Type widened | Old values read as the wider type |
Some changes are refused because old data couldn’t satisfy them. A column can’t become required by default, since old files may contain nulls. A type can’t be narrowed, since values may not fit. A partition source column can’t be dropped while a partition spec uses it.
Cheap for the table doesn’t mean harmless for its users. A rename or drop still breaks queries, views and downstream jobs that use the old name. Spark can also add columns during a write when write.spark.accept-any-schema and mergeSchema are set. Enable that deliberately, or a misspelt field name quietly becomes a new column.
16. What is time travel?
Time travel means querying a table as it was at an earlier snapshot, chosen by snapshot ID, timestamp, branch or tag.
ALTER TABLE demo.shop.orders CREATE TAG initial_load;
SELECT count(*) FROM demo.shop.orders VERSION AS OF 'initial_load';
SELECT count(*) FROM demo.shop.orders TIMESTAMP AS OF current_timestamp();
Both counts are 1000 at this point, because nothing has changed since the tag was created. After later updates and deletes, the tagged query still returns the original 1000 rows.
Nothing is reconstructed or replayed. For a timestamp, Iceberg looks up in the snapshot log which snapshot was current at that moment, then plans the query from that snapshot’s manifest list. The old files are still in storage, so the read costs about what it cost back then.
Which schema you get depends on how you ask. A read by snapshot ID, timestamp or tag uses the schema that belonged to that snapshot. A read of a branch uses the table’s current schema.
Time travel is useful for comparing results before and after a job, reproducing a training dataset and recovering rows deleted by mistake. It lasts only as long as the snapshot does. Once expiry removes a snapshot, that point in history is gone, which is why important states get a tag. It also isn’t a backup: if the files or the bucket are lost, the history goes with them.
17. What are copy-on-write and merge-on-read?
Data files are never edited in place, so changing or deleting a row needs another method. Copy-on-write rewrites each affected file without the old row. Merge-on-read leaves the file alone and records separately which rows are gone.
The same delete under both modes.
Take a table with 1,000 rows in one data file and delete 100 of them. The two modes leave very different results behind:
After DELETE |
Copy-on-write | Merge-on-read, version 2 |
|---|---|---|
| Snapshot operation | overwrite |
delete |
| Data files | A new file with 900 rows | The original file, still with 1,000 rows |
| Delete files | None | One position delete file with 100 entries |
| A query returns | 900 rows | 900 rows, after applying the deletes |
The answer is identical; the work moved. Copy-on-write paid at write time to rewrite 900 surviving rows, and readers pay nothing extra. Merge-on-read wrote only the 100 positions, and every later scan has to apply them. On version 3 tables, deletion vectors take the place of position delete files.
The mode is set separately for each command with write.delete.mode, write.update.mode and write.merge.mode, all defaulting to copy-on-write. Appends only add files in either mode.
Choose by how often data changes. Rare changes with heavy reading favour copy-on-write. Frequent small changes, such as change data capture, favour merge-on-read. The second choice doesn’t remove the rewriting cost, it postpones it to compaction, so a merge-on-read table with no compaction job gets slower with every write.
18. Does Iceberg support UPDATE, DELETE and MERGE?
Yes. Iceberg supports UPDATE, DELETE and MERGE in engines that implement them. Spark needs the Iceberg SQL extensions.
UPDATE demo.shop.orders SET status = 'PAID' WHERE order_id < 100;
DELETE FROM demo.shop.orders WHERE order_id BETWEEN 100 AND 109;
MERGE INTO demo.shop.orders t
USING (SELECT 1L AS order_id, 'SHIPPED' AS status) s
ON t.order_id = s.order_id
WHEN MATCHED THEN UPDATE SET t.status = s.status;
Each statement commits one snapshot. The snapshot summaries show how much work each one did on this copy-on-write table:
statement operation files removed / added total rows
UPDATE 100 rows overwrite 5 / 5 1000
DELETE 10 rows overwrite 5 / 5 990
MERGE 1 matching row overwrite 1 / 1 990
Deleting just 10 rows rewrote all five files, because those rows were spread across all five days and copy-on-write replaces every file holding a match. The MERGE touched one row, so only one file was replaced.
For a row-level change, Spark scans the target to find affected files, joins them with the source for a MERGE, writes either replacement files or delete markers plus new rows, and commits everything together. A DELETE that matches whole files, such as an entire partition, can be completed in metadata alone.
Iceberg has no primary key index, so a MERGE is a real join. Put partition predicates in the ON clause to limit what is scanned and to reduce conflicts with other writers. The source also needs attention: if two source rows match one target row, the statement fails, while two source rows with a new key are both inserted.
19. What happens when you run an INSERT?
An insert writes the data files first, then the metadata that describes them, and finally asks the catalog to make that metadata current. Nothing is visible until the last step.
Rows become visible at the catalog swap.
The work is split between the cluster and the driver. Executors write the data files, grouping rows by partition after applying the transforms, and report each file’s path and column statistics. The driver turns those reports into the manifest, manifest list and metadata file, then commits. The setup insert of 1,000 rows over five days produced exactly five data files, one manifest, one manifest list and a second metadata file.
Two things can go wrong. If the job fails before step 5, readers see nothing new, and the files already written become orphans. If another writer commits first, the swap is refused. An append can’t conflict logically with other changes to the data, so the driver rebuilds the metadata on the new base and retries without rewriting any data files.
Every insert is a commit and a new snapshot, however small. A loop of single-row inserts creates a data file, a manifest, a manifest list and a metadata file on every pass, and the table soon spends more effort on metadata than on rows. Batch your writes.
20. Where does Iceberg store a table's files?
By default a table keeps its files under one table location: data and delete files in a data directory, and metadata files, manifest lists and manifests in a metadata directory.
<table location>/
data/
order_ts_day=2026-11-01/00000-...parquet
metadata/
00001-<uuid>.metadata.json or v1.metadata.json (Hadoop catalog)
snap-<snapshot>-...avro manifest lists
<uuid>-m0.avro manifests
Here is what a real Hadoop-catalog table directory contains after an insert and an update. Hadoop-specific names are marked, and the .crc checksum files that the local file system adds are left out:
data/
00000-0-<uuid>-0-00001.parquet
00000-8-<uuid>-0-00001.parquet <- written by the update
00001-1-<uuid>-0-00001.parquet
metadata/
v1.metadata.json v2.metadata.json v3.metadata.json (one per commit)
version-hint.text (Hadoop catalog only)
snap-<snapshot id>-<uuid>.avro (manifest lists)
<uuid>-m0.avro <uuid>-m1.avro (manifests)
Three commits left three metadata.json files. The older ones stay until metadata cleanup is enabled.
The layout looks like Hive’s, but it is only a convention. Readers never infer anything from a directory name: partition values come from manifests, and every file is recorded with its full path. Files can therefore live elsewhere. Imported files stay where they were, the object storage layout spreads new files under hashed prefixes, and write.data.path or write.metadata.path redirect new ones. To find the current metadata file, ask the catalog or query metadata_log_entries; the directory may also hold old, uncommitted and orphaned files.
Full paths have a consequence. Through format version 3 they are absolute, so copying a table’s directory to another bucket doesn’t move the table, because the metadata still points at the old place. rewrite_table_path prepares metadata for a new prefix. And never point two tables at one location, or orphan removal for one can delete the other’s files.
21. Why does Iceberg not need to list directories?
Iceberg never needs to list directories because its manifests already name every file in a snapshot. Planning reads metadata instead of asking storage what exists.
In a directory-based table, finding the files for a query means at least one listing request per partition. Object stores return listings in pages, so the cost grows with both partitions and files. A table with three years of hourly partitions has more than 26,000 directories to list for a full scan, before a single row is read.
Iceberg reads one manifest list, then only the manifests that might match. Those manifests already hold each file’s path, size and column statistics, so file footers don’t have to be opened just to decide what to skip.
Two ways to find the files of a table.
What a manifest already knows is visible in the files metadata table. Here is a table of 30 rows partitioned by day, with three data files:
SELECT substring_index(file_path, '/', -1) AS file, partition.order_ts_day AS day,
record_count AS rows, readable_metrics.amount.lower_bound AS min_amount,
readable_metrics.amount.upper_bound AS max_amount
FROM demo.ls.orders.files ORDER BY day;
file day rows min_amount max_amount
00000-...-00003.parquet 2026-11-01 10 0 27
00000-...-00001.parquet 2026-11-02 10 1 28
00000-...-00002.parquet 2026-11-03 10 2 29
Take a query for 2 November with amount > 28. The partition value keeps only the second file, and its upper bound of 28 rules that file out, so no data file is opened and nothing was listed. The Spark plan shows both predicates pushed into the BatchScan: order_ts >= 1793577600000000, order_ts < 1793664000000000, amount > 28.
| Directory listing | Iceberg manifests | |
|---|---|---|
| How files are found | Ask storage what is there | Read what was committed |
| Cost grows with | Partitions and files | Manifests that match the filter |
| Half-written files | May appear | Never listed |
| Pruning statistics | In each file footer | Already in the manifest |
The correctness gain matters as much as the speed. A listing can’t tell a finished file from one still being written or left behind by a failed job. A manifest contains only committed files.
Listing hasn’t disappeared completely: remove_orphan_files lists storage to find files that metadata doesn’t mention, which is why it is expensive. What you watch in normal operation is metadata growth, visible in the manifests and files tables.
22. What are metadata tables?
Metadata tables are read-only tables that expose Iceberg’s own metadata through ordinary SQL. You address them as a suffix on the table name.
| Tables | What they show |
|---|---|
files, data_files, delete_files |
Live files with sizes and statistics |
partitions |
Rows and files per partition |
manifests |
How planning metadata is organised |
snapshots, history |
What changed, and which snapshot was current when |
refs |
Branches and tags |
metadata_log_entries |
Earlier metadata files |
SELECT file_path, record_count, file_size_in_bytes FROM demo.shop.orders.files;
SELECT * FROM demo.shop.orders.history;
SELECT partition, file_count, record_count FROM demo.shop.orders.partitions;
SELECT name, type FROM demo.shop.orders.refs;
After the statements in question 18, files shows five data files of 198 rows each, 990 in total, history has four rows and refs lists two names:
name type
initial_load TAG
main BRANCH
These tables are the first place to look when something is wrong. Many files with a low record_count point to a small file problem, rows in delete_files show delete build-up, and history explains why a table suddenly looks like last week’s. Since they are ordinary queries, you can schedule them and alert on average file size, delete file count or snapshot age.
The file and manifest tables describe the current snapshot. Their all_ variants cover every snapshot and can list a file more than once, so count distinct paths. Several metadata tables also support time travel, which shows how an earlier layout looked.
23. How do you roll a table back?
Call a procedure that makes an earlier snapshot current again. No data is rewritten, because the earlier files are still there.
DELETE FROM demo.shop.orders WHERE status = 'PAID';
CALL demo.system.set_current_snapshot(table => 'shop.orders', ref => 'initial_load');
SELECT count(*) FROM demo.shop.orders;
The delete takes the table from 990 rows to 891. The procedure then points main at the snapshot tagged initial_load, and the count is 1000 again, so the earlier update, delete and merge are undone along with this delete.
history shows what happened. The original snapshot appears a second time, and the abandoned snapshots are no longer ancestors of the current one. Only the last part of each ID is shown.
snapshot_id is_current_ancestor
...4579 true the setup insert
...2022 false UPDATE
...6548 false DELETE
...1376 false MERGE
...9247 false DELETE of PAID rows
...4579 true rolled back to the insert
| Procedure | What it does |
|---|---|
rollback_to_snapshot |
Moves back to a snapshot ID that is an ancestor of the current one |
rollback_to_timestamp |
Moves back to the ancestor that was current at a given time |
set_current_snapshot |
Points at any snapshot or reference |
cherrypick_snapshot |
Applies one snapshot’s changes as a new commit |
The newer snapshots stay in metadata until expiry removes them, and schema or property changes aren’t undone. Remember that a rollback discards every later commit on the branch, good ones included, and consumers that already processed the removed data aren’t told. To undo one bad commit while keeping later work, repair forward instead: read the correct rows from the snapshot before it with time travel and merge them into the current table.
24. What is the difference between DROP TABLE and DROP TABLE PURGE?
In Spark, DROP TABLE ... PURGE asks for the table’s data and metadata files to be deleted. What a plain DROP TABLE leaves behind depends on the catalog.
| Setup | Plain DROP TABLE in Spark |
|---|---|
| Hive, REST and similar service catalogs | Typically removes only the catalog entry and keeps the files |
| Hadoop catalog | Deletes the directory, even without PURGE |
The difference follows from where the table lives. A service catalog has an entry separate from the files, so it can forget the name and leave the data. You can then bring the table back by passing its latest metadata file to register_table. In a Hadoop catalog the directory is the table, so dropping one removes the other. Dropping the demo.shop.hello table from question 1 without PURGE deletes its directory.
A short run on a Hadoop catalog confirms the second row of the table. The table directory holds data and metadata, and a plain DROP TABLE with no PURGE removes the whole directory:
before: ['data', 'metadata']
after plain DROP: directory exists = False
The behaviour also differs by engine. Flink’s Iceberg catalog and Trino’s Iceberg connector delete the data on a plain DROP TABLE. Tables created with the snapshot procedure have gc.enabled set to false, so that Iceberg doesn’t delete files they don’t own.
After a purge, recovery depends entirely on storage protection such as object versioning or backups. Some catalogs add soft delete or refuse a purge. Test yours before you rely on a drop either to clean up or to be reversible, restrict who can drop tables and record metadata locations.
25. How does Iceberg compare with Delta Lake and Apache Hudi?
All three provide ACID tables on object storage. They differ in how they record table state: Iceberg uses a tree of snapshots and manifests, Delta Lake an ordered transaction log with checkpoints, and Hudi a timeline of actions over file groups keyed by record.
Iceberg walks a tree from one pointer. Delta Lake replays a log.
| Iceberg | Delta Lake | Hudi | |
|---|---|---|---|
| Table state | Snapshots and manifests | Transaction log with checkpoints | Timeline of instants |
| Commit | Swaps a catalog pointer | Writes the next log entry | Completes an instant on the timeline |
| Strength | Engine neutrality; hidden, evolvable partitioning | Close integration with Spark and Databricks | Record-key index for frequent upserts and incremental pipelines |
Those designs explain the strengths. Iceberg’s specification separates table state from any one engine, which suits platforms where several engines share data. Delta Lake’s log is simple and deeply integrated with Spark. Hudi’s index can find the file holding a record key without joining against the whole table, which matters when updates arrive constantly.
Choose from your engines and workload. List who must read and write, how often rows change and what your platform’s tooling already supports. Iceberg is a weaker fit when the main job is high-rate keyed upserts that a record index handles more cheaply, or when your platform is built around another format. Performance depends on layout and versions, so benchmark your own write pattern and queries. The comparison of the open table formats goes further.
Table design and schema evolution
26. How does Iceberg plan a query?
Query planning narrows the set of files to read in stages, and does all of it from metadata before any data file is opened.
Follow a query for one day against a table partitioned by day.
- Iceberg loads the current metadata file and picks a snapshot.
- It reads that snapshot’s manifest list and skips every manifest whose partition range can’t contain the day.
- It reads the remaining manifests and drops files whose partition value or column bounds rule them out.
- It attaches the delete files that apply to the survivors and splits the work into tasks.
- During the scan, Parquet row group and page statistics skip data inside each file.
Two rounds of pruning happen before any data file is opened.
Each stage is cheaper than the one after it, which is the point. Discarding one manifest in step 2 removes all the files it lists without reading their entries.
Filters are projected onto the partition spec that each manifest was written with, so a table whose partitioning has changed still prunes both old and new files. For very large tables, manifests can be read on the driver or across the cluster, controlled by read.data-planning-mode and read.delete-planning-mode.
Pruning is only as good as the layout. If every file spans the whole range of a column, bounds exclude nothing; if manifests each cover many partitions, none can be skipped; and a filter on a column without statistics reads everything. Don’t assume it worked. Check the pushed filters in the query plan and the number of files read in the Spark UI.
27. What column statistics does Iceberg keep, and what limits them?
For each file and column, Iceberg keeps value counts, null counts, NaN counts, column sizes and lower and upper bounds. What limits them is the metrics mode and, on wide tables, a cap on how many columns are covered.
The bounds are what make file skipping work. If a file’s upper bound for amount is 800, a filter amount > 900 can’t match anything inside, so the file is never opened.
| Metrics mode | What is kept |
|---|---|
none |
Nothing |
counts |
Counts only |
truncate(N) |
Counts, plus bounds cut to N characters; the default is truncate(16) |
full |
Counts and complete bounds |
Truncation saves manifest space for long strings. With the default, a lower bound keeps a 16-character prefix, and a truncated upper bound is rounded up so that it still covers every value in the file. That is safe but can be useless: if the first 16 characters of an identifier are the same in every row, such as a long URL prefix, the bounds of all files look alike and nothing is skipped.
ALTER TABLE demo.shop.orders SET TBLPROPERTIES (
'write.metadata.metrics.column.status' = 'full');
Truncation is easy to see. A string column holds a 52-character value of a and a 36-character alphabet string, written in two files:
SELECT readable_metrics.name.lower_bound AS lo, readable_metrics.name.upper_bound AS hi
FROM demo.b5.s.files;
lo hi
aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaab <- 16 characters, and the upper bound is incremented
abcdefghijklmnop abcdefghijklmnoq
The lower bound is the first 16 characters. The upper bound is those 16 characters with the last one raised by one, so it is still greater than every real value in the file. A truncated bound is slightly looser than the real range, which costs a little pruning and saves manifest space.
Bounds are stored as bytes in a standard single-value encoding, because one manifest schema has to hold values of any column type. On wide tables, metrics are inferred only for the first 100 columns, so a filter on column 150 skips nothing until you set a mode for it.
More statistics prune better but make manifests larger and planning slower, so raise the mode only for columns you filter on. A change affects new files only. And even exact bounds can’t help if every file spans the full range of values, which is a job for sorting.
28. How do you choose a partitioning scheme?
Base the partitioning on the filters your queries use and on how much data lands in each partition. Start coarse, because the spec can evolve later.
| Situation | Usual choice |
|---|---|
| Time-series data | days(ts) |
| A day holds little data | months(ts) |
| Very high volume | hours(ts) |
| Key used for point lookups or joins | bucket(N, key) |
| Column with few values that is always filtered | identity |
| Small table | Possibly no partitioning |
Do the arithmetic before deciding. Suppose a table receives 2 GB a day and files target 512 MB. Daily partitions hold about four full files each, which is healthy. Hourly partitions would hold about 85 MB each, so every file would be far below target. Adding bucket(16, customer_id) to the daily scheme would split 2 GB into 16 pieces of 128 MB, again too small. Cardinalities multiply, and that is easy to forget.
You can see the multiplication on the same 20,000 rows spread over 30 days, written once into a table partitioned by days(ts) and once by hours(ts):
| Table | Partitions | Data files | Average file size |
|---|---|---|---|
days(ts) |
30 | 30 | 3.8 KB |
hours(ts) |
717 | 717 | 1.2 KB |
The data is identical. The hourly table has 24 times as many files and manifest entries, and a query for one day opens 24 partitions instead of one. The sizes here are tiny because the demo is tiny, but the ratio is what carries over to production.
Over-partitioning is the common mistake. It produces tiny files, heavy metadata and many open files per write task, and streaming jobs suffer first. When you need file skipping on a second column, sorting by it often gives that without creating any extra partitions.
Validate the choice against real queries: compare the files each query scans with the files in the table, and use the partitions table to check how evenly data is spread. If the answer is wrong, evolve the spec and let new data follow the better one.
29. One customer produces half of all events. How do you partition?
Partition by time plus a bucket on an evenly distributed key, and sort by customer within files.
The obvious choice, partitioning or bucketing by customer, fails here. All rows of the large customer hash to one value, so half the data lands in one bucket, with one huge write task.
You can measure the problem. Twenty thousand events are written with customer 7 producing half of them, once into a table partitioned by bucket(8, customer) and once by bucket(8, id):
| Partitioning | Largest partition (rows) | Smallest partition (rows) |
|---|---|---|
bucket(8, customer) |
11,360 | 1,040 |
bucket(8, id) |
2,543 | 2,459 |
The hot customer’s rows all hash to one bucket, so one partition holds more than ten times as much as the smallest and one write task does most of the work. Bucketing on the event ID spreads the same rows almost evenly.
partition: days(event_ts), bucket(N, event_id)
sort: customer_id, event_ts
| Element | What it handles |
|---|---|
days(event_ts) |
Retention and time-range queries |
bucket(N, event_id) |
Spreads every customer’s writes evenly, including the large one |
Sort by customer_id |
Filters on other customers skip most files |
Size N by dividing daily data volume by the target file size. At 50 GB a day and 512 MB files, that is about 100 buckets.
Understand what each kind of query gets. Queries for a small customer skip nearly everything, because sorting concentrates that customer’s rows in few files. Queries for the large customer read many files whatever you do, since half the data is theirs. Watch write task sizes too, because a range shuffle on a skewed sort key can still produce uneven tasks that adaptive execution has to split. If this customer’s volume and access pattern are completely different from the rest, give them a separate table and put both behind a view.
30. What is a table sort order, and how does it help?
A table sort order is an ordering declared on the table that writers apply, so that each file covers a narrow range of the sort columns and file skipping starts to work on them.
With narrow ranges per file, a filter can skip most of them.
Column bounds are only useful when files differ. If customers are scattered randomly, every file holds some from the low end and some from the high end, so a filter on one customer must read them all.
ALTER TABLE demo.shop.orders WRITE ORDERED BY customer_id, order_ts;
Narrow ranges per file let a filter skip files.
| Statement | Effect on new writes |
|---|---|
WRITE ORDERED BY |
Range-shuffles data and orders it across tasks and within files |
WRITE LOCALLY ORDERED BY |
Sorts only within each file |
WRITE DISTRIBUTED BY PARTITION |
Controls how rows are grouped, without ordering them |
Here is the effect on 40,000 rows with 1,000 distinct customers, written once to a table with no sort order and once to a table with WRITE ORDERED BY customer, both with a small target file size so that several files are produced:
SELECT 'unsorted' AS t, count(*) AS files,
round(avg(readable_metrics.customer.upper_bound - readable_metrics.customer.lower_bound)) AS avg_range
FROM demo.b5.u.files
UNION ALL
SELECT 'sorted', count(*),
round(avg(readable_metrics.customer.upper_bound - readable_metrics.customer.lower_bound))
FROM demo.b5.o.files;
t files avg_range
unsorted 8 999 <- every file spans customers 0 to 999
sorted 9 110
The sorted table’s files have narrow, almost non-overlapping ranges:
0-124 125-249 250-374 375-499 500-500 501-625 626-750 751-875 876-999
A filter customer = 300 can skip every file in the sorted table except 250-374. In the unsorted table it has to open all eight, because each one might hold customer 300.
Setting the order changes nothing that is already written. To re-cluster existing files, run a compaction with the sort strategy. If queries filter on several independent columns, a Z-order rewrite spreads the benefit across them, giving up some of it on the first column.
Sorting adds a shuffle and a sort to every write, so it pays off when a table is read far more often than it is written. It is also the better tool for high-cardinality columns, which would produce enormous numbers of tiny partitions. See sorting and clustering.
31. What is the difference between partitioning and sorting?
Partitioning decides which files a row is written to. Sorting decides how rows are ordered, which makes the value ranges inside each file narrow.
| Partitioning | Sorting | |
|---|---|---|
| What it controls | Which group of files a row belongs to | The order of rows across tasks and within files |
| How it helps queries | Whole partitions are skipped from their partition values | Files are skipped because their column bounds exclude the filter |
| Best for | Columns that are filtered on often, with a modest number of values | Columns with many distinct values |
| Cost of getting it wrong | Too many small files, or skewed partitions | An extra sort on every write |
CREATE TABLE demo.shop.events (
event_id BIGINT, customer_id BIGINT, event_ts TIMESTAMP, payload STRING
) USING iceberg
PARTITIONED BY (days(event_ts));
ALTER TABLE demo.shop.events WRITE ORDERED BY customer_id;
Here a query for one day opens only that day’s files. Inside the day, sorting by customer_id means each file covers a small range of customers, so a query for one customer skips most of the day’s files.
The two work together, and each covers what the other can’t. Partitioning on customer_id would create an enormous number of tiny partitions; sorting by it costs nothing in file count. Sorting by event_ts alone would also work, but whole-partition elimination is cheaper and also makes retention and deletes by day simple.
Both can change later. A new partition spec applies to new data, and a new sort order applies to new writes. Existing files change only when a rewrite is run with that layout. See questions 35 and 30.
32. Linear sort, Z-order or Hilbert curve: which clustering should you use?
Use a linear sort when one column dominates the filters. Use a space-filling curve, Z-order or Hilbert, when queries filter on two to four columns independently.
A linear sort on (a, b) gives each file a narrow range of a, but b is only ordered within each value of a, so a filter on b alone skips little. A curve interleaves the columns, so files get moderately narrow ranges on all of them.
| Method | Strength | Weakness |
|---|---|---|
| Linear sort | Excellent pruning on the leading column | Poor on later columns |
| Z-order | Useful pruning on several columns | Jumps in the curve widen some file ranges |
| Hilbert | Better locality than Z-order | Narrower support |
CALL demo.system.rewrite_data_files(
table => 'shop.orders', strategy => 'sort',
sort_order => 'zorder(customer_id, order_id)',
options => map('rewrite-all', 'true'));
Spark’s rewrite_data_files accepts Z-order. Newer releases accept hilbert() on Spark 4.1 and later; on Spark 3.5 it fails with “Cannot convert transform with more than one column reference”.
Every column you add dilutes the others, so pick them carefully. A mostly null or constant column contributes little. A steadily increasing timestamp is usually well clustered already through ingestion order and partitioning. For long strings, only the first 8 bytes count by default, set by var-length-contribution, which makes values with a long common prefix indistinguishable.
33. Does a filter such as CAST(event_ts AS DATE) still prune partitions?
In Spark 3.5, CAST(event_ts AS DATE) and to_date still prune, because Spark rewrites them into a timestamp range. date_format and date_trunc on the column are not pushed to the Iceberg scan.
EXPLAIN SELECT * FROM demo.shop.orders
WHERE CAST(order_ts AS DATE) = DATE '2026-11-02';
EXPLAIN SELECT * FROM demo.shop.orders
WHERE date_format(order_ts, 'yyyy-MM-dd') = '2026-11-02';
The two plans differ in what reaches the scan:
CAST(order_ts AS DATE) = DATE '2026-11-02'
BatchScan ... filters=order_ts IS NOT NULL,
order_ts >= 1793577600000000, order_ts < 1793664000000000
date_format(order_ts, 'yyyy-MM-dd') = '2026-11-02'
Filter (date_format(order_ts, yyyy-MM-dd) = 2026-11-02)
+- BatchScan ... filters=order_ts IS NOT NULL
In the first, the cast has become a range over exactly one day, and Iceberg can skip every other day. In the second, the scan receives only a not-null check. Every file is read, and Spark filters the rows afterwards. Both queries return the same rows, so nothing but the plan reveals the difference. to_date behaves like the cast, and date_trunc like date_format.
These rewrite rules vary between engines and versions, so read your own plan. The portable form compares the raw column with literal bounds, such as order_ts >= TIMESTAMP '2026-11-02' AND order_ts < TIMESTAMP '2026-11-03', keeping in mind that the session time zone decides which instants those literals mean.
34. How is Iceberg bucket partitioning different from Spark's hash partitioning?
Iceberg’s bucket transform decides which partition a row belongs to in the table. Spark’s hash partitioning decides which task processes a row during one job. They use different hash functions, so their numbers don’t agree.
SELECT id,
demo.system.bucket(8, id) AS iceberg_bucket,
pmod(hash(id), 8) AS spark_hash
FROM VALUES (1L), (2L), (3L), (34L) v(id);
id iceberg_bucket spark_hash
1 4 5
2 4 0
3 3 3
34 3 4
Key 3 matching is a coincidence.
Iceberg bucket(N, col) |
Spark repartition(N, col) |
|
|---|---|---|
| Lifetime | Stored in table metadata | One job |
| Hash | 32-bit Murmur3 as fixed by the Iceberg specification | Spark’s own hash expression |
| Used for | Pruning and bucketed joins | Parallelism and shuffles |
| Same across engines | Yes | No |
So calling df.repartition(8, "id") before a write to a table bucketed into 8 doesn’t line tasks up with buckets: one task can still receive rows for several, and write a small file for each. Let the table’s write distribution mode do the shuffle, since Iceberg asks Spark to cluster by the transform itself. The matching bucket numbers are also what make the storage-partitioned join in question 101 possible, which plain repartitioning can’t give you.
35. What is partition evolution?
Partition evolution means changing the partition spec of an existing table. Old data keeps its layout, new data uses the new one, and nothing is rewritten.
Old and new layouts live side by side.
This works because each manifest records the spec its files were written with. ADD PARTITION FIELD, DROP PARTITION FIELD and REPLACE PARTITION FIELD change only how future writes are laid out. Here orders, partitioned by day, gains a bucket on the customer:
ALTER TABLE demo.shop.orders ADD PARTITION FIELD bucket(4, customer_id);
INSERT INTO demo.shop.orders (order_id, customer_id, amount, status, order_ts)
VALUES (2001, 3, 15.00, 'NEW', TIMESTAMP '2026-11-02 08:00:00');
SELECT spec_id, count(*) AS files FROM demo.shop.orders.files GROUP BY spec_id;
The result shows both layouts in one table:
spec_id files
0 5 written before the change, partitioned by day
1 1 written after it, by day and customer bucket
A query is projected onto each spec separately. A filter on order_ts prunes both sets of files. A filter on customer_id can use the bucket only on files in spec 1, while the older files are skipped or read on their column bounds. Queries need no changes, since they filter on source columns.
You avoid rewriting a large table just to fix its layout. Rewrite old files with rewrite_data_files only if queries on them need the new layout. The catch is in writers: dynamic partition overwrite follows the current spec, so the same INSERT OVERWRITE can replace a different amount of data after the change. Check those jobs first.
36. You must change partitioning on a live table. How?
Use partition evolution. It changes the layout for new writes only, and old data can be rewritten later if it needs to be.
- Review the writers, especially any dynamic overwrites, and the readers.
- Rehearse on a copy of the table.
- Apply the change in one statement, for example
REPLACE PARTITION FIELD months(ts) WITH days(ts). - Check that new files carry the new spec ID.
SELECT spec_id, count(*) AS files, sum(record_count) AS records
FROM demo.shop.orders.files
GROUP BY spec_id;
There is no downtime. Queries plan across both specs, and old data keeps its layout. On the example table, which has been compacted since the change in question 35, every file now reports spec 1.
Rewrite old partitions only if queries on them are too slow. Do it in batches during quiet periods, using where and partial progress, because it costs compute and temporary storage, and expire snapshots afterwards so that the replaced files are released.
The main behaviour change is in overwrite jobs: a dynamic overwrite that used to replace a month now replaces a day. To undo the change, evolve the spec back. Files written in the meantime remain readable under the spec that created them.
37. What is the difference between schema evolution and partition evolution?
Schema evolution changes a table’s columns: their names, types and order. Partition evolution changes its physical layout, meaning how new rows are grouped into partitions. Both only change metadata, and neither rewrites existing data.
Columns and layout evolve independently.
| Schema evolution | Partition evolution | |
|---|---|---|
| What changes | Columns | The partition spec |
| Typical statement | ALTER TABLE ... ADD COLUMN |
ALTER TABLE ... ADD PARTITION FIELD |
| Tracked by | Schema ID | Spec ID, recorded per manifest |
| Effect on old files | Read by column ID; a new column is null or its default | Keep their layout and are pruned with their own spec |
| What to watch | Queries and jobs that use old column names | Overwrite jobs, whose scope follows the current spec |
The example makes one change of each kind to a small table.
DROP TABLE IF EXISTS demo.shop.evolve PURGE;
CREATE TABLE demo.shop.evolve (id BIGINT, amount INT, ts TIMESTAMP)
USING iceberg PARTITIONED BY (days(ts));
INSERT INTO demo.shop.evolve VALUES (1, 10, TIMESTAMP '2026-11-01 08:00:00');
ALTER TABLE demo.shop.evolve ADD COLUMN country STRING;
ALTER TABLE demo.shop.evolve REPLACE PARTITION FIELD days(ts) WITH hours(ts);
INSERT INTO demo.shop.evolve VALUES (2, 20, TIMESTAMP '2026-11-02 09:00:00', 'IN');
SELECT * FROM demo.shop.evolve ORDER BY id;
SELECT spec_id, partition FROM demo.shop.evolve.files ORDER BY spec_id;
The first query returns both rows, with a null country for the row written before the column existed. The second shows one file under spec 0, partitioned by day, and one under spec 1, partitioned by hour. One table can hold files written under many schemas and many specs at once, and queries need no changes to read them. For the details of each, see questions 15 and 35.
38. Why are column renames safe?
Columns can be renamed safely because every field has a permanent numeric ID, and data files record those IDs. A rename changes only the name attached to an ID.
A rename changes the schema and leaves the data files as they are.
Suppose column ID 2 is called name and you rename it to full_name. Old files still contain ID 2. A query asks for full_name, the schema says that is ID 2, and the reader fetches ID 2 from every file, old and new. Nothing is rewritten, and no snapshot is created: a schema change writes only a new metadata file, so the snapshot history and the data files stay as they were.
The same rule handles a nastier case. Add a city column, load data, drop it, then add city again. The second column gets a new ID, so the final query shows null for the older rows even though their files still hold the old values:
before dropping city after dropping and re-adding city
id full_name city id full_name city
1 a NULL 1 a NULL
2 b Pune 2 b NULL
Time travel to an earlier snapshot still shows Pune under that snapshot’s schema. IDs also apply to struct fields, list elements and map keys and values.
Formats that match columns by name can bring old data back when a name is reused, and formats that match by position shift values when a column is removed. IDs avoid both. The exception to watch is files written outside Iceberg, which carry no IDs. The table property schema.name-mapping.default tells readers which names correspond to which IDs. Migration procedures set it up, and if you later rename such a column, keep the old name in the mapping.
39. What is the difference between a schema ID and a field ID?
A schema ID identifies one version of the whole table schema. A field ID identifies one column, and stays with that column across every version.
Think of a table that starts with two columns and gains a third:
schema 0: 1 order_id, 2 amount
schema 1: 1 order_id, 2 amount, 3 region
schema 2: 1 order_id, 2 revenue, 3 region (amount renamed)
Each change here produces a new schema with its own ID. If a change returns the table to a schema it has had before, such as renaming a column and renaming it back, Iceberg can reuse that schema’s ID. The numbers beside the columns never move: renaming amount keeps field ID 2, which is why old files still supply its values.
| Schema ID | Field ID | |
|---|---|---|
| Identifies | A complete schema version | A single column or nested field |
| Changes when | Any column changes | Never, for a given column |
| Stored in | Table metadata and snapshots | Table metadata and data files |
| Used for | Reading a snapshot with the schema it had | Matching a file’s columns to the current schema |
Time travel relies on the first. A read by snapshot ID uses the schema recorded for that snapshot, so you see the old column names. Compatibility of old files relies on the second.
A follow-up interviewers like: what happens if you drop region and add it again? The table gets another schema ID, and the new column gets a field ID that has never been used, so the old values don’t reappear.
40. Which type promotions are allowed?
Iceberg allows only widening type changes, ones where every old value can still be read exactly.
| From | To | Format versions |
|---|---|---|
int |
long |
1, 2, 3 |
float |
double |
1, 2, 3 |
decimal(P, S) |
decimal(P', S) with P’ greater than P |
1, 2, 3 |
date |
timestamp, timestamp_ns (without time zone) |
3 |
unknown |
any type | 3 |
Take int to long. Old files hold 4-byte integers and new files 8-byte ones. A reader can widen each old value without loss, so nothing needs rewriting. The old column statistics stay usable too, because the reader can tell the original type from the length of the encoded bound.
DROP TABLE IF EXISTS demo.shop.types PURGE;
CREATE TABLE demo.shop.types (qty INT, price DECIMAL(10,2)) USING iceberg;
ALTER TABLE demo.shop.types ALTER COLUMN qty TYPE BIGINT;
ALTER TABLE demo.shop.types ALTER COLUMN price TYPE DECIMAL(14,2);
The rejection is a clear error. Both of these fail in Spark with NOT_SUPPORTED_CHANGE_COLUMN:
ALTER TABLE demo.b5.ty ALTER COLUMN qty TYPE INT; -- from BIGINT
ALTER TABLE demo.b5.ty ALTER COLUMN price TYPE DECIMAL(10,3); -- from DECIMAL(10,2)
[NOT_SUPPORTED_CHANGE_COLUMN] ALTER TABLE ALTER/CHANGE COLUMN is not supported for changing
`demo`.`b5`.`ty`'s column `qty` with type "BIGINT" to `qty` with type "INT".
Narrowing is rejected, since some stored values might not fit. Changing a decimal’s scale is rejected because it would change what the stored numbers mean. Spark reports an attempt to turn a BIGINT column back into INT with NOT_SUPPORTED_CHANGE_COLUMN. Even a widening can be refused when the column feeds a partition field and the new type would produce different partition values.
For a change outside the list, such as string to int, there is no metadata-only route, because every old file would need rewriting and some strings might not parse. Do it in steps instead: add a new column, backfill it, switch readers over and then drop the old one. That costs a rewrite, but you control when it happens and can inspect the values that fail to convert.
41. What is the difference between timestamp and timestamptz, and how do time zones affect partitioning?
timestamp stores a date and time with no time zone attached. timestamptz stores an instant, normalised to UTC. Both have microsecond precision in format versions 1 and 2, and version 3 adds nanosecond variants.
Which one you get depends on the engine. In Spark, TIMESTAMP maps to Iceberg timestamptz and TIMESTAMP_NTZ maps to Iceberg timestamp. A table created with a column order_ts TIMESTAMP, like the example table, therefore holds timestamptz values.
timestamp |
timestamptz |
|
|---|---|---|
| Meaning | A wall-clock reading, such as 09:30 on 2 November | A point in time |
| Time zone stored | None | UTC |
| Session time zone matters | No | Yes, when literals are parsed and results are shown |
| Fits | Business dates and local clock readings | Events, logs, commits |
You can see both types in a table definition. In the DESCRIBE output below, Spark shows timestamp for the Iceberg timestamptz column and timestamp_ntz for the Iceberg timestamp column.
CREATE TABLE demo.tz.t (id INT, ts_ltz TIMESTAMP, ts_ntz TIMESTAMP_NTZ)
USING iceberg PARTITIONED BY (days(ts_ltz));
INSERT INTO demo.tz.t VALUES
(1, TIMESTAMP '2026-11-02 02:00:00', TIMESTAMP_NTZ '2026-11-02 02:00:00');
SELECT partition FROM demo.tz.t.partitions;
Run it twice, once with spark.sql.session.timeZone=UTC and once with Asia/Kolkata. The row prints identically both times, but it lands in a different partition:
UTC session {"ts_ltz_day":2026-11-02}
Asia/Kolkata session {"ts_ltz_day":2026-11-01}
In the second run the literal 02:00 means 02:00 India time, which is 20:30 UTC on 1 November, so the row goes to the 1 November partition.
The part that surprises people is partitioning. For a timestamptz column, the day and hour transforms are computed in UTC. A table partitioned by days(order_ts) therefore groups rows by UTC date, and the session time zone only decides how a literal is turned into that UTC instant. For a team in India (UTC+05:30), an order placed at 02:00 on 2 November local time belongs to the 1 November partition, as the run above shows.
Queries still return correct rows, because Iceberg converts the filter to a UTC range before pruning. What changes is the cost: a “local day” filter covers parts of two UTC partitions, so more files are read than the filter’s width suggests. Reports on local days also need the session time zone set consistently, or two jobs will disagree on which day a row falls in.
To keep this predictable, choose one type per column and say so in the data contract. Store event times as timestamptz and set the session time zone explicitly in every job. When the local calendar date is the business key, store it as a separate date column instead of deriving it at query time. Check EXPLAIN to see whether a filter on a local date was turned into a range on the partition column.
42. How does schema evolution work inside structs, lists and maps?
Every nested field has its own ID, so you can add, rename, widen and drop fields inside structs, lists and maps without rewriting data. The exception is that you can’t add a field to a map’s key struct.
You address nested fields with a dotted path, using element for the struct inside a list and value for the struct inside a map.
DROP TABLE IF EXISTS demo.shop.nested PURGE;
CREATE TABLE demo.shop.nested (
id INT,
addr STRUCT<city: STRING, zip: INT>,
tags ARRAY<STRUCT<k: STRING>>,
attrs MAP<STRING, STRUCT<a: INT>>
) USING iceberg;
INSERT INTO demo.shop.nested VALUES (1, named_struct('city', 'Pune', 'zip', 411001),
array(named_struct('k', 'x')), map('p', named_struct('a', 1)));
ALTER TABLE demo.shop.nested RENAME COLUMN addr.zip TO postcode;
ALTER TABLE demo.shop.nested ALTER COLUMN addr.postcode TYPE BIGINT;
ALTER TABLE demo.shop.nested ADD COLUMN tags.element.v INT;
ALTER TABLE demo.shop.nested ADD COLUMN attrs.value.b STRING;
ALTER TABLE demo.shop.nested DROP COLUMN addr.city;
ALTER TABLE demo.shop.nested ADD COLUMN addr.city STRING;
SELECT * FROM demo.shop.nested;
Reading by ID keeps old files compatible: a field missing from a file is filled with null or its default, and a field no longer in the schema is ignored. The query returns:
id addr tags attrs
1 {411001, NULL} [{x, NULL}] {p -> {1, NULL}}
Look at addr. The postcode survived its rename and widening. The city shows NULL, although the only data file holds Pune, because city was dropped and added again: the new field has a new ID that the old file doesn’t contain. The new fields v and b are null for the same reason. A query against an earlier snapshot still shows the original structure with the city.
Dropping and re-adding a column to “reset” it is therefore a real way to lose access to values, so rename instead when you want to keep them.
43. What is the difference between required and optional fields?
A required field may never be null. An optional field may. Spark’s NOT NULL creates a required field, and every other column is optional.
The difference matters most during evolution, because old files can’t be changed to satisfy a new promise.
DROP TABLE IF EXISTS demo.shop.nulls PURGE;
CREATE TABLE demo.shop.nulls (id BIGINT NOT NULL, note STRING) USING iceberg;
ALTER TABLE demo.shop.nulls ALTER COLUMN id DROP NOT NULL;
INSERT INTO demo.shop.nulls VALUES (NULL, 'x');
Relaxing a required column works, as above. The reverse is refused in Spark:
| Attempt | Result |
|---|---|
ALTER COLUMN note SET NOT NULL |
Cannot change nullable column to non-nullable: note |
ADD COLUMN must STRING NOT NULL |
Incompatible change: cannot add required column: must |
DROP NOT NULL on a required column |
Allowed |
Writing a null into a required column fails too, and the message can mislead. With Spark 3.5.9 and a literal VALUES (NULL), the top of the stack trace is an [INTERNAL_ERROR] that tells you to report a bug. Scroll to the cause, which reads NullPointerException: Null value appeared in non-nullable field. It is your data, not a Spark defect.
In production, make a column required only when every producer can honour it for good. Starting optional and enforcing quality in the pipeline is easier to live with than discovering a late source that sends nulls.
44. What is the VARIANT type, and what does shredding do?
variant is a format version 3 type that stores semi-structured values, such as JSON, in a compact binary encoding. Shredding additionally writes frequently occurring paths into their own typed Parquet columns, so a query can read one path without decoding the whole value.
CREATE TABLE demo.shop.events (id BIGINT, payload VARIANT) USING iceberg
TBLPROPERTIES ('format-version' = '3', 'write.parquet.shred-variants' = 'true');
INSERT INTO demo.shop.events
SELECT id, parse_json(concat('{"user":', id, ',"city":"Pune"}')) FROM range(100);
SELECT variant_get(payload, '$.city', 'string')
FROM demo.shop.events
WHERE variant_get(payload, '$.user', 'int') = 7;
| Storage choice | Reading one field | Adding a field |
|---|---|---|
| JSON string | Parse the whole string every time | Nothing to change |
| Struct | Fast, typed columns | Schema change |
variant |
Decode binary; shredded paths read directly | Nothing to change |
Think of an events table where every record has user and city but a long tail of rare attributes. Shredding can give the common paths real columns, while the rare ones, or paths whose type varies between records, stay in the binary value.
Shredding is off by default and can be enabled by a table property, a session setting or a write option. The engine needs a variant type of its own: a Spark 4 build with the matching Iceberg runtime can use it, while Spark 3.5 can’t create such a column, so this example isn’t part of the runnable sequence. Whether a filter on a shredded path skips files depends on engine and release, so measure the bytes read.
45. What happens if the schema changes while a job is writing?
A running append normally commits successfully. Its files record column IDs, so readers map them onto the new schema.
The writer fixed its schema when it planned the job. At commit time it adds its files to the latest metadata, whatever schema that now has.
| Schema change made during the write | Effect on the rows written |
|---|---|
| Column added | Reads as null or its default |
| Column renamed | None; matched by ID |
| Type widened | Values are promoted on read |
| Column dropped | Values stay in the file, unread |
You can watch this happen. A write is held open for three seconds by a sleeping expression, and a column is added to the table while it runs:
def writer():
df = (spark.range(100, 105)
.selectExpr("id", "cast(id as string) as name",
"reflect('java.lang.Thread','sleep',cast(3000 as long)) as s")
.drop("s"))
df.writeTo("demo.sc.t").append() # takes about 3 seconds
threading.Thread(target=writer).start()
time.sleep(1.5)
spark.sql("ALTER TABLE demo.sc.t ADD COLUMN country STRING") # mid-write
schema changed while the write was running
write: committed
columns: ['id', 'name', 'country']
rows: (1, 'a', None) (100, '100', None) (101, '101', None) ... (104, '104', None)
The append committed without an error, the new column exists, and the five new rows read NULL for it, because their files were written with the old schema.
Two schema changes racing each other behave differently. Each is committed against the metadata it started from, so the second one gets CommitFailedException and must be run again against the new schema.
The table stays readable, but your pipeline may still be surprised. Row-level operations validate more strictly than appends, and a streaming job usually keeps its starting schema until it is restarted, so it won’t populate a newly added column. Coordinate breaking changes, such as renames and drops, with the teams running writers.
46. How do you troubleshoot a schema mismatch when writing to an Iceberg table?
Read the error class first. Spark says whether the number of columns is wrong, a column is missing or a type can’t be converted safely, and each has a different fix.
DROP TABLE IF EXISTS demo.shop.mismatch PURGE;
CREATE TABLE demo.shop.mismatch (id BIGINT, note STRING) USING iceberg;
DESCRIBE TABLE demo.shop.mismatch;
Against that table, Spark 3.5.9 rejects bad writes like this:
| Write | Error |
|---|---|
VALUES (1, 'x', 'extra') |
INSERT_COLUMN_ARITY_MISMATCH.TOO_MANY_DATA_COLUMNS |
(id) VALUES (2) |
INCOMPATIBLE_DATA_FOR_TABLE.CANNOT_FIND_DATA for note |
VALUES ('abc', 'x') |
INCOMPATIBLE_DATA_FOR_TABLE.CANNOT_SAFELY_CAST for id |
The middle one catches people: an optional column can still be demanded by a write that lists only some columns, depending on engine and version.
Then work outward from the table:
- Compare the table schema with the schema of the data being written, including nested fields and nullability.
- Check whether someone changed the table recently, in
metadata_log_entries. - Refresh the table, in case the session cached an old schema.
- For files imported with
add_files, check the name mapping. - Confirm every engine involved supports the column types.
Fix the producer or evolve the table on purpose. Enabling automatic schema merging to silence the error turns a typo into a permanent column, as question 121 describes.
Writes, commits and concurrency
47. What are the write distribution modes?
The write distribution mode decides how rows are shuffled between tasks before files are written. The table property write.distribution-mode accepts none, hash or range.
It matters because each write task creates its own file for every partition it holds rows for. Picture 200 tasks, each holding a mix of rows from 30 days.
| Mode | Shuffle | What happens to those 200 tasks |
|---|---|---|
none |
No shuffle | Each task writes up to 30 files: as many as 6,000 in one commit |
hash |
By partition value | Rows for a day meet in one task: about one file per day |
range |
Sample, then range-shuffle on partition and sort keys | Ordered output with narrow file ranges, at the highest cost |
You can count the effect. Thirty thousand rows covering three days are written from eight tasks into two tables partitioned by days(ts), one with none and one with hash:
| Mode | Data files | Partitions | Average rows per file |
|---|---|---|---|
none |
24 | 3 | 1,250 |
hash |
3 | 3 | 10,000 |
With none, each of the eight tasks wrote a file into each partition it held rows for, so 3 partitions produced 24 files. With hash, all rows for a day went to one task, so each partition got one file.
When the property is unset, Spark picks range for sorted tables, hash for partitioned ones and none otherwise.
ALTER TABLE demo.shop.orders SET TBLPROPERTIES (
'write.distribution-mode' = 'hash');
hash has its own weakness. If one partition is much larger than the rest, a single task receives all of it; adaptive query execution can split such a partition. With none, the writer expects rows already clustered by partition within each task, unless you enable the fanout writer, which keeps a file open per partition at a cost in memory.
Row-level operations have their own settings, such as write.merge.distribution-mode, so tuning appends doesn’t automatically tune merges.
48. What controls output file size?
The table property write.target-file-size-bytes sets the output file size, 512 MB by default. It is a target and not a guarantee.
A writer rolls over to a new file when the current one reaches the target, so the setting caps files well but can’t make small ones bigger. Four things keep real files below it:
- a task can’t write more data than it holds
- a file never crosses a partition boundary
- compressed Parquet is much smaller than the shuffle data it came from
- every commit writes its own files, however little data arrived
With a shuffling distribution mode, adaptive execution sizes the write tasks from spark.sql.adaptive.advisoryPartitionSizeInBytes. That value measures shuffle data, which is larger than the compressed output, so it usually has to be set higher than the file target to produce files of that size.
ALTER TABLE demo.shop.orders SET TBLPROPERTIES (
'write.target-file-size-bytes' = '134217728');
The target is an upper bound that the writer respects. Twenty thousand rows of incompressible text written by a single task with a target of 100,000 bytes gave:
files 10 average size 73 KB largest file 74,200 bytes
No file crossed the target, and the files closed a little below it.
The right target depends on use. Large files suit full scans, with fewer files to open and better compression. Smaller files can help selective queries and make copy-on-write changes cheaper, since less is rewritten per matching row.
When files come out far below target, say 20 MB against 512 MB, raising the target does nothing. Look for too many write tasks, too many partitions or commits that are too frequent. Write reasonably sized files and let compaction close the remaining gap.
49. What is the difference between a fast append and a merge append?
A fast append writes a new manifest for the added files and reuses all the others. A merge append may also combine small manifests while committing.
The trade is between the cost of writing now and the cost of reading later.
| Fast append | Merge append | |
|---|---|---|
| Work during commit | Minimal | Reads and rewrites some manifests |
| Window for conflicts | Short | Longer |
| Number of manifests | Grows with every commit | Kept in check |
| Spark default | Structured Streaming | Batch appends |
Imagine a stream committing every minute with fast appends. After a week it has added more than 10,000 manifests, each listing a handful of files, and every query must work through a very long manifest list.
Merging starts once there are commit.manifest.min-count-to-merge manifests (100 by default), aims for commit.manifest.target-size-bytes (8 MB) and can be turned off with commit.manifest-merge.enabled. A stream uses merge appends only when use-merge-append-for-streaming is set.
SELECT count(*) AS manifests, avg(length) AS avg_bytes
FROM demo.shop.orders.manifests;
You can watch the threshold work. Eight single-row inserts into two tables, one with the default commit.manifest.min-count-to-merge of 100 and one with it set to 3:
table manifests after 8 commits
default (100) 8
min-count-to-merge = 3 2
Each default commit added a manifest and kept all the others. The table with the low threshold merged small manifests as it went, so it ended with two.
Count manifests and check their average size with that query. For a streaming table, either rewrite manifests on a schedule, which keeps commits fast, or enable merge appends and accept slightly slower commits. The first usually suits high commit rates better.
50. What is the difference between static and dynamic partition overwrite?
The two modes decide how much INSERT OVERWRITE replaces. Static mode, Spark’s default, replaces the whole table unless you name a partition. Dynamic mode replaces only the partitions that receive new rows.
SET spark.sql.sources.partitionOverwriteMode=dynamic;
INSERT OVERWRITE demo.shop.orders (order_id, customer_id, amount, status, order_ts)
VALUES (6001, 2, 20.00, 'NEW', TIMESTAMP '2026-11-04 10:00:00');
SET spark.sql.sources.partitionOverwriteMode=static;
The example writes one row for 4 November in dynamic mode, so only that day’s partitions it touches are replaced. In static mode the same statement without a partition clause would replace the entire table with that one row.
| Static | Dynamic | |
|---|---|---|
| Replaces | Whole table, or the named partition | Partitions present in the new data |
| Empty source | Can empty the table | Replaces nothing |
| Depends on the partition spec | Only for the named partition | Yes |
Iceberg recommends dynamic mode or MERGE INTO. The DataFrame v2 writer makes the intent visible: writeTo(t).overwritePartitions() is dynamic, and writeTo(t).overwrite(condition) replaces the rows matching a filter.
Dynamic mode has its own surprise. With hidden partitioning, “the partitions touched” follows the current spec. Here the table also has a customer bucket, so the insert replaces only the bucket of that day that received the row, not the whole day. For a backfill, overwrite with an explicit condition, run it on a branch, validate and then publish.
51. Why does a MERGE fail with MERGE_CARDINALITY_VIOLATION?
MERGE_CARDINALITY_VIOLATION means more than one source row matched the same target row, so Iceberg can’t know which one should win.
target: key=1 source: key=1 'b', key=1 'c' -> error
target: no key=2 source: key=2 'b', key=2 'c' -> both inserted
A common cause is a batch of change events that contains two updates for one key. The fix is to deduplicate the source first, keeping the latest row per key:
SELECT order_id, status FROM (
SELECT *, row_number() OVER (PARTITION BY order_id ORDER BY order_ts DESC) AS rn
FROM demo.shop.orders
) latest WHERE rn = 1 LIMIT 5;
Order by a sequence that comes from the source system, such as a log position or version number. Arrival time is a poor choice, because retries and out-of-order delivery can make an older version look newest.
Two related problems raise no error at all, which makes them worse:
| Situation | What happens |
|---|---|
| Two source rows with a key not yet in the target | Both are inserted, creating a duplicate |
| One source row matching several target rows | All of them are updated |
A replayed batch with no guard such as s.seq > t.seq |
Older data overwrites newer data |
Identifier fields declare which columns identify a row, but writes are not checked against them. Iceberg enforces no primary key, so the pipeline has to keep keys unique and monitor that they stay so.
52. When should you use MERGE instead of DELETE followed by INSERT?
Use MERGE when you are replacing or updating matching rows. It publishes the removal and the new rows in one commit, whereas two statements publish them separately.
DROP TABLE IF EXISTS demo.shop.merge_demo PURGE;
CREATE TABLE demo.shop.merge_demo (id BIGINT, v STRING) USING iceberg;
INSERT INTO demo.shop.merge_demo VALUES (1, 'old');
INSERT INTO demo.shop.merge_demo VALUES (2, 'old');
-- two commits
DELETE FROM demo.shop.merge_demo WHERE id = 1;
INSERT INTO demo.shop.merge_demo VALUES (1, 'new');
-- one commit
MERGE INTO demo.shop.merge_demo t
USING (SELECT 2L AS id, 'new' AS v) s
ON t.id = s.id
WHEN MATCHED THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *;
SELECT operation, summary['total-records'] AS total
FROM demo.shop.merge_demo.snapshots ORDER BY committed_at;
After the two setup inserts, the history shows a delete leaving one row, then a separate append bringing it back to two. A reader arriving between them sees a table with row 1 missing, and if the job dies there, it stays missing. The MERGE appears as a single overwrite that never loses a row.
DELETE then INSERT |
MERGE |
|
|---|---|---|
| Commits | Two | One |
| Intermediate state visible | Yes | No |
| Failure halfway | Rows missing | Nothing changes |
| Cost | A scan for the delete | A join between source and target |
Two statements still make sense when the delete is a whole partition that can be dropped in metadata, but then an atomic overwrite is usually the better tool. Whichever you pick, a source with duplicate keys needs deduplicating first, as in question 51.
53. A MERGE updating ten thousand rows in a huge table takes hours. How do you fix it?
The job is probably scanning and rewriting far more data than it changes. Without a predicate that limits the target table, every file is a candidate.
Copy-on-write rewrites every file that contains even one match. If ten thousand rows are spread across ten thousand files of 512 MB, updating them rewrites about 5 TB.
CREATE OR REPLACE TEMPORARY VIEW order_updates AS
SELECT order_id, 'PAID' AS status, max(order_ts) AS order_ts
FROM demo.shop.orders WHERE order_id < 10 GROUP BY order_id;
MERGE INTO demo.shop.orders t
USING order_updates s
ON t.order_id = s.order_id
AND t.order_ts >= TIMESTAMP '2026-11-01 00:00:00'
AND t.order_ts < TIMESTAMP '2026-11-06 00:00:00'
WHEN MATCHED THEN UPDATE SET status = s.status;
| Fix | Effect |
|---|---|
Literal partition range in the ON clause, computed from the source |
Only matching partitions are scanned |
| Cluster the table by the merge key | Matches fall into few files |
| Merge-on-read | Writes small delete files instead of rewriting |
| Deduplicate and filter the source | It may become small enough to broadcast |
| Compatible partitioning on both sides | The join can avoid a shuffle |
Spark’s runtime row-level group filter, on by default, narrows which files get rewritten. It doesn’t narrow the matching join, which still reads everything the static predicates allow. That is why adding the date range to ON helps even with the runtime filter enabled.
Check the Spark UI for files scanned against files written, and for spill. A large gap between rows changed and data written points at layout; a huge scan points at the missing predicate.
54. What are position deletes and equality deletes?
A position delete names a data file and a row position inside it. An equality delete names column values, such as an ID, without knowing where the matching rows are.
Position deletes name a place; equality deletes name a value.
Both exist because data files are never edited. The difference is who does the work of locating the row.
| Position delete | Equality delete | |
|---|---|---|
| Identifies rows by | File path and position | Column values |
| Writer must find the row | Yes, by reading the target | No |
| Reader’s job | Skip known positions in one file | Compare values against every applicable file |
A streaming upsert shows why equality deletes exist. A Flink writer receives a new version of key 42. Finding the old row would mean searching the table for every event, so it writes “delete where id = 42” together with the new row and moves on. Readers do the matching later. Those deletes apply to older files in the same partition, or to all files if the delete is global. Spark’s row-level commands write position deletes, and on format version 3 new ones are stored as deletion vectors.
The query counts files by content, where 0 is data, 1 position deletes and 2 equality deletes. The example table uses copy-on-write, so only content 0 appears.
SELECT content, count(*) FROM demo.shop.orders.files GROUP BY content;
Equality deletes move cost onto every query, which has to load the delete values and check them against each applicable file, often as an in-memory join. Compact so that deletes are applied and removed, and do it frequently wherever equality deletes are written.
55. What are sequence numbers for?
Sequence numbers give commits a reliable order, which is how Iceberg decides which delete files apply to which data files.
Each successful commit takes the next number, and the files it adds carry it. An equality delete for id = 7 should remove the row that existed when it was written, but not a row with the same ID inserted later.
Only strictly older data is affected by an equality delete.
A file actually has two numbers:
| Number | Records | Used for |
|---|---|---|
| Data sequence number | How old the rows are logically | Matching deletes to data |
| File sequence number | When this file was added | Tracking the file itself |
Compaction shows why. Suppose it rewrites old data while a delete is committed. The new file is physically newer than the delete, yet its rows are older. If it took the new number for its data, the delete would appear to be older than the data and stop applying, and deleted rows would return. So the rewritten file keeps the original data sequence number. The manifest list also stores a min_sequence_number per manifest, which lets planning discard deletes too old to affect anything.
A snapshot ID can’t do this job. It is a random long, so sorting by it gives the wrong order; to read history in order use committed_at in snapshots, or the parent_id chain. The sequence number is also visible per entry in the entries metadata table (sequence_number, file_sequence_number).
Writer clocks couldn’t provide this order, because machines disagree about the time. New manifest entries store null and inherit the number at commit, so a retried commit receives a fresh number without rewriting its manifests. Files in tables upgraded from version 1 count as sequence number 0.
56. When does a delete file apply to a data file?
A delete file applies to a data file when the data is old enough and falls within the delete’s scope.
| Delete type | Sequence rule | Scope |
|---|---|---|
| Position delete or deletion vector | Data sequence number is less than or equal to the delete’s | Same partition spec and values, and the file is referenced |
| Equality delete | Data sequence number is strictly less than the delete’s | Same partition; every file if the delete is unpartitioned |
The one-character difference between the rules is deliberate. A streaming upsert writes everything for a batch in one commit, so all files share one sequence number.
commit 5: insert row (id=7, v='a') into file X
later in the same batch, id=7 changes again:
position delete X, row 0 applies (5 <= 5)
equality delete id=7 does not reach X (5 is not < 5)
insert row (id=7, v='b')
Position deletes can remove a row added by the same commit, which handles changes within the batch. Equality deletes can’t, which is what allows “delete key 7, insert the new key 7” to keep the new row.
Position delete files are ignored for a data file that has a deletion vector, because the vector must already include their positions. An unpartitioned equality delete applies to every older file, so queries pay for it everywhere. After partition evolution, a delete scoped to an old partition doesn’t reach files written under the new spec. And every extra delete that applies to a file adds to the cost of scanning it.
57. What are deletion vectors, and why replace position delete files?
A deletion vector is a bitmap of the deleted row positions in one data file, stored as a blob inside a Puffin file. Format version 3 introduced it to replace position delete files.
Position delete file on the left, deletion vector on the right.
On version 2, repeated small deletes create more and more position delete files, and a reader has to find all that apply to a data file and merge them. With deletion vectors there is at most one per data file in a snapshot. A new delete reads the existing bitmap, adds its positions and writes a replacement, so the reader loads one structure and tests each row position against it.
| Position delete files | Deletion vectors | |
|---|---|---|
| Storage | Parquet rows of file path and position | Roaring bitmap in a Puffin blob |
| Per data file | Any number | At most one |
| Reader’s work | Find, open and merge | Load one bitmap |
Roaring bitmaps stay compact whether the deletions are sparse or dense, and one Puffin file can hold vectors for many data files, with the manifest recording each blob’s offset and length. Using the version 3 table from question 60, deleting one row produces a delete file with format PUFFIN and a record count of 1:
INSERT INTO demo.shop.upgrade_demo SELECT /*+ COALESCE(1) */ id FROM range(10);
ALTER TABLE demo.shop.upgrade_demo SET TBLPROPERTIES ('write.delete.mode' = 'merge-on-read');
DELETE FROM demo.shop.upgrade_demo WHERE id = 3;
SELECT file_format, record_count FROM demo.shop.upgrade_demo.delete_files;
Two limits remain. Because both writers must replace the same vector, concurrent deletes against one data file conflict. And deleted rows are still stored and still read before being skipped, so rewrite heavily deleted files. Old position delete files on an upgraded table stay valid until that file’s deletes are next written.
58. Why can delete files survive a compaction?
Compaction replaces data files, and it can leave behind delete files that point at files no longer live. These dangling deletes change no result but still cost storage and planning time.
How a delete file can outlive the data it applied to.
Say a data file has a delete file against it. Compaction rewrites the data with the deletes applied. The new file is clean, and nothing needs the old delete file, but it may still be listed in the current snapshot.
| Tool | What it does about deletes |
|---|---|
rewrite_data_files with delete-file-threshold or delete-ratio-threshold |
Selects affected files and folds the deletes into new data files |
The same with remove-dangling-deletes |
Also drops delete files that no longer apply |
rewrite_position_delete_files |
Compacts position delete files and removes dangling positions |
By default a data file isn’t rewritten for its deletes until they cover 30% of its rows, and the position delete procedure may find nothing worth selecting.
So check the delete file counts after running these. Removal based on sequence numbers misses some cases, such as a global equality delete that matches nothing, and behaviour has changed between releases. Storage is only released once older snapshots that reference the files expire. See copy-on-write or merge-on-read.
59. What is a table format version?
The format version states which features a table’s metadata may use, so that a reader doesn’t misinterpret something it doesn’t understand. Current libraries create version 2 tables by default.
| Version | What it covers |
|---|---|
| 1 | Analytic tables on immutable files |
| 2 | Row-level deletes through delete files and sequence numbers |
| 3 | Deletion vectors, row lineage, default values and new types |
| 4 | Relative paths in metadata; still under development |
SHOW TBLPROPERTIES demo.shop.orders ('format-version');
For the orders table the value is 2.
A new version appears only when an older reader would otherwise get wrong results. Version 2 is the clearest case. A reader that knew nothing about delete files would ignore them and happily return rows that had been deleted. The version number tells that reader to stop instead.
Choose the lowest version that has the features you need and that all your engines support. Upgrading is a single property change that rewrites nothing, and the new features apply to later writes. There is no downgrade. A newer library reads older tables, but an older one may fail on newer tables, so upgrade every reader before you upgrade the table.
60. How do you upgrade the format version?
Set the table’s format-version property. The upgrade changes metadata only and rewrites no data.
DROP TABLE IF EXISTS demo.shop.upgrade_demo PURGE;
CREATE TABLE demo.shop.upgrade_demo (id BIGINT) USING iceberg;
ALTER TABLE demo.shop.upgrade_demo SET TBLPROPERTIES ('format-version' = '3');
| Upgrade | What changes |
|---|---|
| 1 to 2 | Sequence numbers arrive and row-level deletes are allowed |
| 2 to 3 | New deletes use deletion vectors, and row lineage starts for new snapshots |
Here is the evidence from a table with four data files and two snapshots, upgraded from version 2 to 3. Counting metadata before and after, and reading the format-version field of each metadata.json:
before upgrade after upgrade
data files 4 4
snapshots 2 2
v1.metadata.json format-version 2 (create)
v2.metadata.json format-version 2 (insert)
v3.metadata.json format-version 2 (insert)
v4.metadata.json format-version 3 <- the upgrade: one new metadata file, nothing else
No data file and no snapshot was added. The upgrade is one new metadata file that records the new version.
Existing files stay as they are. Position delete files written on version 2 remain valid after moving to 3, until the deletes for that data file are written again.
The statement takes a moment, and that makes it easy to underestimate. There is no downgrade. Going back means copying the data into a new table at the lower version, which loses the history. And an engine that doesn’t support the new version may be unable to read the table at all.
Treat it as a rollout:
- List every reader, writer and maintenance job.
- Confirm each supports the new version and the features you will start using.
- Rehearse on a test table with the same properties.
- Upgrade the engines, readers first, then the table.
- Have a recovery plan that doesn’t depend on downgrading.
61. What is row lineage?
Row lineage, added in format version 3, gives every row a stable ID and records which commit last changed it. They appear as the metadata columns _row_id and _last_updated_sequence_number.
Without it, an engine comparing two snapshots can’t tell whether a row was updated or one row was removed and a different one added, especially after files have been rewritten.
IDs are assigned by inheritance, so most writes store nothing. Each data file receives a first row ID, and each row’s ID is that value plus its position. The table keeps track of the next unused number.
file A, first row id 1000 rows get 1000, 1001, 1002
compaction moves row 1001 its id 1001 is written into the new file
update of row 1001 id stays 1001, last-updated takes the new commit
Row lineage can be queried directly. Create a version 3 table with two rows, update one, and read the metadata columns:
CREATE TABLE demo.b5.rl (id BIGINT, v STRING) USING iceberg
TBLPROPERTIES ('format-version' = '3');
INSERT INTO demo.b5.rl VALUES (1, 'a'), (2, 'b');
UPDATE demo.b5.rl SET v = 'B' WHERE id = 2;
SELECT id, v, _row_id, _last_updated_sequence_number FROM demo.b5.rl ORDER BY id;
before the update after the update
id v _row_id _last_updated_seq id v _row_id _last_updated_seq
1 a 0 1 1 a 0 1
2 b 1 1 2 B 1 2
Row 2 kept _row_id 1 when it was updated, and its _last_updated_sequence_number moved from 1 to 2. Row 1 was not touched, so both values stayed.
When compaction or copy-on-write moves a row, the ID is copied with it. A modified row leaves the last-updated value empty so that it inherits the new commit’s sequence number. Assigning IDs this way keeps commit retries cheap.
That supports incremental processing, which can now distinguish changed rows from new ones, and auditing. There are gaps to know about. Rows changed through equality deletes lose their identity, because the writer never read the old row. Snapshots from before the upgrade have no IDs. And a row ID is not a business key: two rows describing the same customer have different row IDs.
62. What else does format version 3 add, and what is the status of version 4?
Besides deletion vectors and row lineage, format version 3 adds new data types, column default values, multi-argument transforms and table encryption keys. Version 4 is still being designed.
| Addition in version 3 | What it is for |
|---|---|
variant |
Semi-structured data such as JSON |
geometry, geography |
Spatial data |
| Nanosecond timestamps | Finer time precision |
unknown |
A column whose type isn’t decided yet |
initial-default |
The value older rows show for a newly added column |
write-default |
The value used when a later write omits the column |
The two defaults solve different problems. Add a currency column with an initial default of EUR, and every existing row reads as EUR without any file being rewritten. The write default then fills the column for new rows whose writer doesn’t supply it, and it can be changed independently later.
Deletion vectors are the easiest v3 change to see. Create the same merge-on-read table twice, once as version 2 and once as version 3, delete one row from each, and look at the delete file:
CREATE TABLE demo.q.v3 (id BIGINT, v STRING) USING iceberg
TBLPROPERTIES ('format-version' = '3', 'write.delete.mode' = 'merge-on-read');
INSERT INTO demo.q.v3 SELECT id, 'x' FROM range(10);
DELETE FROM demo.q.v3 WHERE id = 3;
SELECT content, file_format, record_count FROM demo.q.v3.delete_files;
table content file_format record_count
v2 1 PARQUET 1 <- a position delete file
v3 1 PUFFIN 1 <- a deletion vector inside a Puffin file
The version 2 table wrote a separate Parquet file of position deletes. The version 3 table wrote a bitmap blob into a Puffin file instead.
Version 4 is not formally adopted. Its documented change so far is relative paths in metadata, which would make tables easier to move, and it shouldn’t be used in production.
A feature appearing in the specification doesn’t mean you can use it. Every engine on the table has to implement it for both reading and writing; variant, for example, needs an engine that has such a type. Verify each engine, try the feature on a new table and only then upgrade existing ones.
63. Walk through the commit protocol.
A writer builds new files and metadata on top of the current table version, then asks the catalog to switch the pointer only if that version is still current.
A commit is new files plus one conditional pointer swap.
- Read the current metadata. This is the base.
- Write data files and any delete files.
- Write manifests, a manifest list and a new metadata file.
- Ask the catalog to swap from the base to the new file.
- If another writer got there first, reload, check that the change is still valid and try again.
Nothing is locked during steps 1 to 3, which may take hours. This is optimistic concurrency: assume conflicts are rare and check at the end. The check on retry depends on what the operation did:
| Operation | What must still be true |
|---|---|
| Append | Nothing; adding files can’t contradict other changes |
| Compaction | The replaced files are still present, with no new position deletes against them |
| File delete | Its files are still present |
| Row-level change | No conflicting data or deletes, according to its isolation level |
| Schema or partition spec change | The old definition is unchanged |
So a retry is usually cheap. The data files are kept, manifests can often be reused, and only the top of the metadata tree is rebuilt. A long compaction that loses a race to an append succeeds on retry; one that loses to an update of the same files can’t, and its work is wasted. The whole design depends on the catalog performing the compare-and-swap correctly.
64. Compare CommitFailedException, ValidationException and CommitStateUnknownException.
The three exceptions answer different questions. CommitFailedException means a commit lost a race, ValidationException means the change is no longer valid against newer commits, and CommitStateUnknownException means nobody knows whether it happened.
CommitFailedException let retries run; if exhausted, reduce contention
ValidationException recompute from the new table state
CommitStateUnknownException query snapshots; decide; then rerun if absent
| Exception | Raised when | Safe response |
|---|---|---|
CommitFailedException |
The catalog rejects the pointer swap | Retry; Iceberg already retries automatically before surfacing it |
ValidationException |
Checking the new base finds a real conflict, for example “Found conflicting files that can contain records matching” the operation’s filter | Recompute the operation from the new table state, or remove the overlap |
CommitStateUnknownException |
The request was sent but no definite answer came back, such as after a network timeout | Check the table before doing anything |
The first two are certain: nothing was committed. The third is the dangerous one. Iceberg checks the outcome itself first, three times by default (commit.status-check.num-retries), and raises this exception only when it still can’t tell. If the commit did succeed, its files are now live. Deleting them as cleanup corrupts the table, and rerunning the job may apply the change twice. Look for the commit in the snapshots table first.
Design jobs so that the answer matters less. A MERGE on a business key, an overwrite of a deterministic partition, or a batch ID stored in the snapshot summary all make a rerun safe or at least easy to check.
65. How are commit retries configured?
Four table properties control how a writer retries a commit that lost the race.
| Property | Default | Meaning |
|---|---|---|
commit.retry.num-retries |
4 | Attempts after the first failure |
commit.retry.min-wait-ms |
100 | Shortest wait between attempts |
commit.retry.max-wait-ms |
60,000 | Longest wait |
commit.retry.total-timeout-ms |
1,800,000 | Give up after 30 minutes in total |
After a rejected swap the writer waits, doubling the delay each time within those bounds, reloads the table, checks that its change is still valid and tries again. The growing delay spreads competing writers out so they stop colliding.
ALTER TABLE demo.shop.orders SET TBLPROPERTIES (
'commit.retry.num-retries' = '10');
The effect is dramatic when many jobs collide. Eight concurrent INSERT statements into one table, each in its own Spark session, with retries switched off and then left on:
commit.retry.num-retries |
Jobs committed | Failures |
|---|---|---|
| 0 | 1 of 8 | 7 CommitFailedException |
| 4 | 8 of 8 | none |
With no retries, the first commit wins the pointer swap and every other job fails. With four retries, each loser reloads the table, rebuilds its metadata and tries again, and all eight succeed. These are appends, so no retry could ever hit a real conflict.
Retries solve one problem, which is contention between operations that are compatible, mostly appends. They can’t solve a validation failure, because that is a real conflict and will fail the same way next time. Nor can they help when commits arrive faster than the catalog and metadata can process them.
So treat higher retry counts as the last step. First commit less often or use fewer competing writers. Then keep metadata small so each attempt is short. Raise the count only after that. A very high value hides a design problem and stretches job run times. Rising attempts per commit in commit reports and driver logs are the early warning to watch.
66. What isolation levels do row-level operations offer?
Iceberg offers two isolation levels for row-level operations, serializable, the default, and snapshot. Each command has its own property: write.delete.isolation-level, write.update.isolation-level and write.merge.isolation-level.
Both stop two writers from changing the same rows. They differ in what they do about new data that arrives while the operation runs.
| A concurrent commit… | serializable |
snapshot |
|---|---|---|
| Removes or rewrites a file the operation depends on | Fails | Fails |
| Adds deletes for rows being updated | Fails | Fails |
| Appends data that matches the operation’s filter | Fails | Allowed |
| Changes data outside the filter | Allowed | Allowed |
Both levels can be run against the same race. A copy-on-write UPDATE ... WHERE id >= 0 is held open while a second session appends a row:
write.update.isolation-level |
The UPDATE |
Rows afterwards |
|---|---|---|
serializable |
Fails with ValidationException: Found conflicting files that can contain records matching ref(name="id") >= 0 |
4 (the append survived) |
snapshot |
Commits | 4 (the append is kept, but it was never updated) |
Under snapshot the new row 100 was never touched by the update, because it did not exist when the update started. Under serializable that is treated as a conflict, since a serial order of the two operations would have updated it.
Take UPDATE ... SET status = 'CHECKED' WHERE status = 'NEW', while another job appends rows with status NEW. Under serializable isolation the update fails, because running it after the append would have changed those rows too. Under snapshot isolation it commits, and the new rows keep status NEW. No ordering of the two jobs, one after the other, produces that result, although each reader still sees a consistent snapshot.
ALTER TABLE demo.shop.orders SET TBLPROPERTIES (
'write.delete.isolation-level' = 'serializable',
'write.merge.isolation-level' = 'serializable');
Keep serializable unless the pipeline can tolerate rows appearing during an operation, for example when heavy ingestion runs beside corrections to older data. Before relaxing the level, try narrowing the filter: a condition on the partition column lets Iceberg see that unrelated appends can’t match, which removes most false conflicts.
67. Twenty jobs append to one table and some fail with CommitFailedException. How do you fix it?
The jobs lose the race for the pointer swap more often than their retry budget allows. Appends never conflict logically, so this is pure contention.
Confirm the exception really is CommitFailedException and not ValidationException, which would point to a logical conflict. Then measure two numbers: commits per minute and how long a commit takes.
A small reproduction shows the shape of the failure. Eight jobs append to one table at once, each holding its commit for about a second:
commit.retry.num-retries = 0 committed 1 of 8 failures: CommitFailedException
commit.retry.num-retries = 4 committed 8 of 8 failures: none
The raw failure rate is high because all eight jobs reach the commit together. Raising retries hides the problem, as the last item of the list below warns, but it does show that these are pure contention failures: all eight appends were valid.
chance of a collision rises with: commit rate x commit duration
Each writer reads the base, builds metadata and attempts the swap, and anyone who commits during that window defeats it. Suppose twenty jobs each commit every 10 seconds and a commit takes 2 seconds. That is two commits arriving every second, each exposed for 2 seconds, so most attempts find that someone else got there first. A bloated metadata file makes each attempt slower and widens the window.
Fix it in this order:
- Make fewer commits: longer triggers, larger batches, fewer writers.
- Make each commit shorter: expire snapshots, rewrite manifests, check the catalog’s capacity.
- Only then raise the retry settings, accepting longer job tails.
If the design allows it, remove the contention entirely. Have producers write to a queue that one job commits, or give independent sources their own tables and combine them with a view or a scheduled merge. Partitioning the data differently won’t help here, because every writer still swaps the same table pointer.
68. Two MERGE jobs fail intermittently with ValidationException. What is happening?
Each job discovers during commit that the other changed files, or added rows, within the scope its own condition covers. That is a logical conflict, so retrying the commit can’t fix it.
The error message names the conflicting files. The usual surprise is that the two jobs never touch the same rows. Iceberg judges conflicts by the filter of the operation, and a MERGE that matches only on a key gives it a filter covering the whole table.
ON t.id = s.id filter: whole table
ON t.region = 'EU' AND t.id = s.id filter: EU partitions
With the second condition, job A for EU and job B for US are visibly disjoint, and both can commit. The predicate must be a literal condition on the target’s partition column, so Iceberg can use it during validation.
A small reproduction shows the message. A copy-on-write UPDATE ... WHERE id >= 0 is held open for a few seconds, and an INSERT commits to the same table from a second session in the meantime. When the update tries to commit, it fails:
org.apache.iceberg.exceptions.ValidationException:
Found conflicting files that can contain records matching ref(name="id") >= 0:
[file:/tmp/iw/cp/b/data/00000-16-....parquet]
The inserted file could hold rows that the update’s filter covers, and the default serializable level refuses to ignore that. Rerunning the commit cannot help. The job has to run again against the new table state.
| Option | When it works |
|---|---|
Add partition predicates to ON |
The jobs really handle different partitions |
| Run overlapping jobs one after another, or combine them | They truly touch the same data |
| Switch to snapshot isolation | Only where ignoring concurrent appends is acceptable |
| Shorten the jobs | Reduces how often they overlap |
Snapshot isolation never lets two writers rewrite the same files. A rerun must execute the whole merge against the new table state, and moving to merge-on-read doesn’t remove conflicts on the same rows.
69. A job ends with CommitStateUnknownException. What now?
Don’t rerun the job yet, and don’t delete the files it wrote.
The exception means the commit request may or may not have reached the catalog. Both outcomes are possible, and the right action is opposite for each. So find out.
SELECT committed_at, snapshot_id, operation,
summary['spark.app.id'] AS app_id,
summary['added-records'] AS added_records
FROM demo.shop.orders.snapshots
ORDER BY committed_at DESC LIMIT 10;
Look for your job’s application ID, operation, time and record counts, or search the table for the keys it was writing. Streaming writes also record query and epoch IDs.
| What you find | What to do |
|---|---|
| The commit is there | It succeeded; continue with downstream steps |
| It isn’t there, and the catalog is healthy | Rerun |
| The catalog is still unhealthy | Wait and check again |
If the commit never happened, its files are harmless orphans that cleanup will collect later. If it did happen, those files are live, and deleting them would corrupt the table. Iceberg doesn’t retry automatically here for the same reason: it could write everything twice.
Make the next occurrence trivial to resolve. Add a batch ID to the snapshot summary with a snapshot-property. write option, merge on a key so that reruns are harmless and alert on this exception separately from ordinary failures.
70. Can two concurrent jobs insert the same key? How do you enforce uniqueness?
Yes. Iceberg enforces no primary key, so two concurrent jobs can both insert the same key. To prevent it, use a MERGE that includes WHEN MATCHED, under serializable isolation.
The simplest case needs no concurrency at all. A plain INSERT of an existing key just adds a second row, because there is no constraint to stop it:
INSERT INTO demo.c1.k VALUES (1, 'first');
INSERT INTO demo.c1.k VALUES (1, 'second');
SELECT id, v FROM demo.c1.k ORDER BY v; -- (1, first) and (1, second)
MERGE INTO demo.c1.k t USING (SELECT 2L AS id, 'only' AS v) s
ON t.id = s.id WHEN NOT MATCHED THEN INSERT *;
MERGE INTO demo.c1.k t USING (SELECT 2L AS id, 'again' AS v) s
ON t.id = s.id WHEN NOT MATCHED THEN INSERT *;
SELECT count(*) FROM demo.c1.k WHERE id = 2; -- 1
Run one after the other, the insert-only MERGE inserts key 2 only once. The danger comes when two such jobs run at the same moment, which is what the next table covers.
The surprise lies in how Spark commits different statements:
| Statement | Commits as | Second writer, serializable |
Second writer, snapshot |
|---|---|---|---|
| Append | Plain append | Succeeds | Succeeds |
MERGE with only WHEN NOT MATCHED |
Plain append | Succeeds | Succeeds |
MERGE with WHEN MATCHED as well |
Row-level operation | ValidationException if newly added files could match |
Succeeds, both insert |
An insert-only MERGE looks protective, since it checks whether the key exists. But it checks only the snapshot it started from. Two jobs can both find the key absent, and because the commit is a plain append, neither is validated against the other, whatever the isolation level.
ALTER TABLE demo.shop.orders SET TBLPROPERTIES (
'write.merge.isolation-level' = 'serializable');
With WHEN MATCHED present and serializable isolation, the second commit is checked for newly added matching files and fails. Rerun the whole statement: it now sees the existing key.
Also deduplicate the source, and remember the simplest protection is a single writer for each key range. Alert on duplicate keys whichever approach you take.
71. Does Iceberg support multi-table transactions?
Not through the table format itself. An Iceberg commit changes one table.
If a job writes an order header table and an order lines table, a reader can see the new headers before the new lines arrive, and a failure between the two commits leaves them disagreeing.
Two tables and two INSERT statements show the gap. Order 2 is written to the header table first and to the lines table second:
INSERT INTO demo.mt.order_headers VALUES (2, 'ravi');
SELECT h.order_id, h.customer, l.sku
FROM demo.mt.order_headers h
LEFT JOIN demo.mt.order_lines l ON h.order_id = l.order_id ORDER BY h.order_id;
order_id customer sku
1 asha A-100
2 ravi NULL <- header is visible, its lines are not yet
INSERT INTO demo.mt.order_lines VALUES (2, 'B-200', 1); -- second commit
2 ravi B-200
Each table has its own snapshot list: two append snapshots in each, four commits in total, with nothing linking the pairs. Every individual commit was atomic. The pair was not.
A reader that arrives between the two commits sees half of the batch.
There are ways around it, with different strengths:
| Approach | What you get |
|---|---|
| REST specification’s multi-table commit endpoint | One atomic commit, where server and engine support it |
| Catalog branches, as in Nessie | Merge a branch to publish many tables, if every client uses that catalog |
| Table branches, then fast-forward one by one | Validation before publishing, but publishing isn’t atomic |
| A shared tag or batch ID after loading | Readers choose a consistent set |
| Idempotent jobs | A rerun repairs a partial failure |
The last three don’t make the writes atomic; they give readers or operators a way to handle the gap. If readers must always see related tables agree, have them read a published set, by tag or recorded snapshot ID, instead of each table’s latest state.
When a two-table job fails halfway, the usual fix is to rerun it to completion. Rolling back the first table is an option only while nobody else has committed to it since.
72. What do you check before several engines write to one table?
Confirm that all engines use the same catalog, support the same table features and that one party is responsible for maintenance.
| Check | What goes wrong otherwise |
|---|---|
| One shared catalog | Commits made through the other are lost |
| Format version and delete types | A lagging engine fails to read, or returns wrong rows |
| Time zone and timestamp handling | The same value is read differently |
| Partition and sort hints | Some writers ignore them and damage the layout |
| Retry settings | Each engine has its own defaults |
| Table properties | They are shared but not always honoured, so test behaviour rather than settings |
| Maintenance owner | Nobody compacts, or two jobs collide; retention must outlast the slowest consumer |
Then think about who writes where. A Flink job upserting continuously and a Spark batch job merging into the same partitions will keep failing each other’s validation. Giving each table, or each partition range, a single writer removes that whole class of problem.
Test before production: have each engine append, update, delete and read, run them at the same time, compare results on one pinned snapshot and repeat the exercise after every upgrade. Before enabling a new table feature, block writers that don’t support it in the catalog.
73. What is write amplification, and how do you measure it in Iceberg?
Write amplification is how much you physically write compared with how much you logically change. Rewrite 1,000 rows to change one, and the amplification in rows is 1,000.
Snapshot summaries record what each commit added, so you can measure it without any extra tooling:
SELECT operation,
summary['added-records'] AS rows_written,
summary['deleted-records'] AS rows_replaced,
summary['added-files-size'] AS bytes_written
FROM demo.shop.status_demo.snapshots
ORDER BY committed_at;
The table from question 188 shows the effect: its copy-on-write UPDATE of a single row records 1,000 rows added and 1,000 replaced. To get the ratio, divide rows_written by the number of rows your statement actually changed, which your job has to record, because the summary doesn’t know it.
| Source of amplification | What reduces it |
|---|---|
| Copy-on-write updates of scattered rows | Merge-on-read, or clustering by the update key |
| Large files holding few changed rows | A smaller target file size |
| Compaction rewriting the same data repeatedly | Narrower scope and less frequent runs |
| Streaming small files, compacted later | Longer triggers |
Don’t chase the lowest number. Merge-on-read lowers write amplification by raising read cost until compaction pays the difference. The useful question is where you would rather spend: at write time, at read time or in maintenance.
Maintenance and performance
74. Why are small files a problem?
Small files are expensive because every file carries a fixed cost, whatever its size: a manifest entry, a request to open it and a footer to parse.
Compare 10 GB stored two ways. As 20 files of 512 MB, planning handles 20 entries and the scan opens 20 files. As 10,000 files of 1 MB, planning handles 500 times as many entries, and the job spends much of its time opening files instead of reading rows.
| Where it hurts | Why |
|---|---|
| Planning | More manifest entries to read and hold in memory |
| Scans | Time goes into opening files and reading footers |
| Storage | Compression works poorly on little data |
| Object store | Requests are charged and throttled per call |
| Merges | More files to join and rewrite |
Here is the effect on a real table. Sixty INSERT statements of 100 rows each, on a two-core local Spark, produce this:
SELECT count(*) AS files, round(avg(file_size_in_bytes)/1024,1) AS avg_kb
FROM demo.sf.events.files;
SELECT count(*) AS manifests FROM demo.sf.events.manifests;
CALL demo.system.rewrite_data_files(table => 'sf.events',
options => map('min-input-files', '2'));
CALL demo.system.rewrite_manifests('sf.events');
| Step | Data files | Average file size | Manifests |
|---|---|---|---|
| After 60 inserts | 120 | 1.7 KB | 60 |
After rewrite_data_files |
1 | 10.4 KB | 61 |
After rewrite_manifests |
1 | 10.4 KB | 1 |
Two lessons are in those numbers. Every commit wrote at least one file per write task, so 60 commits made 120 files for only 6,000 rows. And compaction fixed the files but not the metadata: the manifest count went up by one, because the rewrite is itself a commit. Small files hurt both layers, and each layer has its own repair job.
The usual causes are frequent commits, partitioning that is too fine, many write tasks with little data each and the none distribution mode.
To measure it, compare the average file size in the files table with the target and count files per partition. There is no fixed size that counts as small; many files far below target is the signal.
Fix both ends. rewrite_data_files combines the existing files, while a longer streaming trigger, coarser partitioning or hash distribution stops new ones appearing. Don’t expect storage to shrink at once: old snapshots still reference the original files, so space is freed only when those snapshots expire.
75. How does compaction work?
The rewrite_data_files procedure compacts a table. It reads selected files, writes better-sized replacements and commits the swap as a replace snapshot, so query results don’t change.
It doesn’t rewrite everything. A file is a candidate when it is below 75% or above 180% of the target size, or when its deletes cross a threshold. Candidates are grouped by partition, and a group is rewritten if it meets any of these:
- it has at least five files
- it holds more than one file totalling over the target size
- it exceeds the maximum file size
- it contains a file over a delete threshold
CALL demo.system.rewrite_data_files(
table => 'shop.orders',
options => map('min-input-files', '2'));
By this point orders has files from two partition specs, and the result is instructive. The procedure reports 5 data files rewritten and far more than 5 added, anywhere from about twenty to a hundred depending on Spark’s parallelism.
That happens because compaction writes under the current spec. The five old files, one per day, are split into the day and customer bucket partitions introduced in question 35. Compaction fixes file size within the current layout; it can’t make a fine layout coarse.
| Option | Effect |
|---|---|
where |
Limits the scope |
strategy => 'sort' |
Re-clusters the data |
rewrite-all |
Ignores the selection rules |
partial-progress.enabled |
Commits group by group |
max-concurrent-file-group-rewrites |
Parallelism, default 5 |
delete-file-threshold |
Delete-count trigger, effectively off by default |
delete-ratio-threshold |
Delete-ratio trigger, 0.3 |
The commit fails if a rewritten file was removed or deleted from in the meantime, and new files keep the starting sequence number so that later equality deletes still apply. If the procedure rewrites nothing, no group met a trigger.
76. A streaming job creates thousands of small files a day. What do you change?
The number of files is roughly files per commit multiplied by commits per day, so reduce both, then compact what remains.
200 write tasks x 1 partition x 1,440 commits per day = 288,000 files per day
Either factor can be changed:
| Change | Reduces |
|---|---|
| Longer trigger, as long as latency allows | Commits per day |
hash distribution with fewer shuffle partitions, or adaptive coalescing |
Files per commit |
| Coarser partitioning | Files per commit |
| Keeping late events from spreading over many partitions | Files per commit |
Moving from a 1 minute to a 5 minute trigger alone divides 288,000 files by five. Combine it with 10 files per commit and the same stream writes under 3,000 files a day. The fanout writer avoids a sort at a cost in memory, but by itself doesn’t reduce file counts.
For what is already written, compact partitions older than the active window with partial progress, then expire snapshots so storage follows. This query shows files added per hour and confirms whether the change worked:
SELECT date_trunc('hour', committed_at) AS hour, count(*) AS commits,
sum(CAST(summary['added-data-files'] AS INT)) AS files_added
FROM demo.shop.orders.snapshots
GROUP BY 1 ORDER BY 1 DESC;
If the latency requirement forbids a longer trigger, compact continuously, or keep a hot append table for fresh data apart from the optimised table that most consumers query.
77. What does expire_snapshots do?
expire_snapshots removes old snapshots from table metadata and deletes the files that no remaining snapshot references. This is the step that actually frees storage.
Updates and compaction never delete anything by themselves. A replaced file stays because an earlier snapshot still points at it. Only when the last snapshot referencing it expires can it be removed.
Every branch and tag head is kept. On each branch, older snapshots survive while they are younger than the age limit or within the minimum count.
| Setting or argument | Role |
|---|---|
history.expire.max-snapshot-age-ms |
Age limit, five days by default |
history.expire.min-snapshots-to-keep |
Minimum count, one by default |
older_than, retain_last |
Override both for one run |
snapshot_ids |
Expire named snapshots |
stream_results |
Avoids collecting a huge delete list on the driver |
max_concurrent_deletes |
Deletes in parallel |
clean_expired_metadata |
Drops unused specs and schemas |
CALL demo.system.expire_snapshots(
table => 'shop.orders',
older_than => TIMESTAMP '2030-01-01 00:00:00',
retain_last => 5);
The date lies far in the future only so that everything on a test table qualifies. After the compaction in question 75, this run reports 16 data files, 9 manifests and 4 manifest lists deleted.
Expiry is permanent. Time travel, rollback and incremental reads can no longer reach the removed history, so set retention from how long you need to recover from a mistake, not only from storage cost. If a run deletes nothing, the files are still held by a retained snapshot, often through a forgotten branch or tag, or the snapshots are too young.
78. What are orphan files, and how do you remove them?
Orphan files are files under the table location that no metadata references. Failed or killed jobs leave them behind, and remove_orphan_files finds and deletes them.
A writer creates data files before it commits. If the job dies in between, the files exist but no snapshot ever mentions them. Expiry can’t clean them, because it only considers files that some snapshot referenced.
The procedure lists the table location, collects every file referenced by the metadata of any retained snapshot and treats the rest as orphans once they are older than a limit. The limit defaults to three days and can’t be set under 24 hours, because a file from a write still in progress looks exactly like an orphan.
CALL demo.system.remove_orphan_files(table => 'shop.orders', dry_run => true);
Start with dry_run, which lists candidates without deleting them; on a clean table the list is empty. Use location to narrow the search.
A leftover file is easy to simulate. A data file was copied into a table’s data directory without a commit, and its modification time set to three days ago. A dry run lists it, and the real run deletes it:
CALL demo.system.remove_orphan_files(table => 'c2.t',
older_than => TIMESTAMP '2026-11-30 00:00:00', dry_run => true);
orphan_file_location
<warehouse>/c2/t/data/orphan-from-failed-job.parquet
After the real run, two data files remain: the two that the table’s snapshots reference. The procedure also protects you from a short age limit. With older_than less than 24 hours ago, it refuses to run:
IllegalArgumentException: Cannot remove orphan files with an interval less than 24 hours.
Executing this procedure with a short interval may corrupt the table if other operations
are happening at the same time.
The main danger is path matching. If metadata records files with one URI form, say s3a://, and the listing returns s3://, live files appear unreferenced. equal_schemes and equal_authorities declare such variants equivalent, and prefix_mismatch_mode defaults to ERROR so that a mismatch stops the run. Switching it to DELETE without understanding the mismatch can destroy the table. Also make sure no other table shares the location.
79. When do you rewrite manifests?
Rewrite manifests when planning is slow because the table has many small manifests, or because their entries are spread across partitions so that none can be skipped.
Manifests accumulate in write order. After weeks of streaming, a manifest may list a few files from many days, and a query for one day has to open most of them.
CALL demo.system.rewrite_manifests('shop.orders');
before m1 [day1, day5, day9] m2 [day2, day5, day8] filter day5 reads both
after m1 [day1, day2] m2 [day5] m3 [day8, day9]
The procedure reads the existing entries, sorts and groups them by partition, writes reasonably sized manifests and commits a new snapshot. Data files are untouched. On the example table it replaces two manifests with one:
rewritten_manifests_count added_manifests_count
2 1
Iceberg already merges manifests during many commits when commit.manifest-merge.enabled is true. Streaming writes use fast appends by default, which skip that merging, so streaming tables benefit most from a scheduled rewrite.
Look before you run it: the manifests table shows their number, size and partition ranges. Compact small data files first, since compaction changes the manifest entries anyway. A rewrite also invalidates cached plans for the table and can conflict with concurrent commits.
If planning is still slow afterwards, the manifests weren’t the whole problem. Choose sort_by to match the column queries filter on, because manifests grouped by a column nobody filters on can’t be skipped. Then check:
| If planning is still slow, check | Remedy |
|---|---|
| Do filters translate into partition predicates? | Change the query or the partitioning |
| Is the metadata file very large? | Expire snapshots |
| Many delete files? | Compact |
| Is streaming fragmenting manifests again? | Rewrite on a schedule, or use merge appends |
| Driver garbage collection? | More driver memory, or distributed planning |
| Slow even on tiny tables? | The catalog |
use_caching caches data inside the rewrite job itself and does nothing for the planning time of later queries.
80. Why do metadata files pile up, and how do you stop it?
Metadata files pile up because every commit writes a new metadata.json, and by default the old ones are never deleted.
A job committing once a minute creates 1,440 of them a day. Two table properties delete earlier files after each commit and keep a fixed number, 100 by default:
ALTER TABLE demo.shop.orders SET TBLPROPERTIES (
'write.metadata.delete-after-commit.enabled' = 'true',
'write.metadata.previous-versions-max' = '50');
Here the retained count is lowered to 50. The cleanup only covers files listed in the metadata log, so files that dropped out of the log before you enabled it remain until orphan removal collects them.
The two properties are easy to compare on two tables with eight commits each. One uses the defaults, and the other sets write.metadata.delete-after-commit.enabled and write.metadata.previous-versions-max to 3:
| Table | metadata.json files after 8 inserts |
|---|---|
| Defaults | 9 |
| Cleanup on, 3 previous versions | 4 |
The first table keeps one file for the creation and one for each insert. The second keeps the current file and the three before it.
Count is one problem and size is another. Each metadata file lists every retained snapshot, along with all schemas and properties, so it grows as history grows.
| What accumulates | What cleans it |
|---|---|
Old metadata.json files |
The two properties above |
| Snapshot entries and manifest lists | expire_snapshots |
| Manifests | rewrite_manifests, merging at commit time, and expiry |
On a busy table without expiry, every commit rewrites an ever larger JSON file. Commits get slower, which widens the window for conflicts with other writers. On an old table, check the metadata file size and snapshot count, expire snapshots first and then enable the cleanup. Deleting old metadata files doesn’t remove time travel, because the current file still lists the retained snapshots.
81. What maintenance does every Iceberg table need, and in what order do you run it?
Four jobs: compact data files, rewrite manifests, expire snapshots and remove orphan files. Run them in that order, because each one prepares the ground for the next.
| Job | What it does | What it leaves for the next job |
|---|---|---|
rewrite_data_files |
Combines small files and folds in delete files | The old files are still referenced by older snapshots |
rewrite_manifests |
Regroups manifest entries so planning reads fewer files | Replaced manifests wait for expiry |
expire_snapshots |
Removes old snapshots, and deletes the files only they referenced | Files that no snapshot ever referenced |
remove_orphan_files |
Deletes files in the table location that no metadata mentions | Nothing |
CALL demo.system.rewrite_data_files(table => 'shop.orders');
CALL demo.system.rewrite_manifests(table => 'shop.orders');
CALL demo.system.expire_snapshots(table => 'shop.orders', retain_last => 10);
CALL demo.system.remove_orphan_files(table => 'shop.orders');
Tables that still use position delete files, which are written by merge-on-read changes before format version 3, need a fifth job. rewrite_position_delete_files compacts them and drops positions that no longer point at live rows, and it belongs after rewrite_data_files, which already folds in many deletes. Without it, every read has to apply an ever longer list of delete files and the benefit of merge-on-read fades.
The order follows from what each job can see. Compaction doesn’t delete anything: the files it replaces stay in storage until every snapshot that refers to them has expired. Expiry therefore has to come after compaction to release them. If you expire first, the next cycle has to wait for the replaced files. Orphan removal comes last because it only deals with files that no snapshot ever referenced, such as those left by failed jobs, and it works from the metadata that expiry has just trimmed.
Two settings protect you. Retention, set with history.expire.max-snapshot-age-ms and history.expire.min-snapshots-to-keep, decides how far back you can time travel or roll back, so agree it with the data owners before it shortens. The age limit on orphan removal, three days by default, keeps the job away from files that a running writer has created but not yet committed.
How often to run each job depends on the table. A streaming table commits constantly, so it needs frequent compaction and expiry. An idle table needs little, and a table nobody changes needs none of them. Question 84 shows how to decide this from table metadata for a large estate, and question 82 how to compact next to active writers.
82. How do you run compaction alongside active writers, such as continuous streaming upserts?
Limit compaction to data that has stopped changing and let it commit in pieces, so that a conflict costs little.
Whether compaction conflicts depends on what the other writer does to the files being rewritten:
| Concurrent operation | Conflicts with compaction? |
|---|---|
| Append | Never |
| Copy-on-write update of a file being compacted | Yes |
| New position deletes against such a file | Yes |
| New equality deletes | No; they still apply afterwards, because the data keeps its sequence number |
Here is the second row of that table, run against a real table. A copy-on-write UPDATE is held open for a few seconds, and rewrite_data_files compacts the same four small files from another session in the meantime. Compaction commits first, so the update’s commit fails:
org.apache.iceberg.exceptions.ValidationException:
Missing required files to delete: file:/tmp/iw/cp/a/data/00000-2-....parquet,
file:/tmp/iw/cp/a/data/00000-1-....parquet, file:/tmp/iw/cp/a/data/00000-3-....parquet, ...
The update had planned to rewrite four files that compaction had already replaced. Two details are worth remembering. The writer that loses is the one that commits second, which is usually the long job. And both jobs must use separate Spark sessions: sharing one session across threads gives a different error, Runtime file filtering is not possible: the table has been concurrently modified.
In practice, new data usually arrives in recent partitions. A compaction restricted with where to yesterday and earlier rarely collides with today’s writers. Enable partial-progress.enabled so that file groups commit separately, keep the groups small and avoid running during heavy merge jobs.
Partial progress changes what success means. You get more snapshots, and the job can finish with only some groups applied, with failures logged. A green job therefore doesn’t prove the table was compacted. Compare file counts before and after and read the procedure’s output.
If compaction keeps failing against streaming upserts, there are more options than partial progress:
| Option | What it costs |
|---|---|
| Run in quiet windows between batches | Limited time to work |
| Pause the stream briefly | Guaranteed progress, delayed data |
| Append raw changes and merge periodically | Less freshness, far fewer conflicts |
| Compact between micro-batches in the same application | Removes the race, adds latency |
If updates reach every partition, there are no settled ones to compact safely, and the real problem is the layout: partition so that most changes fall in recent data.
When compaction and ingestion keep colliding, let compaction lose. Rerunning it costs compute, while a failed or delayed ingestion costs freshness.
83. How do you stop maintenance jobs from overlapping with each other and with writers?
Iceberg has no maintenance lock, so you control overlap from outside: through the scheduler, through the scope of each job and through the ordering of the jobs.
A collision isn’t a correctness problem. Every commit is validated, so a compaction that loses a race fails or is retried and the table stays valid. What you pay is wasted compute, failed runs and noisy alerts. The jobs that can do real harm are the ones that delete: expiry with a short retention, and orphan removal with a short age limit.
One owner, one ordered run per table.
Several habits keep the overlap down:
- One run per table at a time. In Airflow, set
max_active_runs=1on the DAG, or give maintenance tasks a pool with one slot. Where several systems can start jobs, take a lock keyed on the table name in a store such as DynamoDB or Redis, with an expiry so that a crashed job doesn’t hold it forever. - One DAG per table for the whole sequence. Run compaction, manifest rewrite, expiry and orphan removal in order (question 81), so the steps can’t start each other’s work twice.
- Narrow the scope. Compact only the partitions that have collected small files, using
where. The streaming writer then touches new partitions and the compaction touches old ones, and they rarely conflict (question 82). - Keep the safety margins. The orphan age limit, three days by default, protects files from a writer that is still running. Retention should exceed your longest query and the time people need to notice a wrong result.
- Retry sensibly. Let a failed run retry later, as a rewrite that lost to a delete on the same files will usually succeed on a fresh plan.
Watch the outcomes too: the commit failures per job, and how often a job selects nothing. A table whose jobs keep losing races needs a different schedule more than it needs more retries (question 84).
84. How would you automate maintenance for thousands of tables?
Build a control plane that reads each table’s metadata, scores the work worth doing and runs it within a compute budget, skipping tables that haven’t changed and have no problem.
Maintenance driven by evidence.
Running every maintenance job on every table nightly wastes most of the compute, because most tables need nothing. The signals are cheap to collect:
SELECT count(*) AS files,
sum(CASE WHEN file_size_in_bytes < 134217728 THEN 1 ELSE 0 END) AS small_files,
sum(CASE WHEN content <> 0 THEN 1 ELSE 0 END) AS delete_files,
round(avg(file_size_in_bytes) / 1048576, 2) AS avg_mb
FROM demo.shop.orders.files;
| Score higher | Score lower |
|---|---|
| Frequently queried partitions with many small files | Tables nobody reads |
| Rapidly growing delete counts | Tables with no new snapshot |
| Tables with tight latency targets | Rewrites that move a lot of data to remove few files |
A registry gives each table an owner, a service tier and a retention policy. Workers take jobs from a queue with a concurrency limit, compact only qualifying partitions using where, run expiry and orphan removal according to each policy and never run two maintenance jobs on one table at once.
Record values before and after each job. That history shows whether the spend improved anything, and exposes tables whose jobs keep selecting nothing or losing commit conflicts.
85. How do you stop rewrite_data_files from running out of memory on very large tables?
Limit how much is processed at once: smaller file groups, fewer concurrent groups, a where clause and partial progress.
CALL demo.system.rewrite_data_files(
table => 'shop.orders',
where => 'order_ts < TIMESTAMP \'2026-11-04 00:00:00\'',
options => map(
'max-file-group-size-bytes', '10737418240',
'max-concurrent-file-group-rewrites', '2',
'partial-progress.enabled', 'true',
'partial-progress.max-commits', '10'));
| Option | Default | Controls |
|---|---|---|
max-file-group-size-bytes |
100 GB | Data in each unit of work |
max-concurrent-file-group-rewrites |
5 | Groups running at once |
partial-progress.max-commits |
10 | Maximum commits when partial progress is on |
partial-progress.max-failed-commits |
Same as above | Failures tolerated |
With the defaults, five groups of up to 100 GB may be in flight, which is a lot for a modest cluster. The where clause shrinks the job further, and finished groups commit early with partial-progress.enabled, so a later failure doesn’t discard them.
On the small example table, this call reports zero files rewritten, which is expected: no group in that date range met a trigger.
Sort and Z-order rewrites shuffle the data and need much more memory and disk than bin-pack; shuffle-partitions-per-file splits each output file’s work over more partitions. Many delete files add memory to every task. A partial-progress job can end with only part of its selection done, so check failed_data_files_count and rerun. Changing min-input-files affects which groups qualify, not how much memory they use.
86. A table has 100 million files. How do you bring it under control?
First find out whether the files are live or historical, and where they sit. Then compact in bounded slices, expire history and stop the source of new small files.
The arithmetic shows the size of the problem. If those files hold 100 TB, the average is about 1 MB, and the same data in 512 MB files would be roughly 200,000 files.
Fix the source first, then clean in slices.
- Take an inventory. Count live files per partition in
partitions, and compare with all files reachable from any snapshot. - Stop the growth. Fix the writers: trigger intervals, partition scheme, distribution mode.
- Compact in slices. One partition range at a time with
where, partial progress and a concurrency limit, starting with the partitions queries read most. - Rewrite manifests so planning can skip them.
- Expire snapshots, then remove orphan files, to release storage.
| Mistake | Why it hurts |
|---|---|
| Compacting the whole table in one job | Runs for days, fails and conflicts with writers |
| Skipping the writer fix | New files arrive faster than you remove old ones |
| Expiring first | Frees little while the live files are the problem |
| Measuring only job success | A job can succeed while selecting nothing |
If the partitioning itself created the files, evolve it before compacting, or compaction will faithfully preserve the fragmentation, as the example in question 75 shows. Track planning time, files per query and files per partition after each slice to prove it is working.
87. How do you check the health of a table?
Query the table’s metadata tables for file sizes, delete files, manifests and snapshots, and watch how those numbers change over time.
SELECT content, count(*) AS files,
round(avg(file_size_in_bytes) / 1048576, 2) AS avg_mb,
sum(record_count) AS records
FROM demo.shop.orders.files
GROUP BY content;
SELECT count(*) AS manifests, sum(length) AS manifest_bytes
FROM demo.shop.orders.manifests;
SELECT count(*) AS snapshots, min(committed_at) AS oldest
FROM demo.shop.orders.snapshots;
On the small example table the average data file size rounds to 0 MB, which on a real table would make it an obvious compaction candidate. In the first query content 0 means data, 1 position deletes and 2 equality deletes.
| Signal | What it suggests |
|---|---|
| Average file size falling | Compact, and fix the writers |
| Delete files or delete records growing | Compact with delete thresholds |
| Many manifests and slow planning | Rewrite manifests |
| Very old, long snapshot list | Expire snapshots and check branches and tags |
| One partition far larger than the rest | Data skew |
A single reading tells you little: 200 manifests may be fine for one table and a problem for another. Run these on a schedule, store the results and alert on trends. Add evidence from the query side too, such as planning time, files scanned and commit failures, which tells you whether the layout is actually hurting anyone.
88. Queries have slowed steadily over three weeks with no data growth. What do you do?
Start by finding whether the extra time is spent planning or executing, then use the metadata tables to see what changed.
Flat data volume is a strong clue. The same rows are taking longer, so their arrangement has probably changed.
| Symptom | Likely cause | Fix |
|---|---|---|
| Long gap before the first task | Too many manifests or snapshots | Rewrite manifests, expire snapshots |
| Many very short tasks | Small files | Compaction |
| Slow tasks on a table that is updated | Delete files building up | Compact deletes |
| Far more files read than expected | Overlapping column bounds | Sort the data |
| One task much slower than the rest | Skew | Address the skewed key |
The query shows which partitions hold the most files:
SELECT partition, file_count, record_count
FROM demo.shop.orders.partitions
ORDER BY file_count DESC LIMIT 10;
Then look for what started three weeks ago: more frequent commits, a new writer, a maintenance job that was disabled or silently failing, or a new query pattern. Snapshot summaries plotted over time usually show the date it began.
Compaction repairs today’s state, but without fixing the cause and scheduling maintenance the slowdown returns. If compaction changes nothing, check that it selected any files and didn’t fail.
89. A query waits a minute before the first task starts. Where do you look?
A long wait before the first task is planning time, so examine metadata rather than executors.
Before any task can start, the driver must load the table, read the manifest list and the relevant manifests and build the delete index. Each of those can be the slow part:
| Cause | How it shows |
|---|---|
| Slow catalog call | Delay even on tiny tables |
| Many retained snapshots | A very large metadata JSON file |
| Thousands of manifests | A long manifest list to process |
| Overlapping partition ranges | No manifest can be skipped |
| Many delete files | A large delete index |
| Driver short of memory | Heavy garbage collection |
| Filter that can’t use the partitioning | Every manifest is read |
SELECT count(*) AS manifests, round(sum(length) / 1048576, 2) AS total_mb
FROM demo.shop.orders.manifests;
Rewrite manifests so that they cluster by partition, expire snapshots, compact files and commit less often. For very large tables, give the driver more memory or distribute planning across the cluster. More executors alone won’t help while planning runs on the driver.
Measure planning time on the same query before and after each change. Run it more than once with that in mind, since session caching can make a second run fast and look like an improvement.
90. Storage keeps growing although the row count is flat. Why?
Old snapshots are keeping old files alive. Every compaction, update or overwrite writes new files while earlier snapshots still reference the ones they replaced.
So the live data can stay the same size while history grows behind it. Measure the two separately:
-- both include data files and delete files
SELECT sum(file_size_in_bytes) AS live_bytes FROM demo.shop.orders.files;
SELECT sum(file_size_in_bytes) AS reachable_bytes FROM (
SELECT DISTINCT file_path, file_size_in_bytes FROM demo.shop.orders.all_files
) f;
After the earlier examples, the reachable figure for orders is larger than the live one. The difference is history. DISTINCT matters because all_files lists a file once for every manifest that mentions it.
Work through the causes in order:
- Check the oldest snapshot and the snapshot count. Is expiry running and succeeding?
- Look in
refsfor a forgotten branch or tag holding old state. - Compare live and reachable bytes.
- Dry run orphan removal to find files from failed jobs.
- Check storage outside Iceberg: object versioning, incomplete multipart uploads and backups.
| Finding | Meaning |
|---|---|
| Reachable far above live | History is the cost: shorten retention or drop references |
| Reachable small, bucket large | Orphan files or old object versions |
Shortening retention reduces how far back mistakes can be undone, so agree it with the data owners. On tables that commit very often, metadata files add to the total as well.
91. A CDC table gets slower every hour. How do you diagnose it?
A change data capture table that slows hour by hour is usually accumulating delete files. Find which kind is growing, compact the partitions that change and commit less often.
What three merges cost on one table.
Every batch of changes adds small data files plus deletes marking the old versions. Queries must read all of them, so cost grows with the number of batches even though the row count barely moves.
SELECT content, count(*) AS files, sum(record_count) AS records
FROM demo.shop.orders.files
GROUP BY content;
| What the query shows growing | Meaning |
|---|---|
content 1 |
Position deletes, typically from Spark merges |
content 2 |
Equality deletes, typically from Flink upserts |
content 0 count rising, size falling |
Small files from each batch |
Schedule rewrite_data_files with a delete threshold on the active partitions, remove dangling deletes and expire snapshots. A longer trigger creates fewer delete files to begin with, and equality deletes need the most frequent compaction.
Compaction competes with the stream, so use partial progress or compact partitions slightly behind the active one. Alert on delete records as a share of data records and on compaction failures. If reads dominate, changes fall in few files and batches are large and rare, copy-on-write may be the better mode. See CDC into Iceberg.
92. A Trino query filtered on the partition column still scans tens of thousands of files. How do you diagnose it?
Work outwards from the table: count the files that actually match, check which partition spec they use and verify that the filter reaches the Iceberg scan.
SELECT spec_id, partition, count(*) AS files
FROM demo.shop.orders.files
GROUP BY spec_id, partition
ORDER BY files DESC
LIMIT 10;
Trino’s "orders$files" and "orders$partitions" tables give the same information.
| What you find | Meaning |
|---|---|
| The partition really holds that many files | Compact it |
| Files under an old or unpartitioned spec | Leftovers from partition evolution |
| The partition column is wrapped in a function or cast | The filter may not push down |
| A literal of a different type or time zone | The range is wider than intended |
| The filter arrives through a join | It depends on dynamic filtering |
| A second filter on an unsorted column | Its bounds overlap everywhere; cluster by it |
Use EXPLAIN to see which constraint reaches the table scan, and EXPLAIN ANALYZE to see what was actually read.
Then run one decisive test: the same query with a plain literal filter on the raw column. If the file count drops sharply, the table is fine and the problem is in how the query, or the view that generated it, expresses the filter.
93. How do you fix driver out-of-memory errors during scan planning?
Reduce the amount of metadata the driver has to hold, or spread planning across the cluster.
The typical case is a scan covering a very large number of files, each carrying statistics for many columns, some with delete files attached. All of that is assembled in driver memory.
Hold less metadata, or let the executors read it.
| Action | Why it helps |
|---|---|
| Filter on partition and sort columns | Fewer manifests are loaded |
| Compact data files | Fewer file entries |
| Collect metrics only for filter columns | Smaller entries |
| Compact delete files | Smaller delete index |
| Rewrite manifests | More can be skipped |
read.data-planning-mode set to distributed |
Executors read manifests; the default is auto |
| Increase driver memory | More headroom |
First confirm that planning is what fails: the error occurs before any scan task starts. An out-of-memory error during the scan or a later shuffle needs a different fix.
Distributed planning moves the reading of manifests to executors, but the results still return to the driver, so spark.driver.maxResultSize can become the next limit. Reducing metadata is therefore the lasting fix, and the settings are what keep you running while you do it. Question 89 covers planning that succeeds but is slow.
94. Commit latency has suddenly increased. What do you investigate?
Split a commit into its parts: writing metadata, asking the catalog to swap, and retrying after losing. Find which one grew.
| Part | Grows when | Check |
|---|---|---|
| Writing the metadata file | Many retained snapshots make it large | Metadata file size, snapshot count |
| Writing and merging manifests | Many small manifests are merged during commits | Manifest count |
| Catalog request | Slow service or backing database | Catalog latency and errors |
| Retries | More writers competing | Attempts per commit |
| Storage requests | Throttling | Storage error rates |
The first row of that table is easy to measure. A table committed 150 times, with no snapshot expiry, has 151 metadata.json files, and the latest one is 147,826 bytes because it lists all 150 snapshots. After expiring everything except the last snapshot and committing once more, the latest file is 12,034 bytes:
CALL demo.system.expire_snapshots(table => 'ml.t',
older_than => TIMESTAMP '2030-01-01 00:00:00', retain_last => 1);
snapshots latest metadata.json
after 150 commits 150 147,826 bytes
after expiry + 1 commit 2 12,034 bytes
Every commit has to write that file again. In this small example the difference is about 136 KB, but on a table with years of history and wide schemas it is much larger, and it is paid on every commit.
Commit reports, described in question 181, give attempts and total duration per commit, which separates contention from slowness quickly. Many attempts with each one fast means too many writers. One slow attempt means metadata, catalog or storage.
Then ask what changed on the day it started: a new writer, a shorter trigger, expiry that stopped running or a catalog upgrade.
The usual fixes follow from the cause: expire snapshots and enable metadata cleanup, rewrite manifests, commit less often, reduce competing writers or give the catalog more capacity. Raising retry limits comes last, because it hides the latency instead of removing it, and a slow commit widens the window in which the next conflict happens.
95. How do you tune read performance on an Iceberg table?
Remove the largest source of wasted reading first. The usual order is partitioning, sort order, file sizes, delete cleanup, manifests and then statistics.
Biggest win first.
| Step | What improves |
|---|---|
| Partitioning that matches filters | Whole groups of files are skipped |
| Sorting or Z-order | Column bounds become selective |
| Larger files, fewer deletes | Less overhead per file |
| Rewritten manifests | Faster planning |
| Column metrics and table statistics | Better skipping and join plans |
Bloom filters, set with write.parquet.bloom-filter-enabled.column.<name> |
Point lookups |
| Split size and vectorised reads | Fine tuning, last |
Work from one real slow query. Record the files scanned, bytes read, planning time and the plan. Change one thing, run it again and compare. Changing several settings at once leaves you unable to say which helped.
If every file in the table is still being read, the filtered column is neither partitioned nor clustered, and no engine setting will fix that. Features such as dynamic filtering, storage-partitioned joins and aggregate pushdown vary by engine and version, so confirm them in the plan.
96. When does bin-pack compaction make queries slower?
Bin-pack compaction slows queries when it merges files that each held a narrow range of a filter column, producing files whose ranges are so wide that nothing can be skipped.
Merging by size can destroy file skipping.
Before compaction, a query for customer 905 read only file B. Afterwards it must read the combined file, including all the unrelated data. Bin-pack looks only at file sizes; it combines whatever fits, without regard to what values the files contain.
| Strategy | What it does | Relative cost |
|---|---|---|
| Bin-pack | Combines by size | Lowest, little shuffle |
| Sort | Re-sorts so each file has a narrow range | Shuffle and sort |
| Z-order | Clusters on several columns together | Highest |
The damage shows on tables that were deliberately sorted, or whose arrival order happened to cluster a column. The usual metrics look better, with fewer files and faster planning, while each query reads more bytes.
Use bin-pack for tables that are read in full or by whole partitions. Where speed depends on column bounds, use the sort strategy, restricted with where to partitions that have stopped changing. Judge the outcome by bytes scanned per query, not by file counts.
97. How does the Parquet row group size affect pruning and object store reads?
The row group size controls how precisely a reader can skip inside a Parquet file and how a file is split into tasks. It doesn’t affect manifest pruning, which works on whole files.
A Parquet file is divided into row groups, each with its own column statistics. A reader fetches only the column chunks it needs, using ranged requests, and skips groups whose statistics rule them out. Iceberg records the split offsets so that tasks can divide a large file at group boundaries.
| Smaller row groups | Larger row groups | |
|---|---|---|
| Skipping | Finer | Coarser |
| Footer metadata and requests | More | Fewer |
| Compression and encoding | Worse | Better |
| Writer memory per open file | Less | More |
The property is write.parquet.row-group-size-bytes, 128 MB by default.
Two interactions matter more than the number itself. A wide table fits relatively few rows into each group, and a writer with many partitions open multiplies the memory for each. And statistics only help if values are clustered: on randomly ordered data, every row group covers nearly the whole range, whatever its size. Sort first, then measure before changing the size.
98. How do you optimise a table with hundreds of columns when queries read only a few?
Parquet already reads only the columns a query selects. Your job is to control the costs that grow with width: statistics, footers, write memory and rows per row group.
| Problem | What to do |
|---|---|
| Filter column beyond the first 100 can’t skip files | Set write.metadata.metrics.column.<name> for it |
| Large manifests from many column statistics | Default the metrics mode to none or counts, enable only filter columns |
| Users selecting every column | Publish views that expose what they need |
| High write memory | Limit the partitions each write task handles |
| Hundreds of sparse, changing attributes | Group them into a struct, map or variant |
The metrics point catches people out. Bounds are collected for the first 100 columns by default, so if the column everyone filters on is number 240, every query reads every file, and nothing reports a problem.
You can see the effect of the metrics settings directly. With write.metadata.metrics.default set to none, the table keeps no bounds at all. Adding write.metadata.metrics.column.c2 = full brings them back for that one column:
CREATE TABLE demo.q.m_col (id BIGINT, c1 BIGINT, c2 BIGINT) USING iceberg
TBLPROPERTIES ('write.metadata.metrics.default' = 'none',
'write.metadata.metrics.column.c2' = 'full');
INSERT INTO demo.q.m_col SELECT id, id, id FROM range(100);
SELECT readable_metrics.c1.lower_bound AS c1_min, readable_metrics.c1.upper_bound AS c1_max,
readable_metrics.c2.lower_bound AS c2_min, readable_metrics.c2.upper_bound AS c2_max
FROM demo.q.m_col.files;
c1_min c1_max c2_min c2_max
NULL NULL 0 49 <- the column with metrics keeps its bounds
NULL NULL 50 99 <- the other columns have none
A filter on c1 cannot skip either file, because nothing is known about its range. A filter on c2 > 60 skips the first file. The two files are there because the demo ran with two write tasks.
Sort on the common filter columns so that their bounds are selective. If a set of rarely used columns makes every rewrite expensive, you can move them to a second table with the same key. That trades rewrite cost for a join, so only split columns that are genuinely used apart.
99. ZSTD or Snappy for Iceberg data files?
ZSTD is the default for new Iceberg tables and usually produces noticeably smaller files, while Snappy uses less CPU. On object storage, where reading over the network is often the bottleneck, smaller files tend to win.
How much smaller depends entirely on the data. For one synthetic table of a million rows with repetitive strings, ZSTD wrote about 1.9 MB and Snappy about 6.0 MB. Data that is already compressed or highly random shows far less difference.
| ZSTD | Snappy | |
|---|---|---|
| File size | Smaller | Larger |
| Write CPU | Higher | Lower |
| Tunable level | Yes | No |
| Iceberg default for new tables | Yes | No |
ALTER TABLE t SET TBLPROPERTIES ('write.parquet.compression-codec' = 'snappy');
To decide, write the same representative sample with both codecs and record file size, write time and the run time of real queries on your engines. Storage cost is the easy part to measure; query time is the one that usually matters.
Changing the property affects only files written afterwards. Existing files keep their codec until compaction or another rewrite replaces them, and a table holding both is normal, since each file records its own compression.
100. How are files turned into Spark tasks?
Iceberg builds Spark tasks by splitting large files into pieces and packing small pieces together until each task has about the target amount of data.
A large file is divided at Parquet row group boundaries. The pieces are then combined into bins that become tasks.
| Setting | Default | Role |
|---|---|---|
read.split.target-size |
128 MB | Target bytes per task |
read.split.open-file-cost |
4 MB | Minimum weight of any file |
read.split.planning-lookback |
10 | Bins kept open while packing |
The open-file cost protects against tiny files. A 20 KB file still takes time to open, so it is counted as if it were 4 MB:
target 128 MB, open cost 4 MB
file of 20 KB counts as 4 MB -> at most about 32 tiny files per task
Without that floor, one task could receive thousands of files and spend its life opening them. Spark may also adjust the split size to the size of the scan and the available parallelism, and the split-size read option overrides it for a single query.
Task counts therefore reflect file layout. A huge number of very short tasks suggests tiny files or a small split size. A few long tasks on a mostly idle cluster suggest a large split size or files that can’t be split. Remember that these byte figures ignore delete files: a task with many deletes to apply can be much slower than its size suggests.
101. What is a storage-partitioned join?
A storage-partitioned join lets Spark join two tables partition by partition, with no shuffle, because both are partitioned compatibly on the join keys.
Normally Spark has to move rows between executors so that matching keys meet. For two large tables that shuffle is often the most expensive part. If both are already bucketed on the key the same way, bucket 0 of one can only match bucket 0 of the other.
Matching buckets meet without a shuffle.
It needs all of these:
spark.sql.sources.v2.bucketing.enabled- the Iceberg setting
spark.sql.iceberg.planning.preserve-data-grouping - matching transforms on the join columns of both tables
- a join condition covering those columns
SET spark.sql.sources.v2.bucketing.enabled = true;
SET `spark.sql.iceberg.planning.preserve-data-grouping` = true;
Further Spark settings handle partition values that exist on only one side, and can partially cluster one side to ease skew. Parallelism is limited to the number of partitions, so a very large partition becomes a very large task.
It pays off when both tables are large and joined repeatedly on the same key, since you pay for the layout once at write time and skip the shuffle on every read. If one side is small, a broadcast join is simpler and needs no layout. Confirm it happened by checking that neither side of the join has an Exchange operator beneath it in the physical plan.
102. How do you read the query plan of an Iceberg scan in Spark?
Run EXPLAIN FORMATTED and look at the BatchScan node: its filters= list shows what reached Iceberg, and any Filter operator above it shows what Spark still has to check row by row.
DROP TABLE IF EXISTS demo.shop.plan_demo PURGE;
CREATE TABLE demo.shop.plan_demo (order_id BIGINT, customer_id BIGINT, order_ts TIMESTAMP)
USING iceberg PARTITIONED BY (days(order_ts));
INSERT INTO demo.shop.plan_demo
SELECT id, id % 100, TIMESTAMP '2026-11-01' + make_interval(0, 0, 0, CAST(id % 3 AS INT))
FROM range(300);
EXPLAIN FORMATTED
SELECT order_id FROM demo.shop.plan_demo
WHERE order_ts >= TIMESTAMP '2026-11-02' AND customer_id = 7;
The interesting lines, trimmed:
(1) BatchScan demo.shop.plan_demo
[filters=order_ts IS NOT NULL, customer_id IS NOT NULL,
order_ts >= 1793577600000000, customer_id = 7, ...]
(3) Filter
Condition : (isnotnull(customer_id) AND (customer_id = 7))
Both predicates reached the scan. Only the one on customer_id is repeated in a Filter. order_ts is the partition source column and the bound falls on a day boundary, so the partition filter answers it completely. customer_id can only be narrowed by file statistics, so Spark must still test every row it reads.
| In the plan | Means |
|---|---|
Predicate in filters= only |
Fully satisfied by the scan |
In filters= and in Filter |
Used to skip data, then checked again |
Only in Filter |
Never pushed down, so no skipping |
A plan doesn’t tell you how many files were skipped or how long planning took. For that, read the scan metrics in the Spark UI.
103. What does write.object-storage.enabled do?
write.object-storage.enabled adds a hash-based prefix to data file paths, so that requests spread across many object store key prefixes. It is off by default.
Object stores scale their request rate by key range. In a conventional layout, today’s files share a long prefix ending in today’s date, and since recent data is read and written most, one key range takes nearly all the traffic and may be throttled.
default .../data/order_ts_day=2026-11-01/00000-....parquet
enabled .../data/<hash dirs>/order_ts_day=2026-11-01/00000-....parquet
Here is a real path from a table with the property on, after one insert:
<warehouse>/c3/os/data/1111/0100/0100/10010100/00000-16-4e621afe-03dc-447b-b179-d932f22afe49-0-00001.parquet
The 1111/0100/0100/10010100 part is the hash prefix. Those four directory levels replace the usual partition directory, so no two consecutive files share a leading key range.
The hash comes from the file name. On partitioned tables the partition path is included too, depending on write.object-storage.partitioned-paths. Iceberg queries behave exactly as before, because readers take paths from metadata and never infer anything from directory names.
| Gains | Costs |
|---|---|
| Requests spread over many prefixes | Directories are hard to browse |
| Less throttling at high request rates | Lifecycle rules and scripts that assume partition paths stop working |
The setting affects new files only; existing ones keep their paths until a rewrite replaces them. Small tables, low concurrency and file systems such as HDFS get nothing from it, so enable it when you actually see request throttling or expect very heavy parallel access.
104. A busy table gets 503 Slow Down errors from object storage. What do you do?
Cut the number of requests first, mainly by compacting, then spread new files across key prefixes and make retries back off.
503 Slow Down means too many requests per second against part of the key space. Find which operations and prefixes are throttled and what changed recently: a new job, a flood of small files or a large expiry run deleting thousands of objects at once.
Each cause has its own remedy.
| Action | Effect |
|---|---|
| Compaction | Fewer files, so fewer opens and range reads |
| Better partitioning and sorting | Queries skip more files |
write.object-storage.enabled |
New files spread over many prefixes |
| Lower maintenance concurrency | Softer bursts of deletes |
| Retry and back-off settings of the file IO | Transient throttling is absorbed |
Layout changes help gradually, since existing files keep their paths until rewritten.
The instinctive reactions make it worse. Adding executors sends more requests per second, and retrying immediately keeps the pressure on. The opposite extreme isn’t the answer either: one enormous file per partition would cut requests but hurt selective reads and make rewrites expensive. Aim for files near the target size.
105. What is in a snapshot summary, and how do you use it?
A snapshot summary is a small map of properties recorded with each commit: the operation, counts of files and records added or removed, totals and engine identifiers.
SELECT committed_at, operation,
summary['added-data-files'] AS added_files,
summary['added-records'] AS added_records,
summary['total-data-files'] AS total_files,
summary['spark.app.id'] AS app_id
FROM demo.shop.orders.snapshots
ORDER BY committed_at DESC
LIMIT 5;
The rows tell a story. A small append shows one file, one record and the writing application’s ID. A replace commit from compaction reports added files and records although no new data arrived, so summing added-records over all snapshots overstates what was ingested. A manifest rewrite, also a replace, adds no data files at all.
| Question | Where to look |
|---|---|
| Is a job creating small files? | added-data-files against added-records |
| Which job wrote this? | spark.app.id or flink.job-id |
| Which micro-batch? | Streaming query and epoch IDs |
| Did my batch land? | A custom property added with the snapshot-property. write option prefix |
Which keys appear depends on the operation and the engine, so queries should expect nulls. The totals count records in data files without subtracting merge-on-read deletes, so they aren’t a row count for such tables.
Within those limits, summaries are the quickest record of what each job did to a table. Writing your own batch ID costs one option and pays off the first time a commit outcome is unknown: one query tells you whether the batch is there.
106. How do you benchmark Iceberg performance fairly?
Fix the data, the queries and the cluster, change one thing at a time and measure planning separately from execution.
| Measure | Why it matters |
|---|---|
| Planning time | Reflects metadata health, hidden inside total latency |
| Files and bytes scanned | Shows whether pruning worked |
| Execution time | What users feel |
| Files and bytes written | Write amplification |
| Commit time and attempts | Behaviour under concurrency |
| Maintenance cost | The price of keeping the reads fast |
Make runs comparable. Pin reads to one snapshot ID, so that a change in data can’t explain a change in time. Record cache state, since a warm session can make the second run look like a tuning success. Run each query several times and report the median and spread, not the best.
Use your own workload. A fresh, perfectly compacted table flatters every design, while production tables carry delete files, late data and many manifests. Test the table as it looks after a week of writes without maintenance, and again after maintenance.
Finally, include writes and concurrency. A layout that wins on read latency can lose once updates run beside it, because it rewrites far more data or conflicts more often. State the engine and format versions with every result, since both change the numbers.
Streaming, change data capture and ingestion
107. How does Spark Structured Streaming write to Iceberg?
Structured Streaming writes each micro-batch to an Iceberg table as one commit, in append or complete output mode.
Each micro-batch produces one commit.
events = (spark.readStream.format("rate").option("rowsPerSecond", 5).load()
.selectExpr("value AS order_id", "value AS customer_id",
"CAST(1 AS DECIMAL(12,2)) AS amount", "'NEW' AS status",
"timestamp AS order_ts"))
query = (events.writeStream.format("iceberg")
.outputMode("append")
.trigger(processingTime="1 minute")
.option("checkpointLocation", "/tmp/ckpt/orders")
.toTable("demo.shop.orders"))
# after a few triggers:
query.stop()
The checkpoint remembers how far the source has been read, and each commit records the query ID and epoch ID in the snapshot summary. Consider a crash after the commit but before the checkpoint is updated. On restart Spark replays that batch; the sink walks back through history, finds the epoch already committed and skips it. That is where exactly-once comes from. Remove the checkpoint before resetting the table and rerunning the example.
The trigger interval is the commit interval. Iceberg recommends at least a minute, since shorter triggers mean more snapshots and smaller files. Appends are fast appends unless use-merge-append-for-streaming is set, and fanout-enabled keeps a writer open per partition to avoid sorting. Compaction and snapshot expiry are still required.
The guarantee has edges. It covers this sink with its checkpoint: a new checkpoint means a new query ID with no memory of earlier commits, writes inside foreachBatch must be made idempotent by you, and aggressive expiry can remove the snapshots the duplicate check relies on.
108. Can you stream from an Iceberg table?
Yes. Spark can read an Iceberg table as a stream, picking up newly appended data incrementally and recording its position in the checkpoint.
Each micro-batch plans the files added since the position recorded last time. stream-from-timestamp chooses where a new query starts. streaming-max-files-per-micro-batch and streaming-max-rows-per-micro-batch cap the batch size, so that catching up after an outage doesn’t become one enormous batch.
The source is built for appends, and other commit types behave differently:
| Snapshot in the source table | Default behaviour |
|---|---|
| Append | Read |
| Compaction | Not replayed, since it adds no new rows |
| Overwrite | The query fails unless streaming-skip-overwrite-snapshots is set |
| Delete | The query fails unless streaming-skip-delete-snapshots is set |
The behaviour is easy to reproduce with an AvailableNow copy job between two tables. Three rows arrive, then two more, then row 1 is deleted from the source and row 6 is added:
def run(skip="false"):
q = (spark.readStream.format("iceberg")
.option("streaming-skip-delete-snapshots", skip)
.load("demo.st.src")
.writeStream.format("iceberg").outputMode("append")
.trigger(availableNow=True)
.option("checkpointLocation", "file:///tmp/ck")
.toTable("demo.st.dst"))
q.awaitTermination()
after insert of 1, 2, 3 dst = [1, 2, 3]
after insert of 4, 5 dst = [1, 2, 3, 4, 5] (only the new rows were read)
after DELETE 1 and insert of 6 STREAM_FAILED: Cannot process delete snapshot: 4037453969882873287,
to ignore deletes, set streaming-skip-delete-snapshots=true
rerun with the skip option dst = [1, 2, 3, 4, 5, 6] (row 1 is still there)
The second run reads only the two new rows, not all five, because the checkpoint remembers its position. The third run fails on the delete, as the table above says. With the skip option the job moves on and picks up row 6, but row 1, which was deleted upstream, stays in the destination for good.
The skip options keep the query running, but think about what they mean. If someone deletes bad rows upstream and the stream skips that snapshot, the downstream copy keeps them forever. Skipping is right only when downstream is meant to retain removed data.
For tables that are updated in place, run the changelog view in a batch loop, or stream from an append-only raw table and apply changes downstream. Either way, keep snapshot expiry behind your slowest consumer, or its saved position will disappear.
109. How does Spark's AvailableNow trigger work with an Iceberg source?
The AvailableNow trigger processes everything available in the source when the query starts, using one or more micro-batches, and then stops. The checkpoint lets the next run continue from there.
(spark.readStream.format("iceberg")
.option("streaming-max-files-per-micro-batch", "100")
.load("demo.shop.source")
.writeStream.format("iceberg")
.trigger(availableNow=True)
.option("checkpointLocation", "s3://bucket/checkpoints/target")
.toTable("demo.shop.target")
.awaitTermination())
It combines streaming’s bookkeeping with batch scheduling. Run the job every hour from an orchestrator: it picks up exactly the data added since the previous run, without a cluster running in between and without you managing snapshot IDs.
| Behaviour | Detail |
|---|---|
| Backlog | Split into batches by rate limit options, such as maximum files per batch |
| Commits | One snapshot in the target per micro-batch |
| No new data | Nothing is committed |
| Data committed after the run starts | Waits for the next run |
The rate limit is worth setting even for a scheduled job. After a weekend outage, it turns one enormous batch into several manageable ones, each committed separately, so a failure loses less work.
The usual streaming source rules still apply. Overwrite and delete snapshots stop the query unless you choose to skip them, and the source table must keep its snapshots until the next run has read them, so retention has to cover missed runs as well as the schedule interval.
110. How do you read only the data added between two snapshots?
Use an incremental read. Give start-snapshot-id, which is exclusive, and end-snapshot-id, which is inclusive, and you get the rows that append commits added in that range.
ids = [r.snapshot_id for r in spark.sql(
"SELECT snapshot_id FROM demo.shop.orders.snapshots "
"WHERE operation = 'append' ORDER BY committed_at").collect()]
start_id, end_id = ids[-2], ids[-1]
(spark.read.format("iceberg")
.option("start-snapshot-id", start_id)
.option("end-snapshot-id", end_id)
.load("demo.shop.orders"))
Iceberg walks the snapshots between the two IDs and reads the files those appends added. It doesn’t compare table states, so the cost follows the amount of new data and not the size of the table. Both snapshots must still exist on the same line of history.
A pipeline built on this keeps a bookmark:
run 1 read up to snapshot A save A
run 2 read after A up to B save B
run 3 read after B up to C save C
Because the start is exclusive, pass the saved ID itself as the next start; there is no “next ID” to calculate, since IDs are random. Save the bookmark together with the output, or make the write safe to repeat, so a crash between the two doesn’t skip or duplicate data.
An incremental read represents appends only. Updates, deletes and overwrites in the range are not reported, so a table that changes in place needs the changelog view instead. And if expiry removes the saved snapshot, the job can’t resume and needs a full reload, so retain snapshots longer than the longest outage you expect.
111. How do you capture row-level changes from an Iceberg table?
Create a changelog view over a range of snapshots. It returns inserted and deleted rows, with _change_type, _change_ordinal and _commit_snapshot_id describing each one.
CALL demo.system.create_changelog_view(table => 'shop.orders', changelog_view => 'orders_changes');
SELECT _change_type, count(*) FROM orders_changes GROUP BY _change_type;
The procedure creates a temporary view that you query like any table. _change_type says whether a row was inserted or deleted, _change_ordinal gives the order of changes, and _commit_snapshot_id names the commit.
Iceberg records files and deleted positions, not logical updates, so an updated row appears as a delete of the old version plus an insert of the new one. The arguments decide how that is presented:
| Argument | Effect |
|---|---|
identifier_columns |
Pairs the delete and insert of one row |
compute_updates |
Produces before and after images |
net_changes |
Collapses intermediate changes to their net effect |
options |
Sets the snapshot or timestamp range |
compute_updates and net_changes can’t be combined. A copy-on-write rewrite also copies unchanged rows into new files; the procedure removes those carried-over rows, which costs extra work on large rewrites.
This lets downstream jobs follow a table that is updated in place. Its limits are that history must still be retained, some delete types aren’t supported, and only differences between commits appear. A value that changed twice before a single commit shows once, so it doesn’t replace change capture at the source database.
112. How does Flink write to Iceberg?
Flink writers create files continuously, and the Iceberg sink publishes them as a table commit each time a Flink checkpoint completes.
A checkpoint turns files into a snapshot.
Until a checkpoint completes, the files exist in storage but belong to no snapshot, so readers don’t see them. That link is what gives exactly-once behaviour after a failure.
| Write mode | Behaviour |
|---|---|
| Append | Adds data files |
| Overwrite | Replaces partitions, in batch jobs |
| Upsert | Keyed on a primary key; needs format version 2 or later; writes delete files alongside new rows |
CREATE TABLE sample (
id BIGINT, data STRING,
PRIMARY KEY (id) NOT ENFORCED
) WITH ('format-version' = '2', 'write.upsert.enabled' = 'true');
Upsert and overwrite can’t be combined, and in upsert mode the partition source columns must be among the equality fields, so that a delete lands in the same partition as the row it replaces. Rows can be distributed by hashing the partition or equality key, which handles skew poorly, or by an experimental range option.
The checkpoint interval is the commit interval, so it sets freshness and the rate of small files at the same time. A 10 second checkpoint means thousands of commits a day. Upserts also produce equality deletes that need regular compaction. If checkpoints succeed but no snapshots appear, look for committer failures, and alert on time since the last commit.
113. What can table maintenance break in a running Flink job?
Maintenance can remove the record of what a running job has committed, or delete files the job has written but not yet committed.
Three maintenance actions, three failures.
| Maintenance action | What breaks | Guard against it |
|---|---|---|
| Expiring the job’s latest snapshot | Flink loses its record of the last committed checkpoint, found through flink.job-id in the summary |
Always keep each job’s latest snapshot |
| Orphan removal with a short age limit | Files waiting for a checkpoint to commit are deleted | Set the age well beyond the longest checkpoint outage you expect |
| Compaction on active partitions | Conflicts with the upserts | Compact only partitions no longer being updated |
All three come from the same blind spot: a maintenance job sees the table, not the state held inside the streaming job.
The danger shows up during recovery. A job runs fine for months, then is stopped for a week. If maintenance was configured assuming an hour of lag, the snapshot or files it needs to restart may be gone, and restarting from the old savepoint is no longer safe. Retain snapshots longer than the longest planned downtime.
Give every table one maintenance owner, either a scheduled Spark job or Flink’s post-commit maintenance, so that retention rules are defined in one place and can be checked against the streaming jobs.
114. How does the Flink sink achieve exactly-once delivery into Iceberg?
The Flink sink ties a two-phase commit to checkpoints: writers close their files when a checkpoint begins, the file list is stored in checkpoint state and the committer publishes it only after the checkpoint completes.
The recorded checkpoint ID prevents a double commit.
Walk through a failure. The commit succeeds, but the job crashes before learning that it did. On restart, Flink restores the checkpoint and is about to commit those files again. First it reads the table’s snapshot summaries, which record flink.job-id, flink.operator-id and flink.max-committed-checkpoint-id. Finding that checkpoint already committed, it skips it.
End to end, the Kafka source stores its offsets in the same checkpoint, so source position and table advance together. After a restore, Kafka replays from exactly the point that matches the table.
| Requirement | Why |
|---|---|
| Checkpointing enabled | Commits happen only on completed checkpoints |
| Restart from checkpoint or savepoint | A fresh start has no position or committed ID |
| Latest committed snapshot not expired | It carries the record used to skip duplicates |
The guarantee starts at Kafka. If a producer wrote the same event twice into the topic, both copies arrive, and removing them needs an upsert or a merge on a key. The Kafka Connect sink has its own exactly-once path based on Kafka transactions.
115. Why does Flink write equality deletes instead of finding the old row's position?
To write a position delete, a writer must know the file and row of the old version. Keeping that mapping for every key would need an index over the whole table, and Flink’s writer keeps it only for rows written during the current checkpoint.
What the writer knows decides the delete type.
So the same upsert stream produces both kinds of delete, depending on how recently the key was written. This keeps writer state small and writes fast. The price moves to queries, which must match equality deletes against older files until compaction removes them, as described in question 54.
| Delete resolved by | Cost paid | |
|---|---|---|
| Equality delete | Readers, at query time | On every scan until compaction |
| Index in maintenance | A background task | In state and compute, once |
The alternative moves the index into maintenance. An experimental Flink task reads equality deletes from a staging branch, resolves them using a primary key index held in Flink state and commits deletion vectors to the target branch. It requires format version 3. Its state grows with the number of live rows, so size it generously, prefer the RocksDB state backend and keep other writers off the target table.
116. What is the difference between an exactly-once table commit and exactly-once processing?
An exactly-once commit means one table update is published once, completely or not at all. Exactly-once processing means every source event affects the result once, across the whole pipeline. Iceberg gives you the first; the second needs the source, the engine and your logic as well.
Each guarantee covers one stretch of the pipeline.
Follow one payment event. The application sends it, times out and sends it again. Kafka now holds two records. Spark reads both, once each, and commits them to the table, once each. Every component behaved correctly and the payment is counted twice.
| Stretch | Protected by | Not protected against |
|---|---|---|
| Producer to topic | Producer idempotence and transactions | An application that resends on its own |
| Topic to engine | Offsets in the checkpoint | A reset or deleted checkpoint |
| Engine to table | The snapshot summary: query and epoch IDs for Spark; job ID and highest committed checkpoint ID for Flink | Duplicates already in the input |
| Table state | Atomic commit | Wrong business logic |
The fix for the remaining gap is business identity: give each event a stable ID or a source sequence number and merge on it, so that applying it a second time changes nothing.
In an interview, avoid saying “Iceberg is exactly-once”. Say which stretch each mechanism covers and name the one you would have to build.
117. A streaming job into Iceberg has failed. How do you restart it safely?
Restart it from its existing checkpoint, after confirming what the table already committed. Don’t delete the checkpoint to make an error go away.
The table records which micro-batches arrived:
SELECT committed_at,
summary['spark.sql.streaming.queryId'] AS query_id,
summary['spark.sql.streaming.epochId'] AS epoch
FROM demo.shop.orders.snapshots
ORDER BY committed_at DESC LIMIT 5;
Each streaming commit carries the query ID and an epoch number that increases with every batch. Compare the latest epoch in the table with the checkpoint’s progress.
- Find the cause of the failure and fix it.
- Check that the checkpoint directory is intact.
- Check the latest committed epoch for this query ID.
- Check that the source still holds the offsets the checkpoint needs.
- Restart from the checkpoint.
- Reconcile counts or totals for the affected window.
If the commit succeeded just before the crash, the replayed batch is recognised by its query and epoch IDs and skipped.
| Situation | Consequence |
|---|---|
| Checkpoint intact | Safe to restart |
| Checkpoint deleted | New query ID, so earlier commits aren’t recognised: duplicates or gaps |
| Source offsets expired | Data is lost from the source’s point of view; backfill another way |
| Table rolled back behind the checkpoint | The stream won’t replay the removed batches by itself |
If you must start a new checkpoint, choose the starting offsets deliberately and make the write idempotent with a merge on a business key.
118. Design a CDC pipeline from a database into Iceberg for high event rates with low latency.
Capture changes with Debezium into Kafka keyed by primary key, write them with Flink into an append-only changes table and maintain a current-state table by upsert or frequent MERGE.
History and current state side by side.
Start with arithmetic, because it decides the design. At 100,000 events a second with a 30 second checkpoint, each commit carries 3 million events and there are 2,880 commits a day. Those figures drive parallelism, file sizes and how often maintenance must run.
| Decision | Reason |
|---|---|
| Key Kafka by primary key | All changes to a row stay in order in one partition |
| Longest commit interval the latency target allows | Fewer, larger files |
| Keep an append-only changes table | A bug in the merge can be fixed by replaying |
| Bucket the current table by key | Spreads writes and narrows merges |
| Keep the source log position | Deduplication and correct ordering |
Data becomes visible after roughly one commit interval plus the time to commit, so state that number rather than promising real time. Equality deletes need compaction from the first day, not after queries get slow. Monitor consumer lag, commit duration, delete counts and the age of the newest event in the table.
119. Change events arrive out of order or hours late. How do you apply them correctly?
Order events by a sequence number from the source, not by arrival time. Keep the newest event per key within each batch, apply it only if it is newer than the stored row, and keep deletes soft while old events can still arrive.
DROP TABLE IF EXISTS demo.shop.customers PURGE;
CREATE TABLE demo.shop.customers (id BIGINT, name STRING, seq BIGINT, deleted BOOLEAN)
USING iceberg;
INSERT INTO demo.shop.customers VALUES (1, 'new name', 30, true);
MERGE INTO demo.shop.customers t
USING (
SELECT id, name, seq, deleted FROM (
SELECT *, row_number() OVER (PARTITION BY id ORDER BY seq DESC) AS rn
FROM VALUES (1, 'late name', 15L, false), (2, 'second', 40L, false)
AS v(id, name, seq, deleted)
) latest WHERE rn = 1
) s
ON t.id = s.id
WHEN MATCHED AND s.seq > t.seq THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *;
SELECT * FROM demo.shop.customers ORDER BY id;
The table starts with key 1 deleted at sequence 30. The batch then brings an old update for key 1 with sequence 15, and a new key 2:
id name seq deleted
1 new name 30 true the late event at 15 changed nothing
2 second 40 false inserted
Two guards did the work. row_number() keeps one row per key in the batch, which avoids a cardinality error. s.seq > t.seq rejects anything older than what the table already holds.
The soft delete is the third guard. Had row 1 been physically removed, the old event would have found no match and inserted the customer again. Readers filter on deleted = false, usually through a view, and soft-deleted rows are purged once they are older than the longest delay you expect.
A direct streaming upsert applies events in arrival order, so it is only correct when each key’s events arrive in order, for example through a single Kafka partition. Also check how old late events can be, since merging them touches old partitions and widens each merge.
120. A replay of a change stream created duplicate keys. How do you clean up and prevent it?
Identify the affected keys, rebuild the correct rows in one atomic operation, then make the pipeline idempotent so it can’t happen again.
Where a replay enters a CDC pipeline.
SELECT order_id, count(*) AS copies
FROM demo.shop.orders
GROUP BY order_id
HAVING count(*) > 1
ORDER BY copies DESC LIMIT 10;
The query lists keys that appear more than once; on a healthy table it returns nothing. If the duplicates came from one commit with nothing after it, simply roll that commit back. Otherwise:
- Pause the pipeline.
- For each affected key, choose the newest version by the source sequence column.
- Replace the affected keys or partitions in a single commit, on a branch.
- Check counts and uniqueness, then publish.
Iceberg enforces no primary key, so prevention belongs to the pipeline:
- deduplicate every incoming batch
- merge on the real business key
- apply updates and deletes only when the incoming sequence is newer
- keep soft deletes while old inserts can still be redelivered
- avoid resetting checkpoints casually
- alert on duplicate keys
The soft delete point is easy to miss. If a deleted row is physically removed and an old insert for it is replayed, nothing remembers that it was deleted, so it comes back.
121. How do you handle schema changes automatically in a Kafka to Iceberg pipeline?
Automate only additive changes. Let the sink add nullable columns, send incompatible records to a dead-letter path and have a person review renames, type narrowing and drops.
Automate only the additive changes.
| Tool | Schema evolution support |
|---|---|
| Kafka Connect sink | Adds missing record fields with iceberg.tables.evolve-schema-enabled |
| Flink | The experimental dynamic sink can update table schemas |
| Spark | mergeSchema, on tables with write.spark.accept-any-schema |
Adding a nullable column is safe: old rows read as null and existing queries are unaffected. Other changes can’t be inferred from data. When a producer renames userId to user_id, an automatic sink sees a new field and creates a second column, while the original quietly stops filling. A misspelt field becomes a permanent column in the same way.
The cheapest control sits upstream. A schema registry with compatibility rules rejects breaking changes before they are published, so they never reach the sink.
Remember that evolving the table isn’t enough for every job. Many streaming applications fix their parser schema when they start and ignore new fields until restarted. Alert on unknown fields and decide deliberately when to roll them in.
122. When would you append to a staging table and merge periodically instead of upserting directly?
Append to a staging table and merge periodically when minutes or hours of latency are acceptable and you want cheap reads, replay and control over conflicts. Upsert directly when the table must be current within one checkpoint.
Appends are cheap and replayable. The merge sets the freshness.
| Direct upsert | Staging table, then merge | |
|---|---|---|
| Freshness | One checkpoint | The merge interval |
| Delete files | Equality deletes accumulate | The merge chooses its write mode |
| Event order | Arrival order | Deduplicate and order by source sequence |
| Replay | Only while Kafka retains the events | From the staging table |
| Compaction | Conflicts continuously | Scheduled between merges |
| Storage | One copy | Two copies |
The staging design works well partly because the staging table only ever receives appends. The merge job can therefore read just the new rows with an incremental read, apply them and save its position.
If different consumers need different things, combine the two. Consumers who need data within seconds query the append table through a view that picks the latest row per key, accepting a more expensive query. Everyone else reads the merged table, which is fast to query and slightly behind.
123. Design ingestion into Iceberg from hundreds of source tables.
Make adding a source table a configuration change. Generate pipelines from a registry, keep a replayable raw layer with idempotent merges and let metadata signals trigger maintenance.
Sources are added by configuration.
With hundreds of sources, hand-written jobs don’t survive. A registry entry per table records its keys, ingestion mode, schedule and owner, and one framework generates the jobs from it.
| Concern | Approach |
|---|---|
| Schema changes | Apply compatible ones automatically; queue the rest for review |
| Event data | Append |
| Frequently updated tables | Merge-on-read |
| Commit volume | Batch rather than commit per record |
| Maintenance | Driven by file counts and delete counts |
Isolation matters as much as automation. One broken source must not hold up the others, so group pipelines by priority and give each table its own checkpoint or bookmark. Hundreds of jobs starting on the hour can overwhelm a catalog, so spread their schedules and watch its latency.
Track freshness, lag, file counts, delete share and failed commits per table. Without per-table figures, the first sign of a problem is a consumer complaining.
124. Design a table that serves a near-real-time view and a daily batch report from the same data.
Write the stream into one table, serve the live view from its latest snapshot and run the daily report from a tag taken at the close of the day.
One table serves both consumers.
Start by asking about requirements. How fresh must the live view be? Are rows updated or only appended? Must the report be reproducible later?
| Concern | Design choice |
|---|---|
| Freshness | Commit every minute or few minutes |
| Small files | Compact closed hours |
| Stable report numbers | Tag at a defined cut-off, and read the tag |
| Late events | Define the cut-off; publish corrections under a new tag |
| Updates to rows | Keep raw data append only and build a merged table |
| Upkeep | Schedule snapshot expiry and manifest rewrites alongside compaction |
The attraction is that both consumers read one dataset. There is no second batch pipeline to disagree with the real-time figures. The report reads a fixed snapshot while the stream keeps writing, so it can’t change halfway through. When late data arrives afterwards, a new tag publishes the revised figures while the old tag preserves what was originally reported.
If the live view needs sub-second latency, Iceberg’s commit cycle is the wrong tool. Serve that view from a stream processor or serving store, and keep Iceberg for history and reporting.
125. Design the Iceberg settings for a raw, cleaned and reporting pipeline.
Begin with volume, latency, update rate, consumers and retention. Then choose a write pattern, layout, row-level mode and maintenance plan for each layer.
Three layers with three write patterns.
| Layer | Writes | Layout and mode | Maintenance |
|---|---|---|---|
| Raw | Frequent appends | Partitioned by ingest day; source fields preserved | Compact settled days |
| Cleaned | Upserts by key | Partitioned by event time and organised by key; merge-on-read if updates are frequent | Compact deletes often |
| Reporting | Rebuilt in batches | Sorted by common filters; copy-on-write | Tag each publish |
The reasoning behind each layer matters in an interview. Raw keeps source fields so that later layers can be rebuilt after a bug, and partitioning by ingest time means appends only touch today. Cleaned absorbs changes, so it pays for deduplication and deletes once. Reporting is read far more than written, so it takes the expensive write for fast reads.
How layers feed each other follows from their write patterns. Cleaned can read raw incrementally because raw is append only. Reporting can’t read cleaned that way, since cleaned is updated in place; use the changelog view or rebuild affected partitions.
All layers need one catalog, a named maintenance owner, alerts on file size, deletes, failures and freshness, and a tested recovery path. When costs rise, look first at retention and at commits that are more frequent than anyone needs.
Catalogs, engines and integrations
126. Which engines work with Iceberg?
Spark, Flink, Trino, Presto, Hive, Impala, Dremio, StarRocks and a number of cloud warehouses work with Iceberg tables. “Works with” covers very different levels of support, so check what each one can actually do.
Four questions settle most of it:
- Can it read your format version, including every delete type your writers produce?
- Which writes does it support: append, overwrite,
MERGE? - Which catalogs can it talk to?
- Can it run maintenance such as compaction and snapshot expiry?
A common arrangement gives each engine one job. Flink ingests streams, Spark runs merges and maintenance, and Trino or a warehouse serves interactive queries. They share tables safely because they all resolve them through the same catalog, which arbitrates every commit. Two catalogs pointing at the same files would break that: each would accept commits the other never sees.
The least capable consumer sets the limit for the whole table. Suppose Spark can write deletion vectors on format version 3 but one reporting tool can’t read them. Upgrading the table breaks that tool, or forces you to wait for it. Before upgrading an engine or the format, write a test table with each writer, read it with each reader and compare row counts and aggregates.
127. How do you choose between Spark, Flink and Trino for working with Iceberg?
Choose by the shape of the workload, not by the table format, because all three read and write the same tables. Flink suits continuous, low-latency ingestion. Spark suits large batch transformations and maintenance. Trino suits interactive SQL for many concurrent users.
The tables are shared. The workload picks the engine.
| Workload | Usual choice | Why |
|---|---|---|
| Continuous ingestion and change streams | Flink | Long-running jobs, state and event-time handling, commits tied to checkpoints (question 114) |
Large batch ETL, backfills, MERGE pipelines |
Spark | Strong at heavy shuffles and large rewrites, plus the widest set of Iceberg procedures (question 131) |
| Table maintenance | Spark, or the same engine that owns the table | Compaction, expiry and manifest rewrites are procedures there |
| Dashboards and ad hoc analysis | Trino | Low startup cost and good concurrency for short queries |
Two checks matter more than the label. First, confirm that each engine supports the table features you use: the format version, delete types, data types and any MERGE behaviour (question 72). A table can be valid and still use something one connector doesn’t implement. Second, decide who owns writes. Many engines can read a table, but writers contending for one table cost you commit conflicts and make maintenance harder to schedule.
When you compare engines on the same table, hold the table state, the filters, the concurrency and the caches constant, and measure planning time separately from execution time (question 106). Speed alone is a poor basis for the choice: an engine that is faster on one query may need more operational work to run safely.
128. What Spark configuration does Iceberg need?
Spark needs three things: the Iceberg runtime jar, a catalog declared under spark.sql.catalog.<name> and the Iceberg SQL extensions.
| Setting | Purpose |
|---|---|
--packages org.apache.iceberg:iceberg-spark-runtime-<spark>_<scala>:<version> |
The integration jar |
spark.sql.catalog.<name> |
Catalog implementation class |
spark.sql.catalog.<name>.type and .uri, .warehouse |
Which catalog and where |
spark.sql.extensions |
org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions |
The jar’s name carries the Spark and Scala versions, such as iceberg-spark-runtime-3.5_2.12. A mismatch typically fails with NoSuchMethodError or a missing class at runtime. Cloud storage may also need an SDK bundle.
There are two catalog classes with different purposes:
| Class | What it does |
|---|---|
SparkCatalog |
Adds a separate catalog containing only Iceberg tables |
SparkSessionCatalog |
Wraps the built-in spark_catalog, so Iceberg and other tables share names |
Migration procedures rely on the second. One session can declare several catalogs, and you pick one by qualifying the table name, as demo.shop.orders does here.
You can see what each piece does by leaving it out. These runs use a session with the catalog declared but without spark.sql.extensions:
| Statement | Result without the extensions |
|---|---|
SELECT count(*) FROM demo.cf.t |
Works, and returns the row count |
CALL demo.system.rewrite_data_files(...) |
[PARSE_SYNTAX_ERROR] Syntax error at or near 'CALL' |
ALTER TABLE demo.cf.t CREATE BRANCH b1 |
[PARSE_SYNTAX_ERROR] Syntax error at or near 'CREATE' |
ALTER TABLE demo.cf.t WRITE ORDERED BY id |
[PARSE_SYNTAX_ERROR] Syntax error at or near 'WRITE' |
Reading, INSERT, DELETE and MERGE all worked in the same session, so they need only the catalog. The procedures and the Iceberg-specific ALTER TABLE forms need the extensions. If the catalog is missing as well, the error is not “catalog not found” but [REQUIRES_SINGLE_PART_NAMESPACE] spark_catalog requires a single-part namespace, but got demo.cf, because Spark treats demo as a namespace inside its built-in catalog. That message sends many people looking in the wrong place.
The extensions add the SQL that Spark doesn’t parse itself, including CALL procedures, branch and tag statements and partition field changes. They are read when the session is built, so setting them afterwards has no effect, and with Spark Connect they belong on the server. A misspelt extension class only logs a warning. The first visible symptom is often a PARSE_SYNTAX_ERROR on an ALTER TABLE that looks perfectly correct.
129. Which table properties do you review first on a production table?
Review the format version, file size and distribution mode, row-level write modes, column metrics, snapshot retention, metadata cleanup and commit retries first.
These decide who can read the table, how its files are laid out, what queries can skip, how far back you can recover and how writers cope with each other.
| Property | Default | Question to ask |
|---|---|---|
format-version |
2 | Do all engines support it? |
write.target-file-size-bytes |
536870912 | Does it match the query pattern? |
write.distribution-mode |
unset | Is the chosen shuffle producing sensible files? |
write.delete.mode, write.update.mode, write.merge.mode |
copy-on-write | How often do rows change? |
write.metadata.metrics.default |
truncate(16) | Are filter columns covered? |
history.expire.max-snapshot-age-ms |
5 days | How far back must you recover? |
history.expire.min-snapshots-to-keep |
1 | Minimum history for idle tables? |
write.metadata.delete-after-commit.enabled |
false | Will metadata files pile up? |
commit.retry.num-retries |
4 | How many writers compete? |
SHOW TBLPROPERTIES demo.shop.orders;
SHOW TBLPROPERTIES lists only properties that have been set. Anything missing from the output is using the library default, which can differ between versions, so an absent property is not the same as a disabled one.
Set these early. Layout properties apply to data written afterwards, so changing the file size or metrics mode later leaves old files as they were until compaction rewrites them. Treat the retention settings as a recovery decision first and a cost decision second: with the defaults, a snapshot older than five days can be expired even if you only notice the bad load on day six.
130. What is the difference between a table property, a Spark configuration and a write option?
They live at three different levels. A table property is stored in the table’s metadata and applies to every engine that writes the table. A session configuration applies to one Spark session. A write or read option applies to one operation.
| Level | Where it lives | Reaches other engines? | Example |
|---|---|---|---|
| Table property | Table metadata | Yes | write.target-file-size-bytes |
| Session configuration | The Spark session | No | spark.sql.iceberg.vectorization.enabled |
| Operation option | One read or write call | No | .option("target-file-size-bytes", ...) |
ALTER TABLE demo.shop.orders SET TBLPROPERTIES ('write.target-file-size-bytes' = '268435456');
That statement changes the default for every later write by every engine. A session setting changes only what this Spark application does, and disappears with it.
For a setting that exists at several levels, the narrowest one wins: an operation option beats a session setting, which beats the table property. Not every setting exists at every level, so look up the one you need.
Use a table property for what should be true of the table whoever writes it, such as target file size, compression, retention and write modes. Use a session or operation setting to tune one job without affecting others. Mixing them up causes quiet surprises: a job-level tweak that helps your Spark job does nothing for the Flink writer, and a table property you forgot about explains why two jobs write different file sizes. SHOW TBLPROPERTIES lists only what has been set, so a missing property means the library default applies (question 129).
131. What are Iceberg's Spark procedures, and how do you call them?
Iceberg exposes table operations as procedures in each catalog’s system namespace, called with CALL <catalog>.system.<procedure>(name => value). Spark needs the Iceberg SQL extensions for this syntax.
CALL <catalog>.system.<procedure>(name => value, ...);
| Area | Procedures |
|---|---|
| Snapshots and branches | Rollback, set_current_snapshot, cherrypick_snapshot, fast_forward, publish_changes |
| Maintenance | Rewrite data files, manifests and position delete files; expire snapshots; remove orphan files |
| Migration | migrate, snapshot, add_files, register_table, rewrite_table_path |
| Analysis | Changelog views, table and partition statistics, ancestors_of |
CALL demo.system.ancestors_of(table => 'shop.orders');
ancestors_of is a harmless one to try: it lists the current snapshot and its parents with timestamps.
Use named arguments, which survive signature changes and are readable in review. Pass literal values, because an expression such as current_timestamp() is rejected as an argument. Read the result row, which reports what actually changed; zeros mean no files matched the rules, not that something broke. The same operations are available in the Java actions API, and other engines have their own syntax for them.
132. How do you choose a catalog, and does Iceberg require Hive Metastore?
Iceberg needs a catalog but not the Hive Metastore, which is one option among several. Choose from the engines that must connect, how access has to be controlled, how often tables commit and what your team already runs.
| Catalog | Suits | Cost or limit |
|---|---|---|
| REST | Many engines and central security | You run or buy the server |
| Hive Metastore | Existing Hadoop platforms | Thrift protocol; scaling and coarse security; commits by checking and swapping the table entry |
| AWS Glue | AWS platforms | Tied to AWS; commits through conditional updates |
| Apache Polaris | Iceberg REST with role-based privileges | Another service; vends short-lived credentials |
| Unity Catalog | Databricks platforms | REST endpoint; external write support differs by table type, so check current documentation |
| JDBC | Small deployments | Every client needs database access |
| Nessie | Branching across several tables | Another service to run |
| Hadoop | Local tests | Unsafe for shared storage |
Four questions narrow the list quickly:
- Does every engine that reads or writes support it?
- Who authorises access, and who issues storage credentials?
- Can it handle your sustained commit rate?
- How do you restore it after an outage or a bad change?
The first usually eliminates the most options. An engine that can’t use the catalog either can’t use the tables or ends up reading files behind the catalog’s back.
With a Hive catalog the metastore entry only holds a property pointing at the current metadata file. The schema is mirrored for other tools, but Iceberg’s metadata file stays the source of truth. For a new platform a REST catalog is the usual choice, provided your engines support it and someone will run it.
Treat the decision as long-lived. Tables can be moved without copying data: stop writers, register the latest metadata file in the new catalog, repoint every client and never write through both. Permissions, views and automation are much harder to move. Iceberg catalogs compares the options in detail.
133. Why is the Hadoop catalog unsafe on object storage?
The Hadoop catalog commits by renaming a new metadata file to the next version number. That is safe only if the rename is atomic and fails when the target already exists, and many object stores guarantee neither.
Why a rename is not a safe commit everywhere.
On HDFS the second writer’s rename fails, so it knows to retry. On an object store a rename is often a copy followed by a delete, and nothing stops the second copy from overwriting the first. Both writers report success and one commit silently disappears.
Nothing fails at write time. You find out later, from missing rows, snapshots absent from history or a stale version-hint.text, which is the small file this catalog uses to record the current version. The specification marks this file-system table scheme as deprecated and calls it unsafe in object stores and local file systems.
| Use | Hadoop catalog? |
|---|---|
| Local development and single-writer tests | Acceptable, as in these examples |
| Shared storage or concurrent writers | No |
For anything real, use a catalog with a true compare-and-swap and register the existing metadata file there; no data needs copying. A lock manager can protect the rename, but only if every client uses it, and one writer that doesn’t is enough to lose commits.
134. How does a REST catalog change commits and security?
With a REST catalog the client no longer swaps the pointer itself. It sends the server a list of requirements and updates, and the server applies the updates only if every requirement still holds.
One REST catalog implementation handling a request.
A commit might say: require that main still points at snapshot 7, then add snapshot 8 and move main to it. The server checks the requirement, writes the new metadata file and swaps the pointer.
| Requirement | Protects against |
|---|---|
assert-table-uuid |
The table having been dropped and recreated |
assert-ref-snapshot-id |
A branch having moved |
| Schema and partition spec checks | Concurrent definition changes |
assert-create |
Creating a table that already exists |
Because the checks are specific, a change to one branch needn’t conflict with unrelated metadata changes, and the commit logic lives in one place instead of in every client library and language.
Security moves to the server too. It can authorise each operation and hand out short-lived storage credentials or sign individual requests, so engines need no long-lived keys. The specification also defines multi-table commits and server-side planning, which a given server may or may not implement. The price is a service whose availability, latency, backups and authentication are now critical. Apache Polaris is one implementation.
135. What is the difference between the REST catalog API and a REST API that serves data?
The REST catalog API serves table metadata and commits to query engines. A data API serves rows to applications, and you design it yourself.
One API serves metadata, the other serves rows.
| Iceberg REST catalog API | Data API | |
|---|---|---|
| Defined by | The Iceberg specification | You |
| Called by | Query engines | Your consumers’ applications |
| Returns | Table metadata, file locations, credentials | Rows |
| Reads data files | No, the engine does | Should delegate to a query engine or serving store |
Loading a table from the catalog returns where the metadata is and, optionally, credentials. It never returns query results. Expecting it to is a common misunderstanding.
If you build a data API over Iceberg tables, design for how the table behaves:
- precompute the result shapes the API needs instead of scanning files per request
- paginate, and pin every page to the same snapshot, so that a commit between two requests can’t repeat or skip rows
- cache by snapshot ID, and invalidate when the table’s current snapshot differs
If applications need responses in milliseconds, publish results into a key-value or relational store built for that, and keep Iceberg as the source of truth they are derived from.
136. What happens if two catalogs point at the same table, and how do you avoid it?
Each catalog swaps its own pointer and never sees the other’s commits, so the table forks into two histories. Changes get lost, and maintenance on one side can delete files the other still references.
Two pointers produce two histories.
Both writers report success. Nothing errors until someone notices missing rows, or a query fails because the other side’s expiry removed a file.
The rule is that one catalog owns commits. Every engine writes through it, and other platforms either read through it or receive a refreshed, read-only copy. Snowflake illustrates both arrangements:
| Table type in Snowflake | Who owns commits | Notes |
|---|---|---|
| Snowflake-managed | Snowflake | It maintains the table and documents external read and write through the Horizon Iceberg REST API |
| Externally managed | Another catalog | Support is more limited, Snowflake must refresh to see changes, and writes are supported for tables in a remote Iceberg REST catalog |
These limits change, so check current documentation.
To detect a fork, compare the metadata locations each catalog reports. To repair it, stop all writers, decide which history is authoritative, replay the other side’s changes onto it and remove the duplicate entry without purging, because purging would delete files the surviving table still uses.
137. How do you make the Iceberg catalog highly available?
Run several stateless copies of the catalog service behind a load balancer, put its state in a replicated database, and make sure the commit’s compare-and-swap still holds during a failover. Availability without correct commits is worse than an outage.
Everything in a table depends on one atomic step: replacing the metadata pointer only if it is unchanged (question 9). A catalog that stays up but loses that guarantee during a failover can let two writers both succeed, and one commit disappears without any error. Test for this explicitly.
Every layer can fail without losing an acknowledged commit.
| Layer | What to do |
|---|---|
| Service | Several stateless instances behind a load balancer, so one can fail without taking commits down |
| Backing store | A replicated database with automatic failover, and no lagging replica serving the commit path |
| Clients | Bounded retries with backoff, and handling for the unknown-outcome case (question 69) |
| Credentials | Short-lived tokens that refresh, so an expiry during a failover doesn’t fail every client |
| Recovery | Backups of the catalog entries, and a rehearsed restore (questions 185 and 163) |
Test the failure modes rather than assume them: kill an instance during a commit, fail the database over while writers are running, partition the network, and race two writers on one table throughout. After each test, check that every acknowledged commit is in the snapshot history and that none was applied twice.
Also decide what should keep working when the catalog is down. Sessions that cached a table can often still read, but nothing can commit (question 138). Say plainly to the people who depend on the platform what that means for them.
138. What still works when the catalog is unavailable?
The data and metadata files are untouched, but clients can’t find out which metadata file is current, so new queries and all commits fail.
Files stay safe. Finding and publishing the current version does not.
| Activity during the outage | Works? |
|---|---|
| A query that already planned its files | Usually, since it only reads storage |
| A session holding a cached table | Reads may continue on a possibly stale snapshot |
| A new session reading the table | No |
| Any commit | No |
| Files being written by running jobs | The writes succeed; publishing them doesn’t |
A job that fails at commit leaves unreferenced files. One that sent the commit and lost the connection may end with CommitStateUnknownException, so check the table when the catalog returns before rerunning anything.
Resist the shortcut of reading or writing around the catalog by pointing a client at the newest metadata file in the directory. The newest file may belong to a commit that never succeeded, and a second writer path forks the table, as in question 136.
Plan for the outage instead. Run the catalog with redundancy, monitor request latency and errors, back up its state, record metadata locations elsewhere and rehearse the restore. Streaming jobs should retry with back-off and keep their checkpoints, so that they resume where they stopped once the catalog is back.
139. Why might a session not see another engine's commit, and how do engines cache Iceberg metadata?
Caching metadata files is always safe, because they never change. Stale results come from caching which snapshot or metadata file is current.
The expiry restarts on every access.
| Engine | What it caches | Staleness to expect |
|---|---|---|
| Spark | Loaded tables, through the catalog cache, on by default with a 30 second expiry | Longer in busy sessions, since access renews the entry |
| Trino | iceberg.metadata-cache.enabled, on by default, keeps metadata files in coordinator memory, or on local disk with the file system cache |
Caches immutable files |
| StarRocks | Memory and optionally disk, refreshed in the background by polling the metastore, every ten minutes by default | Up to the polling interval after another engine commits |
The StarRocks case is a good example to give: a Spark job commits, and for several minutes StarRocks users still see the previous data, with no error anywhere.
In Spark the cache is controlled by spark.sql.catalog.<name>.cache-enabled. REFRESH TABLE demo.shop.orders; reloads one table now, a shorter expiry bounds staleness at the cost of more catalog calls, and disabling the cache means the most catalog traffic. A dashboard session that queries every 10 seconds keeps renewing the entry, so it can read an old snapshot indefinitely while a new session sees the latest one. Before blaming the cache, rule out a branch or time travel setting, catalogs that point at different metadata, and a failed commit.
The staleness shows up in plain tests, too. While checking the isolation behaviour in question 66, a count(*) in the session that had created the table returned 3 although two other sessions had since committed a fourth row. Running REFRESH TABLE first returned 4. Nothing was wrong with the table. The session was holding its cached copy.
When two engines disagree, find the snapshot ID each is using. If they differ, it is caching, so refresh or restart the lagging one and compare again. Check the cache settings for the versions you actually run. When results must match exactly, such as in a reconciliation, don’t rely on freshness at all: pin both queries to one snapshot ID or tag.
140. How does credential vending work in a REST catalog, and what can it not secure?
The engine asks a REST catalog to load a table, and the catalog returns storage credentials that are short-lived and limited to that table’s location. It can’t restrict rows or columns.
Temporary access scoped to one table.
Without vending, every engine needs standing permission on the bucket, which means anyone with that permission can read any table’s files, whatever the catalog says. With vending, only the catalog holds broad rights, and each request gets access to one table for a limited time. It also saves writing storage policies for every combination of user and table.
| Method | How access is granted | Cost |
|---|---|---|
| Vended credentials | Temporary keys scoped to the table’s paths | The client must refresh them during long jobs |
| Remote signing | The catalog signs each storage request | More calls to the catalog |
A client asks for vending by sending the header X-Iceberg-Access-Delegation: vended-credentials when it loads the table.
The security boundary is the file. Once a principal can read a data file, it sees all rows and all columns in it, so row filters and column masks have to be enforced somewhere else.
Two setup details decide whether this works. Remove the engines’ standing bucket permissions, or vending is only optional. And give each table its own prefix, since credentials scoped to a shared prefix expose neighbouring tables.
141. How are access control and encryption handled for Iceberg tables?
The table format doesn’t enforce access control. It is the job of the catalog, the storage permissions and the query engines together.
Four layers share the job. Direct bucket access skips them all.
| Layer | What it controls |
|---|---|
| Catalog | Who may list, read, change or drop tables |
| Storage | Who may read or write objects |
| Credential vending | Short-lived storage access scoped to one table |
| Engines | Row filters, column masks and views |
The layers must agree. If any identity holds broad bucket permissions, it can read the files directly and bypass every rule in the catalog, so grant storage access through the catalog rather than alongside it.
Encryption is available at two levels. Storage-side encryption is simple and transparent. Iceberg table encryption needs format version 3 and a release that supports it: configure a key management service on the catalog and set encryption.key-id on the table. Data files, delete files, manifests and manifest lists are then encrypted, while the metadata JSON is not, and support depends on the catalog and file format.
One detail is often missed: column statistics in metadata contain real values, such as the lowest and highest email address in a file. Protect metadata with the same care as data.
142. How do you apply column masking and row-level security consistently across engines?
The Iceberg table format defines no row or column policies, so catalogs and engines enforce them. Consistency comes from allowing only engines that enforce your rules to read the files.
| Approach | Where it works | Weakness |
|---|---|---|
| Policies in each engine | That engine | They drift apart unless carefully duplicated |
| Central policy service | Engines with its plugin | Others are unprotected |
| Views with filters and masks | Engines that understand the dialect | Base table access must be denied |
| Masked copies of tables | Everywhere | Extra pipelines and storage |
| Query service in front of sensitive data | Everywhere | A single access path |
The underlying limit is that storage permissions and credential vending work per file. Whoever can read the file reads every column and row, regardless of any mask configured in an engine.
A workable design combines these. Classify the data, allow direct file access only to trusted pipeline jobs, publish masked copies or views for everyone else, and test with a restricted user in every engine, since a policy that works in one may be silently ignored in another. Don’t forget metadata: column bounds contain real values.
143. How do you enforce table standards at creation time?
Set them in the catalog configuration. Properties prefixed table-default. apply when a statement gives no value, and table-override. properties replace whatever the statement asks for.
spark.sql.catalog.prod.table-default.write.parquet.compression-codec=zstd
spark.sql.catalog.prod.table-override.write.metadata.delete-after-commit.enabled=true
spark.sql.catalog.prod.table-default.history.expire.max-snapshot-age-ms=604800000
With the override above, CREATE TABLE with write.metadata.delete-after-commit.enabled set to false still produces true. The defaults for compression and snapshot age apply only if the creator says nothing.
| Mechanism | Binds | Can be bypassed by |
|---|---|---|
table-default. |
Tables created through this configuration | Specifying a value |
table-override. |
Tables created through this configuration | A client without the configuration, or a later ALTER TABLE |
| Catalog service policy, where supported | Every client | Depends on the service |
| Scheduled audit job | Detects drift afterwards | Nothing prevented, only reported |
The limitation is that the prefixes are client-side settings. An engine configured without them ignores them entirely, and neither prefix stops someone altering the property after creation.
So layer the controls: defaults for sensible starting values that owners may change, overrides for the platform’s non-negotiables, permissions on altering tables and an audit job that reads table properties and reports exceptions.
144. What are Iceberg views?
An Iceberg view is a view definition stored in a standard format, so that different engines can read the same view from the catalog. It holds no data.
A stored view records:
- the SQL text and the dialect it is written in
- the output columns and their types
- a history of versions, with one marked current
- the default catalog and namespace used to resolve names
Replacing a view creates a new version and switches to it atomically, much like a table commit, so readers see the old definition or the new one, never a mixture. Nothing is materialised: every query against the view reads the underlying tables.
Sharing a definition is not the same as translating it. Suppose Spark creates a view that uses a Spark-only function. Another engine can see the view, but it needs a representation in a dialect it understands, so the query may fail there. Write views in standard SQL and test each one in every engine that depends on it.
Trying it on a Hadoop catalog shows the limit:
CREATE VIEW demo.vw.v1 AS SELECT id FROM demo.vw.t;
-- java.lang.UnsupportedOperationException:
-- Creating a view is not supported by catalog: demo
Support also depends on the catalog. The Hadoop catalog used by these examples has no view support, which is why there is no runnable statement here. Iceberg views covers creating and versioning them.
145. How do you use Iceberg from Python without a Spark cluster?
Use PyIceberg. It loads a table through a catalog, plans the scan from Iceberg metadata and returns Arrow data that pandas or DuckDB can use.
Metadata pruning without a cluster.
No cluster or JVM is involved. The same metadata pruning applies, so a good filter means only a few files are downloaded.
| Good uses | Poor uses |
|---|---|
| Reading filtered slices for analysis or machine learning | Large joins |
| Inspecting metadata | Compaction |
| Small appends and overwrites from a service | Rewriting large tables |
Always pass a row filter and the list of columns to the scan. Reading the whole table and filtering in pandas downloads everything first.
The limits are those of one process. Memory bounds how much you can read, and delete files must be applied locally too, so read only the partitions you need. PyIceberg also doesn’t support everything the Java library does: write operations, delete types, transforms and format versions differ and change quickly between releases, so check the version you use against your table. DuckDB and some warehouses can read Iceberg directly as well, each with its own limits.
146. What programmatic APIs does Iceberg provide?
Iceberg provides a Java API, the core library that engines are built on, and implementations in other languages, including the Python library PyIceberg.
from pyiceberg.catalog import load_catalog
table = load_catalog("prod").load_table("shop.orders")
rows = table.scan(row_filter="status = 'PAID'",
selected_fields=("order_id", "amount")).to_arrow()
| Interface | What you can do with it |
|---|---|
Java Table API |
Read schema, partition spec, properties and snapshots; plan filtered scans; change schema or partitioning; add and remove files; group changes in a transaction |
| Java actions | Run maintenance such as compaction and orphan removal |
| PyIceberg | Load tables from a catalog, scan into Arrow, append, overwrite, delete, upsert and inspect metadata, with no Spark cluster |
The example loads a table and reads two columns for matching rows into Arrow. The filter is applied during planning, so only relevant files are read.
Choose by the job. SQL in an engine is the right tool for ordinary data work. The APIs suit platform tooling, custom ingestion and automation, such as a service that checks table health across a catalog.
Libraries differ in the format versions and delete types they support, so verify yours. Low-level file operations also bypass the checks an engine would apply: registering files that don’t match the schema, for instance, can leave a table returning wrong results.
147. How do you use Iceberg on AWS?
On AWS, Iceberg tables usually live in S3 and are registered in the AWS Glue Data Catalog, with EMR, Glue jobs, Athena or other engines doing the processing. A Spark catalog for this setup is configured like so:
spark.sql.catalog.prod = org.apache.iceberg.spark.SparkCatalog
spark.sql.catalog.prod.type = glue
spark.sql.catalog.prod.io-impl = org.apache.iceberg.aws.s3.S3FileIO
spark.sql.catalog.prod.warehouse = s3://my-bucket/warehouse
The iceberg-aws module supplies the Glue catalog and S3FileIO, which the project recommends over the S3A file system for S3 access.
| Service | What it does with Iceberg |
|---|---|
| Athena | Reads, writes and optimises tables |
| EMR | Runs Spark, Flink, Hive or Trino on them |
| Glue jobs | Read and write them |
| Redshift | Queries tables registered in the Glue catalog |
| Data Firehose | Delivers streaming data into them |
DynamoDB and JDBC catalogs are alternatives to Glue, though Glue is the simplest choice when you already use these services, since they all see the same tables.
Three practical checks save trouble. The Spark runtime jar doesn’t include the AWS SDK, so add iceberg-aws-bundle unless your platform provides it; a missing class error is the sign you forgot it. Service features and supported format versions differ, so verify each one you rely on, especially before upgrading a table. And grant identities access only to the table locations they need, while planning for S3 request throttling on busy tables.
148. How do you use Iceberg with Databricks?
Databricks works with Iceberg mainly through Unity Catalog, in three ways: managed Iceberg tables, foreign tables from another catalog and Delta tables that Iceberg clients can read.
CREATE TABLE main.shop.orders (order_id BIGINT, amount DECIMAL(10,2))
USING iceberg;
The USING iceberg clause matters. Without it, the table created is a Delta table.
| Option | Who maintains the table | External access |
|---|---|---|
| Managed Iceberg table | Databricks | Read and write through the Iceberg REST endpoint |
| Foreign table, for example from AWS Glue | The external catalog’s writers | Generally read only in Databricks; needs a refresh to see new snapshots |
| Iceberg reads on a Delta table, built on UniForm | Delta writers | Iceberg clients can read the generated metadata |
The choice mostly decides who is allowed to write. If other engines must write the same table, a managed Iceberg table is the natural fit. If Databricks is the writer and others only read, enabling Iceberg reads on Delta avoids changing the table. If another platform owns the data, use a foreign table.
Each option has limits. For example, Iceberg reads at format version 2 can’t be combined with deletion vectors, while version 3 handles them differently, and some data types and partition expressions aren’t supported on managed tables. These change often, so check the current Databricks documentation for your workspace.
149. What should you know before using Iceberg with Amazon Athena?
Athena works with Iceberg tables registered in the AWS Glue catalog, creates them as format version 2 and handles row-level changes with merge-on-read.
| Topic | Athena behaviour, from the AWS documentation |
|---|---|
| Catalog | AWS Glue only, with Glue optimistic locking |
| Format version | Creates and operates on version 2 tables |
| Data formats | Parquet, ORC and Avro; Parquet with ZSTD by default |
UPDATE, DELETE, MERGE |
Always merge-on-read with position deletes; write.*.mode properties are ignored |
| Compaction | OPTIMIZE table REWRITE DATA USING BIN_PACK, with a WHERE on partition columns only |
| Cleanup | VACUUM expires snapshots and removes orphan files |
The merge-on-read rule has a practical effect. A table you configured as copy-on-write for Spark still accumulates delete files when Athena modifies it, so schedule compaction accordingly.
VACUUM is controlled by vacuum_max_snapshot_age_seconds, five days by default, and vacuum_min_snapshots_to_keep. The query role needs permission to delete objects. Without it, the documentation says the statement succeeds while no files are removed, which is an easy problem to miss.
Format version is the other check. The documentation describes version 2 and doesn’t mention version 3, so don’t upgrade a table that Athena reads without confirming support first. Cloud service behaviour changes, so verify these points against the Athena Iceberg documentation for your engine version.
150. How do you share Iceberg tables with consumers outside your platform or cloud?
Share tables by letting capable consumers read them through a catalog, serving other consumers through a query engine or API, or replicating a published copy for them.
Three routes to the same tables.
| Option | Suits | What it costs |
|---|---|---|
| REST catalog with short-lived credentials | Large reads by engines that speak Iceberg | Network egress; format and version compatibility |
| Query service | Tools without Iceberg support | You pay for compute and handle concurrency |
| Data API | Applications needing small results | An API to build and run |
| Replicated copy | Strict isolation between parties | Duplicate storage and delayed freshness |
Handing out access to the bucket looks easiest and is the weakest. Storage permissions can’t express table, row or column rules, and a consumer reading raw files has no way to know which are live, replaced or orphaned.
Whichever route you take, agree four things in advance: how consumers authenticate, what they may see, how access is audited and how schema or format version changes are communicated. Then insulate them from your internal operations. Publish a stable view or a tagged snapshot, so that your compaction, expiry and refactoring don’t break someone outside your team.
151. What do Apache XTable and Delta UniForm translate, and what is lost?
Both generate another table format’s metadata over existing data files, without copying data. XTable converts between Hudi, Delta Lake and Iceberg. UniForm goes only from Delta to Iceberg or Hudi.
The target metadata is a view. The data files stay shared.
| Apache XTable | Delta UniForm | |
|---|---|---|
| Direction | Among Hudi, Delta Lake and Iceberg | Delta to Iceberg or Hudi |
| When it runs | As a separate sync step | Asynchronously after Delta commits |
| Not carried over | Merge-on-read tables and deletion vectors | Deletion vectors, in its documented Iceberg compatibility version 2 mode |
| Other clients | Read the translated metadata | Read only |
Only the metadata is translated, and each format has features the others can’t express. Generated columns and similar format-specific behaviour may be missing on the target. And because the translation is asynchronous, the target view lags behind the source by some amount.
Treat translated metadata as a read-only view. Let only the source format’s writers change the data and run maintenance, because a compaction or expiry run from the target side could delete files the source still needs. Monitor the sync lag and read the current limitation list before building anything that depends on it.
152. How does Apache Arrow relate to Iceberg?
They sit at different layers. Iceberg is a table format, which decides which files make up a table. Parquet is a file format on disk. Arrow is a columnar format for data in memory, which engines and libraries use while they process it.
Three layers, three questions.
| Layer | Example | Concern |
|---|---|---|
| Table format | Iceberg | Which files, which schema, which snapshot |
| File format | Parquet, ORC, Avro | How rows are encoded on storage |
| In-memory format | Arrow | How column data is held and exchanged while a program runs |
Arrow shows up in two practical places. Engines such as Spark use Arrow-based vectors in the vectorized Parquet reader, so that decoded column data can be processed in batches. And Python libraries can hand you a table as Arrow data, for example PyIceberg’s scan, which lets you pass it to pandas or DuckDB without converting rows one by one (question 145).
Arrow doesn’t store anything. A table that is read through Arrow is still an Iceberg table with the same snapshots, manifests and deletes. If someone says a platform is “Arrow-based”, ask where: the storage format, the engine’s memory layout or the interchange between tools are different claims.
Migration, recovery, governance and operations
153. How do you migrate a Hive table to Iceberg?
You can migrate a Hive table with the snapshot, migrate or add_files procedures, or rewrite its data into a new Iceberg table.
Rehearse with snapshot, cut over with migrate.
| Procedure | What it does | Watch for |
|---|---|---|
snapshot |
Creates an Iceberg table over the source files and leaves the source unchanged | The new table doesn’t own the files, has expiry disabled and breaks if source files are removed |
migrate |
Replaces the table in place and keeps the original as a backup by default | Needs Parquet, ORC or Avro; refuses bucketed tables |
add_files |
Imports files into an existing table | Doesn’t check their schema; expiry may later delete them |
The first three register existing files: they read footers, record statistics and add a name mapping, without copying data. add_files refuses files already referenced by the table, but with check_duplicate_files => false adding a file twice duplicates its rows.
A typical sequence is to rehearse with snapshot, compare counts, aggregates and query plans, then pause writers and run migrate. To roll back, stop writers, drop the new table without purging and restore the backup, remembering that it lacks anything written after the cutover.
In-place migration is quick but keeps the old file sizes and partitioning. If those are poor, rewriting costs more now and avoids carrying the problem forward. See Hive to Iceberg migration.
154. Plan the migration of a very large Hive table to Iceberg with little downtime.
Take an inventory, rehearse on a copy, choose between in-place migration and a rewrite, cut over with a rollback plan and start maintenance immediately.
Rehearse first and keep a way back.
- Inventory. Formats, partitioning, file sizes, every writer and reader, engine support and permissions.
- Rehearse. Create a copy with
snapshotand compare counts, aggregates and query plans. - Choose the method.
- Cut over. Pause writers, migrate, validate, repoint jobs and views.
- Settle in. Keep the backup until confidence is established, and schedule compaction and expiry.
In-place migrate |
Rewrite into a new table | |
|---|---|---|
| Data copied | None | All of it |
| Cutover time | Short metadata step | Backfill first, then a short switch |
| Layout afterwards | Same as before | Whatever you design |
| Choose when | Files and partitioning are already good | Files are small or partitioning is poor |
For a very large rewrite with little downtime, backfill history partition by partition while the old table keeps serving, apply the changes that arrived meanwhile, validate and then switch.
The traps are outside the table. While a snapshot table exists, deleting source files breaks it. Old Hive-style writers must be stopped for good, and queries that filtered on partition columns need review. Prove correctness with per-partition checksums and the queries the business actually relies on.
155. What does register_table do?
register_table adds an existing Iceberg table to a catalog by pointing the new entry at one of its metadata files. No data is copied.
The metadata file already describes the whole table, so a catalog only needs to know where it is. That makes the procedure useful for three jobs: moving a table to another catalog, recreating an entry after a drop that kept the files, and bringing up a replicated copy during disaster recovery.
CALL <catalog>.system.register_table(
table => 'db.orders',
metadata_file => 's3://bucket/warehouse/db/orders/metadata/00042-<uuid>.metadata.json');
For a move, follow this order:
- Stop every writer and note the final metadata file location.
- Register it in the new catalog.
- Repoint clients and verify counts.
- Remove the old entry without purging.
If the files have moved to different storage, the absolute paths in metadata must be rewritten with rewrite_table_path and the files copied first.
Two mistakes lose data. Registering an older metadata file silently discards every later commit, and maintenance may then delete files that the newer history needs. Leaving the table writable in both catalogs is just as bad: their pointers diverge, and cleanup in one can remove files the other still references. Take the metadata location from the old catalog or metadata_log_entries, never by guessing from a directory listing.
156. Why can add_files return wrong query results, and how do you guard against it?
add_files registers existing files using the statistics in their footers, without checking that their schema matches the table. Query planning then trusts those values.
| Problem in the imported files | What happens |
|---|---|
| Incorrect bounds from a faulty writer | Planning silently skips a file containing matching rows |
| Mismatched column types or names | Errors, nulls or wrong values |
| Same file added twice with the duplicate check disabled | Duplicate rows |
| Files still used by another system | Iceberg expiry may later physically delete them |
The first is the nastiest, because nothing fails. A query returns fewer rows than it should, and the result looks plausible.
Type mismatches are easy to reproduce. The target table below has amount DECIMAL(10,2). One folder of Parquet files has a matching column, and the other was written with amount as DOUBLE:
CALL demo.system.add_files(table => 'af.target',
source_table => '`parquet`.`/tmp/ext_ok`'); -- added_files_count 2
CALL demo.system.add_files(table => 'af.target',
source_table => '`parquet`.`/tmp/ext_bad`'); -- also accepted: added_files_count 2
SELECT count(*) FROM demo.af.target; -- 10, answered from metadata
SELECT sum(amount) FROM demo.af.target;
The procedure accepted both folders without complaint, and count(*) returned 10 because it never opened a file. The sum failed when the reader reached the second folder:
java.lang.ClassCastException: DecimalVector cannot be cast to Float8Vector
Error reading file(s): file:/tmp/ext_bad/part-00000-....snappy.parquet
The table looked healthy until a query touched the bad files. Run one full-column read, such as SELECT sum(<each numeric column>), as part of every import check.
After importing, compare the minimum and maximum values computed from the data with the bounds recorded in the files table. Compare filtered counts with the source as well: if a filter returns fewer rows than the same condition applied after a full scan, the bounds are wrong.
When you don’t trust where the files came from, rewrite them with Iceberg, which computes statistics from the actual values. It costs a full rewrite and removes this whole category of risk, including the shared ownership of the original files.
157. Which legacy Hive data types cause trouble in a migration?
CHAR and VARCHAR, which become plain strings, and old INT96 timestamps, which are imported without usable statistics. Both can change query results or performance without any error.
The CHAR case is subtle because it depends on who wrote the data. Take a CHAR(5) column holding ab:
| Written by | Stored as | After migration |
|---|---|---|
| Spark | Padded to five characters | WHERE c = 'ab' finds nothing |
| Hive’s Parquet writer | Unpadded | A comparison with the padded value finds nothing |
Here is the effect after importing files that a Spark CHAR(5) column wrote, into a table that already holds a natively written ab:
CALL demo.system.add_files(table => 'ct.t', source_table => '`parquet`.`/tmp/ch_src`');
SELECT id, length(code) AS code_len, concat('[', code, ']') AS code_txt FROM demo.ct.t ORDER BY id;
id code_len code_txt
1 5 [ab ] <- imported from the CHAR(5) column
2 2 [ab] <- written by Iceberg
Both rows mean the same thing, but WHERE code = 'ab' returns only row 2 and WHERE code = 'ab ' returns only row 1. No error is raised either way, which is why the check has to be explicit.
A table with a long history may contain both forms. VARCHAR simply loses its length limit, so values longer than before can now be written.
INT96 columns remain readable, but manifests have no bounds for them, so filters on those timestamps can’t skip files. Values written under different time zone settings may also be shifted.
Check stored lengths before migrating, then trim CHAR values while rewriting or adjust every comparison. Enforce length limits in the pipeline, and compare edge values, including very old dates, on every engine. Running rewrite_data_files with rewrite-all restores timestamp statistics, but it can’t fix inconsistent strings; those need an explicit transformation.
158. How do you keep Hive and Iceberg consistent if both are written during a cutover?
Avoid writing to both independently. Have one authoritative write path, derive the other table from it and reconcile every batch.
One source of truth during a cutover.
Two separate writes can’t be made atomic. One succeeds and the other fails, a retry produces slightly different results, and soon the tables disagree with no way to say which is right.
If both really must be fed directly from the source, make each write idempotent per batch, record the batch ID in both and consider a batch published only when both have it.
A staged cutover keeps one source of truth at every moment:
| Stage | Authoritative | Other table |
|---|---|---|
| Shadow | Hive | Iceberg follows and is validated |
| Move readers | Hive | Consumers switch to Iceberg in groups |
| Move writers | Iceberg | Hive is fed from Iceberg |
| Retire | Iceberg | Hive removed |
Define when each stage ends, such as a number of consecutive batches that reconcile on counts, keys and checksums, and set a date for retiring the old table. An open-ended dual-write period doubles the cost and leaves nobody certain which numbers to believe.
159. Can you convert a Delta Lake table to Iceberg without rewriting data?
Yes, within limits. Iceberg’s Delta Lake module has a snapshot action that builds an Iceberg table over the existing Parquet files, replaying the Delta transaction history, and leaves the source unchanged.
DeltaLakeToIcebergMigrationActionsProvider.defaultActions()
.snapshotDeltaLakeTable("s3://bucket/delta/orders")
.as(TableIdentifier.of("db", "orders"))
.icebergCatalog(catalog)
.deltaLakeConfiguration(hadoopConf)
.execute();
The result is two tables sharing the same data files, which is convenient and fragile:
| Risk | Consequence |
|---|---|
VACUUM on the Delta source |
Files the Iceberg table references disappear |
| Expiry or orphan removal on the Iceberg table | Files the Delta table uses are deleted |
| Newer Delta features | The module documents older protocol versions (reader 1, writer 2), so deletion vectors and similar aren’t included |
The module is shipped separately from the engine runtimes. Its documentation forbids running cleanup on the new table, yet the action doesn’t set gc.enabled to false and uses the source’s location by default. Set both yourself.
For a permanent migration, stop the Delta writers, take the snapshot, validate it and then rewrite the data into the new table so that it owns its files. If consumers only need to read the data as Iceberg, metadata translation is the better choice.
160. How do you prove that a migrated table matches its source at large scale?
Pin or freeze both sides and compare in layers: row counts, checksums per partition, column aggregates and finally the individual rows of any partition that differs.
DROP TABLE IF EXISTS demo.shop.orders_copy PURGE;
CREATE TABLE demo.shop.orders_copy USING iceberg AS SELECT * FROM demo.shop.orders;
WITH source AS (
SELECT CAST(order_ts AS DATE) AS day, count(*) AS n,
sum(CAST(xxhash64(order_id, customer_id, amount, status, order_ts) AS DECIMAL(38,0))) AS h
FROM demo.shop.orders GROUP BY CAST(order_ts AS DATE)
), target AS (
SELECT CAST(order_ts AS DATE) AS day, count(*) AS n,
sum(CAST(xxhash64(order_id, customer_id, amount, status, order_ts) AS DECIMAL(38,0))) AS h
FROM demo.shop.orders_copy GROUP BY CAST(order_ts AS DATE)
)
SELECT * FROM source FULL OUTER JOIN target USING (day)
WHERE NOT (source.n <=> target.n AND source.h <=> target.h);
For each day, the query counts rows and sums a hash of every row, on both tables, and returns only the days that disagree. On the example copy it returns no rows.
| Check | Catches | Misses |
|---|---|---|
| Row counts | Missing or extra rows | Wrong values |
| Column aggregates | Many value errors | Errors that cancel out |
| Summed row hashes | Changed values and duplicates | Rare hash coincidences |
EXCEPT ALL on a partition |
The exact differing rows | Too costly for the whole table |
Summing hashes ignores row order, which is what you want between two tables with different file layouts, and it still notices duplicates. A matching checksum is strong evidence, not proof.
Most false alarms come from the comparison itself. Cast both sides to identical types, because a type or time zone difference changes the hash even when the data is right, and watch nulls and padded strings. Compare a fixed Iceberg snapshot against a source that isn’t changing. Finish by running the reports people care about on both.
161. Someone ran a DELETE without a WHERE clause, or a job overwrote a table with wrong data. How do you recover?
Stop writers and maintenance, find and tag the last good snapshot, restore it and verify.
The data isn’t gone. The DELETE created a new snapshot, and the previous one still references every file, as long as nothing expires it. So the first priority is to stop expiry.
SELECT made_current_at, snapshot_id, is_current_ancestor
FROM demo.shop.orders.history
ORDER BY made_current_at DESC LIMIT 5;
Find in history the snapshot that was current just before the delete, confirm it with a count using time travel and tag it so it can’t be expired while you work. Then pick the method by what happened afterwards:
| Since the delete | Restore with |
|---|---|
| No good commits | rollback_to_snapshot |
| Other jobs kept writing | INSERT ... SELECT ... VERSION AS OF for the missing rows |
A rollback in the second case would discard the legitimate writes along with the mistake. Afterwards, find and reprocess anything downstream that read the empty table.
The overwrite case usually comes from static overwrite mode: a job meant to replace one partition replaces the whole table. Prevent it with dynamic or explicitly filtered overwrites, validation on a branch before publishing and a row count guard that fails the job when the numbers are implausible.
To prevent a repeat, restrict delete permission, require predicates in reviewed jobs, tag known good states and retain snapshots for longer than it takes someone to notice a problem. If the snapshot has already been expired, only object versioning or backups can recover the data.
162. Someone deleted a manifest file from storage. Is the data lost?
Usually not. A manifest only lists files, so the data files are normally still in storage.
The effect is limited to snapshots that need the missing manifest: their queries fail with NotFoundException naming the .avro file, while other snapshots read normally.
Here is what it looks like. A table has two snapshots, and the newest manifest file is deleted from storage by hand. A tag marks the first snapshot:
SELECT count(*) FROM demo.d2.t;
NotFoundException: Failed to open input stream for file:
<warehouse>/d2/t/metadata/b9753d82-7929-44ac-92ac-273dcc29d3b1-m0.avro
Caused by: FileNotFoundException: File ... does not exist
SELECT * FROM demo.d2.t VERSION AS OF 'first_load';
1
2
The current snapshot fails and names the exact manifest, while the earlier snapshot, which does not use it, still reads normally. The data files were never touched.
First stop writers and pause maintenance. This matters more than it looks: orphan removal could now consider the files that only the broken manifest listed as unreferenced, and delete them.
- Restore the exact manifest from object versioning or a backup. This fixes everything.
- If that’s impossible, roll back to the newest snapshot that doesn’t use it, and reload newer data from the source.
- If neither works, rebuild the table, preferably by reloading from the source.
CALL demo.system.rollback_to_snapshot('shop.orders', <last good snapshot id>);
Salvaging data files by hand is risky. The data directory also holds replaced and orphaned files, and add_files imports whole directories without applying delete files, which brings back deleted rows and creates duplicates. If you must, copy only files you know were live into a staging location and reapply the deletes.
Protect against this with versioned buckets, no lifecycle rules on metadata paths and delete permission restricted to maintenance jobs. Note the contrast: a missing manifest can usually be recovered from, while a missing data file means rows are lost until you reload them.
163. The catalog entry is gone or points to a missing metadata file. How do you recover?
If the table’s files survive, you can recreate the entry by registering the table from a metadata file.
- Stop every writer.
- List the
metadata/directory and find candidate metadata files. - Pick the newest valid one and confirm that its manifest lists and manifests exist.
- Register it under a temporary name.
- Validate counts and key queries, then swap to the real name.
CALL demo.system.register_table(
table => 'shop.orders_recovered',
metadata_file => '<full path to the metadata.json>');
Choosing the right file is the hard part. Too old, and every commit after it silently disappears. The highest version number isn’t automatically right either, because a commit can write its metadata file and then fail to make it current.
| Evidence | Why it helps |
|---|---|
| Catalog backups | Show the pointer at a known time |
| Catalog audit logs | Show which commits succeeded |
| The metadata log inside candidate files | Shows the chain of previous versions |
Never leave two catalog entries writing to the same table. And make this recovery possible in advance: back up catalog state, record metadata locations and keep enough storage history that the files a restored pointer refers to still exist.
164. A table was dropped with PURGE, but the bucket has versioning. How do you recover it?
Restore the deleted object versions, then register the latest metadata file in the catalog again.
With versioning enabled, a delete usually adds a delete marker and keeps the previous version. The data is recoverable until a lifecycle rule removes old versions, so act quickly.
- Pause jobs and any lifecycle rules.
- Find the table location from catalog logs, backups or job configuration.
- Remove the delete markers, or copy previous versions back, for the newest metadata JSON file, its manifest lists and manifests and every data and delete file they reference.
- Register the table under a temporary name.
- Validate counts, then rename.
CALL demo.system.register_table(
table => 'shop.orders_restored',
metadata_file => 's3://bucket/warehouse/shop/orders/metadata/<latest>.metadata.json');
The metadata file alone is not enough. Every file reachable from it has to be back, or queries fail on whatever is missing. Files stored outside the table location, such as imported ones, need restoring separately.
Anything already removed by a lifecycle rule is gone, so your recovery window equals your version retention. Rehearse on a test table: restoring millions of objects takes planning, tooling and real time, and an incident is a bad moment to discover that.
165. A pipeline bug corrupted hundreds of related tables. How do you restore them to one point in time?
Stop writers, then roll each table back to the snapshot that was current at a chosen moment, in dependency order. Iceberg has no cross-table transaction, so you coordinate this yourself.
- Stop writers, snapshot expiry and orphan removal.
- Choose the moment just before the first bad write.
- Find each table’s snapshot for that moment in
historyand record the plan. - Roll back table by table.
- Reset bookmarks, streaming checkpoints and source offsets.
- Validate relationships between tables before restarting anything.
CALL prod.system.rollback_to_timestamp('db.orders', TIMESTAMP '2026-11-26 02:00:00');
CALL prod.system.rollback_to_timestamp('db.customers', TIMESTAMP '2026-11-26 02:00:00');
Step 5 is easy to forget and undoes the whole effort. A stream whose checkpoint is ahead of the restored table believes the removed data was processed and never replays it.
A timestamp only approximates consistency, because related tables commit at different moments. Where jobs record a batch ID in snapshot summaries, restore by batch instead. Better still, tag a consistent set of snapshots after each successful run, so there is a known good point to return to.
With hundreds of tables, generate the calls from a script, review them before running and save the previous snapshot IDs, so that the restore itself can be undone. Retention must be longer than the time it takes to notice such a bug.
166. Queries fail with a missing data file after a cleanup job. How can that happen, and how do you respond?
Cleanup deletes live files when retention is too short, table locations are shared, paths don’t match or something outside Iceberg removes objects.
| Cause | How it happens |
|---|---|
| Orphan age too short | Files of a write still in progress are removed before the commit |
| Shared location | One table’s cleanup sees another’s files as orphans |
URI mismatch with prefix_mismatch_mode => 'DELETE' |
Live files look unreferenced |
| Table registered in two catalogs | Each one’s maintenance ignores the other’s commits |
| Storage lifecycle rules or manual deletion | Objects vanish without Iceberg knowing |
The failure looks like this. Create a table with two inserts, delete one of its data files from storage, and query it:
SELECT count(*) FROM demo.ms.t; -- 20
SELECT sum(id) FROM demo.ms.t;
count(*) 20 <- answered from metadata, the missing file is never opened
sum(id) ERROR org.apache.iceberg.exceptions.NotFoundException:
File does not exist: file:/tmp/iw/ms/t/data/00000-0-....parquet
A count that still works is a trap: it makes the table look healthy while real queries fail. Test with a query that reads column data, not with count(*), when you check a table after a cleanup incident.
To respond, stop cleanup and writers at once so the damage doesn’t spread. Compare all_data_files with what is in storage to list exactly what is missing. Restoring from object versions or backups is the only way to get the same files back. Where that is impossible, remove the broken references and reload the data from a source, checking every affected snapshot and not only the current one.
Prevention is cheap by comparison: one location per table, generous retention, reviewed dry runs, bucket versioning, no lifecycle rules on table paths and a scheduled job that checks referenced files still exist.
167. Rows that were deleted have reappeared in query results. What could have happened?
Start by finding out whether the delete was undone, bypassed or never applied. Several different causes produce the same symptom.
| Cause | How it happens | How to confirm |
|---|---|---|
| The table was rolled back or restored | A rollback or an older metadata file made a snapshot from before the delete current (question 23) | history shows the current snapshot changing, and is_current_ancestor is false for the delete |
| A reader ignores the delete files | A tool that reads the Parquet files directly, or an engine without delete support, skips the delete files | The same query gives different counts in different tools |
| Files were re-imported | add_files or a copy put the original files back into the table |
entries shows the files added after the delete |
| The key was inserted again | A later commit wrote the same key, and a delete only affects older data (question 55) | The row’s data is newer than the delete |
| A replay reapplied events | A change stream replayed old inserts (question 120) | Duplicate event IDs in the source |
SELECT made_current_at, snapshot_id, is_current_ancestor
FROM demo.shop.orders.history
ORDER BY made_current_at DESC;
Then use time travel to compare the table just before and just after the delete, and again after the rows came back. The first commit where they return is your suspect, and its summary tells you which job wrote it (question 169).
Compaction deserves a separate check. An Iceberg compaction applies the deletes while it rewrites, so it shouldn’t bring rows back. If it did, look for a custom rewrite that copied files without applying delete files, or for a tool that wrote new files without going through Iceberg’s rewrite action. Test every rewrite path against position deletes, equality deletes and a concurrent update before trusting it.
168. A job finished successfully, but some records are missing from the table. How do you investigate?
A successful job only means that no error was raised. Compare what the job meant to write with what the table’s commit actually recorded, then look for a write that went somewhere or did something unexpected.
Begin with the snapshot the job produced. Its summary says how many records and files the commit added and removed.
SELECT committed_at, operation,
summary['added-records'] AS added_records,
summary['deleted-records'] AS deleted_records,
summary['spark.app.id'] AS app_id
FROM demo.shop.orders.snapshots
ORDER BY committed_at DESC
LIMIT 5;
Then check the usual causes in order:
- The operation was an overwrite. An
overwritewith a largedeleted-recordsfigure replaced data. A staticINSERT OVERWRITEreplaces the whole table, and a dynamic one replaces every partition it touches (question 50). - The write went to a branch. If
spark.wap.branchis set, the commit lands on that branch andmainnever sees it. Checkrefsand the branch’s contents (question 172). - The records never reached the writer. A filter, a join or a deduplication step upstream can drop rows without any error. Compare counts between the source and the input of the write.
- A
MERGEmatched differently than expected. Rows that didn’t match, or that matched and were removed by aWHEN MATCHED ... DELETEclause, don’t show up as inserts (question 18). - A later commit removed them. Another job’s overwrite or delete may have run after yours. Walk the snapshot list forward from your commit.
- The reader is looking at an older state. A cached table or a different catalog entry can lag behind (question 139).
Count the rows before and after the job with time travel, rather than only the current table. If the job’s own snapshot shows the right added-records and a later one removed rows, the cause is a different job.
To prevent a repeat, have the job record its expected count and check it against the snapshot summary after the commit, and write a batch ID into the summary so one query tells you whether a batch landed (question 105).
169. A downstream report changed unexpectedly. How do you find which commit changed the table?
Work down the metadata the way you would read git log: find the commit, read what it did, then compare the table before and after.
1. Find the suspect commit. history says when each snapshot became current, and snapshots says what each one did. Join them.
SELECT h.made_current_at, s.snapshot_id, s.operation,
s.summary['added-records'] AS added_records,
s.summary['deleted-records'] AS deleted_records,
s.summary['spark.app.id'] AS app_id
FROM demo.shop.orders.history h
JOIN demo.shop.orders.snapshots s ON h.snapshot_id = s.snapshot_id
ORDER BY h.made_current_at DESC
LIMIT 10;
Look for a commit just before the report changed. An overwrite or delete with a large deleted-records figure is a better suspect than a small append. A replace is compaction and doesn’t change query results. The application ID tells you which job wrote it. Also check is_current_ancestor in history: a false row is a snapshot that was rolled back, so somebody has already undone it.
2. Compare the table before and after. Take the suspect snapshot and its parent from the snapshots table, then compare the rows each one returns.
SELECT * FROM demo.shop.orders VERSION AS OF <parent_snapshot_id>
EXCEPT
SELECT * FROM demo.shop.orders VERSION AS OF <suspect_snapshot_id>;
Run it in both directions to see what disappeared and what appeared. Replace the two placeholders with the IDs from step 1.
3. See which files the commit touched. The entries table lists the manifest entries, with the snapshot that added or removed each file.
SELECT status, data_file.file_path, data_file.record_count
FROM demo.shop.orders.entries
WHERE snapshot_id = <suspect_snapshot_id>;
A status of 1 is a file added and 2 a file deleted. A commit that deleted a file and added a similar one is a rewrite, and one that only deleted files removed data.
4. Rule out changes that create no snapshot. A new column, a renamed column or a changed property writes a new metadata file but no snapshot, so none of the queries above shows it. Check metadata_log_entries for a metadata file whose latest_snapshot_id is the same as the one before it, which means that file came from a change that wasn’t a commit of data. A report can also change without any commit if a reader uses a cached copy of an older table state.
This works only while the snapshots exist. If expiry has removed the commit you are after, the summary and the files are gone, which is one more reason to keep retention longer than the time it takes people to notice a wrong report.
170. Spark and Trino report different counts for the same table. How do you investigate?
First make sure both engines read the same catalog and the same snapshot. Then compare how they handle deletes, types and caching.
Most of these cases are freshness, not correctness. Check the metadata location each engine resolves and pin both queries to one snapshot ID, watching for caches, branch settings and time travel clauses.
| Result with the snapshot pinned | Where to look |
|---|---|
| Counts agree | One engine was showing older data |
| Counts differ without any filter | Engine feature support, often delete files |
| Counts differ only with a filter | Time zones, timestamp types, case sensitivity, null handling or a pruning bug |
Then narrow it down. Count per partition, then per file, until you can show the specific rows that differ. Reproduce them on a small table and check both engines’ release notes. If a particular feature turns out to be the cause, compacting can remove it from the table as a temporary measure.
SELECT snapshot_id, committed_at, summary['total-records'] AS total_records
FROM demo.shop.orders.snapshots
ORDER BY committed_at DESC LIMIT 3;
Don’t use total-records from a snapshot summary as the referee. It counts records in data files and doesn’t subtract merge-on-read deletes, so it can disagree with both engines.
171. An auditor needs a report exactly as it ran six months ago. Is that possible?
Only if every snapshot the report read still exists. Normal retention won’t keep one for six months, so this has to be designed before the report runs.
At each reporting close:
- Tag the snapshot with a long retention, or none.
- Record the snapshot ID of every table the report read, including lookup tables.
- Keep the query and the application version.
- Note settings that affect results, such as the session time zone.
Reading by tag also applies that snapshot’s schema, so later column changes don’t alter the result. If any one input has expired, the report can’t be reproduced exactly.
SELECT name, type, snapshot_id, max_reference_age_in_ms
FROM demo.shop.orders.refs;
The refs table shows each tag and how long it will be kept; a null maximum age means it doesn’t expire by age.
Every tag keeps its files alive, so years of monthly closes can hold a lot of storage. Copying the reported data into an archive table may then be cheaper and easier to explain. Be clear with the auditor about guarantees: time travel is not a backup, and it isn’t tamper proof, since anyone with the right permission can drop a tag. Control that permission, and use immutable storage if the audit demands it.
172. What is write-audit-publish?
Write-audit-publish means writing new data where consumers can’t see it, validating it, and publishing it with a single metadata operation only if it passes.
Without it, a bad batch is visible the moment it commits, and fixing it means rolling back after dashboards have already shown it.
ALTER TABLE demo.shop.orders CREATE BRANCH audit;
INSERT INTO demo.shop.orders.branch_audit (order_id, customer_id, amount, status, order_ts)
VALUES (5001, 1, 10.00, 'NEW', TIMESTAMP '2026-11-03 09:00:00');
SELECT count(*) FROM demo.shop.orders.branch_audit WHERE amount < 0;
CALL demo.system.fast_forward('shop.orders', 'main', 'audit');
The branch receives the insert while main stays as it was. The check finds no negative amounts, so fast_forward moves main to the branch’s snapshot and reports the old and new references. If the check had failed, you would simply not publish.
| Branch | WAP ID | |
|---|---|---|
| Write | Commit to a named branch | Set write.wap.enabled and a session spark.wap.id, which stages an unreferenced snapshot |
| Publish | fast_forward, only if main hasn’t diverged |
publish_changes applies it as a new snapshot; fails if the ID was used for several snapshots |
Useful audits compare counts with the source and check nulls, value ranges, duplicate keys and business totals.
If main moves while an audit runs, the fast-forward is refused; recreate the branch from the new head or cherry-pick the audited commit. Give audit branches a retention period so that failed runs don’t hold files forever. A branch hides data from ordinary reads, but it is not access control.
173. What is the difference between a branch and a tag?
Branches and tags are named references to a snapshot. A branch moves forward as you commit to it, while a tag stays fixed on one snapshot.
An audit branch holds a snapshot that main does not see.
| Branch | Tag | |
|---|---|---|
| Accepts writes | Yes | No |
| Typical use | Audits, experiments, backfills | Releases, month-end states |
| Protects its snapshot from expiry | Yes | Yes |
ALTER TABLE demo.shop.orders CREATE BRANCH etl_test RETAIN 7 DAYS;
ALTER TABLE demo.shop.orders CREATE TAG month_end RETAIN 365 DAYS;
RETAIN limits how long the reference itself lives, measured from the age of its snapshot, after which expiry may drop it. In the example etl_test lasts 7 days and month_end a year. main is never dropped. Branches can also keep a minimum number of snapshots.
Write to a branch by naming it, as in table.branch_<name>, or by setting spark.wap.branch for the session. The session setting works only when the table has write.wap.enabled=true; otherwise writes go to main without any warning.
Creating a reference is cheap because it shares data files with main. Keeping one for a long time is not free, since it stops old files from being deleted. The schema belongs to the whole table, not to a branch. To publish a branch, use fast_forward if main hasn’t moved since, or cherry-pick the commit. There is no three-way merge as in Git.
174. How do you test pipeline changes against production-sized Iceberg data safely?
Use branches to check outputs, pinned snapshots for repeatable inputs and separate copies for anything destructive.
| Need | Tool |
|---|---|
Write test output that readers of main don’t see |
A branch on the production table |
| Compare old and new logic on identical input | Time travel to a pinned snapshot |
| Rehearse migrating a Hive or Spark table | The snapshot procedure, which doesn’t apply to Iceberg sources |
| Try DDL or layout changes | A copy of representative partitions |
Here is the branch route on a 100-row table. The changed pipeline writes 50 new rows and deletes 10 of the old ones, but only on a branch:
ALTER TABLE demo.br.orders CREATE BRANCH test_run RETAIN 3 DAYS;
INSERT INTO demo.br.orders.branch_test_run SELECT id + 1000, 99 FROM range(50);
DELETE FROM demo.br.orders.branch_test_run WHERE order_id < 10;
SELECT 'main' ref, count(*) rows, sum(amount) total FROM demo.br.orders
UNION ALL
SELECT 'test_run', count(*), sum(amount) FROM demo.br.orders VERSION AS OF 'test_run';
ref rows total
main 100 1000
test_run 140 5850 <- 100 + 50 - 10 rows; readers of main see none of it
When the comparison is done, ALTER TABLE demo.br.orders DROP BRANCH test_run discards the experiment. refs goes back to listing only main, and main still has its 100 rows. The data files the branch wrote become unreferenced and are removed by the next snapshot expiry.
A trustworthy comparison follows a recipe: pin the input snapshots, run both versions, write each to its own branch or table, compare row counts, key uniqueness, aggregates and a sample of differing rows, then drop the branches. Without pinning, the two runs read different data and the differences tell you nothing.
Branches and snapshot tables share data files with their source, which is why they are cheap and also why maintenance needs care. Never run expiry on a table created with snapshot, since its files belong to the source. Test copies contain real data, so the same access rules apply. For unit tests in CI, small tables in a local catalog are enough.
175. How do you backfill years of history into a table that readers and writers are using?
Readers can’t see a half-written batch, because each commit is atomic and each query reads one snapshot. The real questions are what they see between batches, and whether the backfill collides with the live writers.
The two main designs trade isolation against effort:
| Approach | Readers see | Watch out for |
|---|---|---|
Backfill in batches on main, one old date range per commit |
History appearing gradually, range by range | A report that spans the range can mix filled and unfilled periods |
| Write to a branch, validate, publish | Nothing until the publish, then everything at once | fast_forward is refused if main has moved, and on a busy table it usually has |
Backfilling on main suits the common case, where live writers add the newest data and the backfill fills old partitions. An append to new partitions and an overwrite of old ones touch different files, so they don’t conflict, and the commit retry handles the rest.
SET spark.sql.sources.partitionOverwriteMode=dynamic;
INSERT OVERWRITE demo.shop.orders
SELECT * FROM demo.shop.orders_history
WHERE order_ts >= TIMESTAMP '2023-01-01' AND order_ts < TIMESTAMP '2023-02-01';
Each statement replaces the partitions for one month, so a failed or repeated run produces the same table. Loop over the months, and check counts against the source after each one. Question 50 explains why dynamic mode needs care when a table has more than one partition field.
If consumers must never see a partial history, use a branch when main is quiet, or load a separate table, validate it and publish it with a view or a single INSERT. Pick a branch only if you can pause other writers or retry from the new head, because question 172 shows the fast-forward fails once main has moved on.
Other points apply either way:
- Sort or cluster the backfill data and let it write files near the target size. A backfill that writes thousands of small files only creates a compaction job.
- Throttle the batch size so that the backfill doesn’t delay the commits of the live jobs.
- Expect orphan files from failed batches, and remove them later with the age limit applied (question 78).
- Compact and expire only after the load has been validated. Expiring too early removes the snapshot you would roll back to.
176. How do you honour a right-to-erasure request?
Delete the rows, rewrite the files that held them, remove every reference and snapshot that preserves old versions, then clean up storage.
A DELETE statement alone satisfies none of that. It creates a new snapshot without the rows, while earlier snapshots still return them. With merge-on-read, even the current data file still contains the values; the delete file only hides them.
Each step removes another way the data can survive.
Each step removes a different way the data can survive. A forgotten tag or branch keeps everything it references. Old metadata can hold identifiers in column statistics and partition values until it expires. And the same person’s data usually also exists in raw tables, derived tables, exports, object versions and backups, all of which need the same treatment.
Verify against every retained snapshot, not only the current one.
The process is far easier when designed in from the start: keep personal data in few tables, cluster by the subject key so that deletes rewrite little, set snapshot retention shorter than the legal deadline and record evidence of each run. An alternative is to encrypt each subject’s data with its own key and destroy the key on request.
177. How do you prove to an auditor that a deleted record is really gone?
Show that no retained snapshot or reference can return it, that no live file still holds it, and that the old files were removed from storage. Keep the output of each check as evidence.
A DELETE alone proves nothing, as question 176 explains. The proof therefore follows the same steps as the erasure itself.
1. The delete commit. Find it in snapshots and record its ID, time and operation.
2. Nothing retained can return the record. List every snapshot and every branch and tag, then query each one for the key.
SELECT name, type, snapshot_id FROM demo.shop.orders.refs;
SELECT snapshot_id, committed_at FROM demo.shop.orders.snapshots ORDER BY committed_at;
SELECT count(*) FROM demo.shop.orders VERSION AS OF <snapshot_id>
WHERE customer_id = 42;
Every count must be 0. A forgotten tag that points to a pre-delete snapshot is the usual failure. Once expiry has run, this list should be short.
3. No live file still holds it. With merge-on-read, a delete file only hides the row. Compaction has to rewrite the data file.
SELECT content, count(*) FROM demo.shop.orders.files GROUP BY content;
For the affected partitions, check that the data files are new ones written after the compaction and that no delete files remain against them. For the strongest evidence, read a rewritten file directly with a Parquet reader and confirm the key isn’t in it.
4. The old files are gone. Keep the expire_snapshots output, which counts the data files it deleted, and run remove_orphan_files with dry_run. An empty result shows nothing unreferenced is left. Then list the storage prefix and confirm the old file paths no longer exist.
5. The copies outside Iceberg. Old metadata files can hold the key in column statistics and partition values until they are cleaned up. Object-store versioning, backups, replicas, caches and downstream tables hold copies too. Iceberg can’t prove anything about them, so list each one with its own deletion record.
Give the auditor the timeline: the delete, the compaction, the expiry and the cleanup, each with a timestamp, a job log and a query result. Say plainly which copies the evidence doesn’t cover.
178. How do you audit who changed or read a table?
No single source answers it. Table metadata records changes, but it isn’t an audit log, so combine it with catalog and storage logs.
| Question | Source | Limitation |
|---|---|---|
| What changed, and when? | snapshots and history |
Removed by expiry |
| Which job did it? | Summary keys such as application IDs | Written by the client, so not tamper proof |
| Which identity committed or loaded the table? | Catalog audit log | Misses direct file access |
| Who read the data? | Engine and storage logs | Table metadata records no reads |
A snapshot tells you that 10,000 rows were deleted at 02:14 by application X. It can’t tell you who launched that application unless the job recorded it, and it knows nothing about who queried the table.
You can see what a commit records without any extra setup. The summary of a Spark DELETE on a test table included:
operation overwrite
app-id local-1796205828622
app-name SparkSQL::172.17.0.2
engine-name spark
engine-version 3.5.9
iceberg-version Apache Iceberg 1.11.0
added-records 1
deleted-records 2
total-records 4
That identifies the engine and the application run, not the person. To add the person or pipeline, pass snapshot-property. options on a DataFrame write:
(df.write.format("iceberg")
.option("snapshot-property.job", "nightly_load")
.option("snapshot-property.run_id", "2026-12-02")
.mode("append").save("demo.dp.t"))
spark.sql("SELECT summary['job'], summary['run_id'] FROM demo.dp.t.snapshots")
-- nightly_load 2026-12-02
Require jobs to stamp identity and run ID into the summary with the snapshot-property. write option. Ship catalog and storage logs somewhere that writers can’t modify, and export snapshot records before they expire. Route access through the catalog, since anyone reading files directly leaves no trace in its log.
179. Which rules would you enforce from the start on a company-wide Iceberg platform?
Enforce the rules that are cheap to apply at the start and very expensive to retrofit.
| Rule | Incident it prevents |
|---|---|
| One catalog owns each table’s commits | Forked tables and lost writes |
| Storage access goes through the catalog | Permission bypass |
| One storage location per table | Cleanup deleting another table’s files |
| Every table has an owner, retention and maintenance from creation | Neglected tables nobody can decide about |
| Writes are idempotent and carry a run ID | Duplicates after reruns |
| Versioned storage, catalog backups, rehearsed restores | Mistakes that can’t be undone |
The first three are about correctness and security, and breaking them can destroy data. The last three decide whether a bad day takes an hour or a week.
Rules in a wiki are ignored, so build them into the platform: creation defaults and overrides, permissions that make the unsafe path impossible and automated audits that report exceptions. Allow exceptions when needed, each with a named owner and an expiry date. And treat format version upgrades as a platform decision, made only once every engine using a table supports the new version, since there is no way back.
180. What do you monitor on an Iceberg platform?
Monitor four things: freshness, table health, reliability and cost.
| Area | Alert when |
|---|---|
| Freshness | Time since the last commit exceeds its target |
| Table health | Average file size falls; delete records or manifest count climb; the oldest snapshot exceeds retention |
| Reliability | Commit failures rise; catalog latency or error rate rises; maintenance is missed or changes nothing |
| Cost | Storage grows without matching data growth |
Metadata tables supply most of this: snapshots, files, manifests and all_files. This query is a starting point for freshness and history:
SELECT max(committed_at) AS last_commit,
count(*) AS snapshots,
min(committed_at) AS oldest_snapshot
FROM demo.shop.orders.snapshots;
On a platform with many tables, loop over the catalog, write the results to a monitoring table and let maintenance act on thresholds, so that people only look at exceptions.
Separate urgent from important. A stopped pipeline or failing commits justify waking someone. A slowly rising delete count belongs to scheduled work. And watch for maintenance that “succeeds” while selecting no files: the job dashboard stays green while the table keeps degrading.
181. What can Iceberg's metrics reporting tell you?
After planning a scan or committing a change, Iceberg produces a report describing what happened.
| Report | Contains |
|---|---|
| Scan | Planning time, manifests and data files scanned or skipped, delete files involved |
| Commit | Number of attempts, duration, files and records added or removed |
By default the reports are only written to the log. Set the catalog property metrics-reporter-impl to a class that implements MetricsReporter to send them to your monitoring system. REST catalogs can also receive them from clients.
spark.sql.catalog.prod.metrics-reporter-impl=com.example.PlatformMetricsReporter
Collected across many tables, they show problems early. Rising commit attempts mean writers are contending. A falling share of skipped files means the layout is no longer matching the queries, perhaps after a change in data distribution or a compaction that widened file ranges. Growing planning time points at metadata that needs maintenance.
The coverage is limited to clients that report: an engine without the setting is invisible. Combine reports, which describe activity, with metadata tables, which describe the table’s current state regardless of who wrote it.
182. Storage and compute costs for the lakehouse doubled. Where do you look?
Attribute cost to tables first, then cut retained history, repeated rewrites, small files and unnecessary scanning, in the order of what is actually large.
Without per-table figures you will optimise the wrong thing. Once you have them:
The storage part is easy to measure. A table of 5,000 rows is updated twice, which writes new files and leaves the old ones reachable from earlier snapshots:
SELECT 'live' AS what, count(*) AS files, sum(file_size_in_bytes) AS bytes
FROM demo.co.t.files
UNION ALL
SELECT 'all snapshots', count(*), sum(file_size_in_bytes)
FROM (SELECT DISTINCT file_path, file_size_in_bytes FROM demo.co.t.all_files);
files bytes
live 1 11,208
all snapshots 4 34,487 <- 3.1 times the live data
after expire_snapshots (retain_last 1)
live 1 11,208
all snapshots 1 11,208
Row counts never changed, yet the table held three times the bytes it needed. This ratio of everything reachable to what is live is the first number to compute for every table when a storage bill grows.
| Finding | Action |
|---|---|
| Much data reachable but not current | Shorten retention, drop old branches and tags |
| Orphan files and old object versions | Remove them |
| The same data stored in several layers | Drop redundant copies |
| Compaction rewriting the same files repeatedly | Narrow its scope and run it less often |
| Writers producing small files | Fix the writers |
| Queries scanning far more than they need | Improve partitioning, sorting and statistics |
| Small changes rewriting large files | Use merge-on-read or better clustering |
Ask what started when costs doubled, since a new job or a changed setting is often behind it.
Weigh both sides of every fix. Compaction spends compute and temporary storage to save query compute and requests, and on a table that is rarely read it can cost more than it saves. Report cost by table and owner, so the largest consumers are visible and someone has the authority to decide on retention.
183. How would you attribute lakehouse storage, compute and request costs to business teams?
Give every table an owner, measure storage from table metadata, tag compute with table and team, and attribute request costs from access logs by table path.
SELECT count(*) AS files, sum(file_size_in_bytes) AS reachable_bytes
FROM (SELECT DISTINCT file_path, file_size_in_bytes FROM demo.shop.orders.all_files) f;
This sizes everything reachable from any snapshot. DISTINCT is needed because all_files repeats files.
| Cost | Charge to | Measured from |
|---|---|---|
| Storage | Table owner | all_files and storage inventory |
| Maintenance compute | Table owner | Maintenance job history |
| Query compute | The team that ran the query | Engine query history |
| Requests | By prefix and identity | Access logs |
| Shared catalog | Everyone, by an agreed rule | Platform cost |
Table metadata can’t see orphan files or old object versions, so reconcile its totals with the storage inventory and report the difference as unowned cost; it tends to shrink once someone has to explain it. For tables shared by tenants, allocate storage by partition and query cost by caller.
Publish each figure next to the lever its owner controls, such as retention or compaction frequency. A bill alone rarely changes behaviour; a bill with a clear action does.
184. Can you move old Iceberg data to colder storage classes?
Only into storage classes that still allow immediate reads, because any file referenced by a retained snapshot may be needed at once.
Only classes that read immediately are safe.
| S3 storage class | Usable for table files? |
|---|---|
| Standard and infrequent access | Yes; some charge retrieval fees |
| Glacier Instant Retrieval | Yes; higher retrieval cost and a minimum storage duration |
| Intelligent-Tiering, automatic tiers | Yes |
| Intelligent-Tiering, optional archive tiers | No, objects need restoring first |
| Glacier Flexible Retrieval and Deep Archive | No, objects need restoring first |
A file in a class that needs restoring breaks every query that touches it, along with compaction and time travel.
The tempting rule, “move anything older than a year”, is dangerous, because file age says nothing about whether the file is current. A table that is rarely updated keeps old files in its live snapshot. Rules based on paths fail too when the object storage layout scatters files under hashed prefixes.
Prefer tagging objects through a process that reads Iceberg metadata and knows which files are genuinely cold. Never move metadata files to cold tiers. Remember that compacting cold data pays retrieval charges. If data is truly rarely read, an archive table with its own policy is cleaner than tiering inside an active one.
185. How do you replicate Iceberg tables to another region for disaster recovery?
Copy the data first, then metadata whose paths have been rewritten for the new location, and register that metadata in a second catalog.
A plain copy of the directory doesn’t work, because Iceberg metadata stores absolute paths. The copied metadata would still point at files in the primary region.
Replication copies files and registers rewritten metadata.
- Run
rewrite_table_pathon the primary. It writes rewritten metadata and position delete files to a staging area and produces a list of source and target paths. It copies nothing. You can skip it only if the target storage preserves the original paths. - Copy the data files.
- Copy the rewritten files.
- Register the metadata in the secondary catalog and validate.
- Rehearse failover, and failback too.
The order protects consistency: metadata should never arrive before the files it references. That is also why bucket replication alone isn’t enough. It delivers objects in no particular order and doesn’t replicate the catalog pointer, so the secondary may hold a metadata file whose data hasn’t arrived.
Set recovery point and recovery time objectives first, because they decide how often to replicate. Keep a single writer, and make sure expiry on the primary can’t remove files the secondary still needs.
Internals, comparisons and architecture
186. What does the table metadata file contain?
The table metadata file is a JSON document describing the whole table at one version: its structure, settings and snapshots.
| Contents | Examples |
|---|---|
| Identity | Format version, table UUID, location |
| Structure | Every schema and partition spec used so far, with the current ones marked; sort orders |
| Counters | Last assigned column ID and sequence number |
| Settings | Table properties |
| History | Retained snapshots with their manifest list paths, branches and tags, logs of earlier snapshots and metadata files |
You can read one directly. This is the top level of a real v1.metadata.json for a table that has just been created, with nested values shown as counts:
format-version 2 table-uuid ed0e2bcb-... location file:///tmp/iw/c4/u
last-sequence-number 0 last-updated-ms 1796207874594 last-column-id 1
current-schema-id 0 schemas (1) default-spec-id 0
partition-specs (1) last-partition-id 999 default-sort-order-id 0
sort-orders (1) properties (5) current-snapshot-id -1
refs (0) snapshots (0) statistics (0)
partition-statistics (0) snapshot-log (0) metadata-log (0)
A new table has one schema, one partition spec and no snapshots, and current-snapshot-id is -1. The last-partition-id of 999 is just the starting value for partition field IDs, which begin at 1000.
Every change writes a new file, and the catalog points at the latest. Loading this one document is enough for an engine to know how to read the table, without listing storage. The history of metadata files is visible through SQL:
SELECT timestamp, file, latest_schema_id, latest_sequence_number
FROM demo.shop.orders.metadata_log_entries
ORDER BY timestamp DESC LIMIT 3;
Each row shows when a version was written, which file it is and the latest schema and sequence number at that point.
Because the file carries every retained snapshot, it grows on tables that commit often and are never expired, making every commit read and write more. Expiring snapshots shrinks it. Deleting old metadata files is a different thing: it reduces clutter in storage but doesn’t make the current file any smaller.
187. Why does Iceberg reuse manifests?
Most commits touch a small part of a large table, so Iceberg writes new manifests only for the files that changed and points the new snapshot at the existing manifests for the rest.
Snapshot 100: M1, M2, M3
Snapshot 101: M1, M2, M4 M3 was rewritten as M4
Snapshot 102: M1, M4, M5 M2 was rewritten as M5
Each snapshot has its own manifest list, which is always new, but the manifests it names are shared. Snapshot 101 reuses M1 and M2 exactly as they were. M4 holds the entries that changed: the files the commit added, and the files it removed, marked as deleted. Old snapshots keep pointing at M3, which is why time travel still works.
Reuse keeps commit cost proportional to the change. An append of one file writes one small manifest and one manifest list, even if the table has millions of files. Rewriting every manifest on each commit would make commits slow and would create a full copy of the file metadata every time.
A reused manifest is not rewritten, so its entries keep the snapshot ID of the commit that first wrote them. That is why an existing entry can show an older snapshot ID than the current one.
Which manifests are reused depends on the operation. A fast append reuses all of them. A merge append can combine small manifests while it commits. A delete or overwrite rewrites only the manifests that hold the affected files. After many commits the table can end up with lots of small manifests, and rewrite_manifests regroups them so that planning reads fewer files.
188. What do the ADDED, EXISTING and DELETED manifest entry statuses mean?
Every entry in a manifest carries a status, 0 for existing, 1 for added and 2 for deleted, along with a snapshot ID. For an added or deleted entry the ID names the commit that did it. An existing entry keeps the ID of the commit that first added the file.
Read the status together with the snapshot ID in the entry.
The wording hides a trap. “Added” doesn’t mean “added by the current snapshot”. Run two inserts and then update one row of the first file:
DROP TABLE IF EXISTS demo.shop.status_demo PURGE;
CREATE TABLE demo.shop.status_demo (id BIGINT, v STRING) USING iceberg;
INSERT INTO demo.shop.status_demo SELECT /*+ COALESCE(1) */ id, 'a' FROM range(1000);
INSERT INTO demo.shop.status_demo SELECT /*+ COALESCE(1) */ id, 'b' FROM range(1000, 2000);
UPDATE demo.shop.status_demo SET v = 'z' WHERE id = 5;
SELECT status, snapshot_id, data_file.record_count AS records
FROM demo.shop.status_demo.entries
ORDER BY status;
Three entries come back. The file from the second insert still says 1, with the snapshot ID of that insert, because its manifest was reused untouched. The replacement file written by the update also says 1, with the new snapshot ID. The original first file says 2.
| Status | Meaning | Where you meet it |
|---|---|---|
| 0, existing | Carried into a rewritten manifest; the entry keeps the snapshot ID that added the file | After manifests are merged or rewritten |
| 1, added | New in the snapshot named by the entry | Fresh and reused manifests |
| 2, deleted | Removed in the snapshot named by the entry | Rewrites and deletes |
A deleted entry is a record of the removal. The physical file stays in storage until no retained snapshot needs it and expiry deletes it. To find what one commit added, filter on both status and snapshot ID, never on status alone.
189. What is the difference between a delete file and a deleted data file?
A delete file is a new file that lists rows to ignore. A deleted data file is a data file that the current snapshot no longer includes. One adds something to the table; the other takes something away.
Removing a whole data file can leave its delete file dangling.
You can produce both with merge-on-read:
DROP TABLE IF EXISTS demo.shop.delete_demo PURGE;
CREATE TABLE demo.shop.delete_demo (id BIGINT) USING iceberg
TBLPROPERTIES ('write.delete.mode' = 'merge-on-read');
INSERT INTO demo.shop.delete_demo SELECT /*+ COALESCE(1) */ id FROM range(1000);
INSERT INTO demo.shop.delete_demo SELECT /*+ COALESCE(1) */ id FROM range(1000, 2000);
DELETE FROM demo.shop.delete_demo WHERE id = 1500;
DELETE FROM demo.shop.delete_demo WHERE id >= 1000;
SELECT content, record_count FROM demo.shop.delete_demo.files ORDER BY content;
The first delete removes one row, so Iceberg keeps the data file and writes a delete file. The second removes every remaining row of that file, which can be done in metadata: the file simply leaves the snapshot. The query then shows one data file of 1,000 rows and still one delete file with one row, pointing at data that is no longer live.
| Delete file | Deleted data file | |
|---|---|---|
| What it is | A file of positions or key values | An entry marked as removed |
| Read by queries | Yes, while it applies | No |
content in files |
1 or 2 | Not listed |
| Storage freed | After it is no longer referenced and expiry runs | After expiry |
Neither kind of removal frees storage by itself. The leftover delete file is harmless to results. Here, calling rewrite_data_files with the remove-dangling-deletes option set to true rewrites no data and reports one delete file removed. It doesn’t catch every case, as question 58 explains.
190. What happens internally when Spark runs CREATE TABLE on an Iceberg catalog?
Spark parses the statement and hands it to the catalog, which writes the first metadata file and records the table. No data file, manifest or snapshot is created.
- Spark parses the DDL and resolves the catalog name, such as
demo. SparkCatalogconverts the Spark types into an Iceberg schema and assigns field IDs.- The
PARTITIONED BYclause becomes a partition spec; properties are attached. - The catalog writes the initial metadata file.
- The catalog records the table name with that metadata location.
On a Hadoop catalog the whole result of a CREATE TABLE is two small files:
shop/t/metadata/v1.metadata.json
shop/t/metadata/version-hint.text
A service catalog stores the pointer in its own database instead of the hint file.
Because there is no snapshot yet, a few things follow that surprise people. The snapshots and files tables are empty, time travel has nothing to travel to, and the table’s current snapshot is null in the Java API. The first write creates the first snapshot.
CREATE TABLE ... AS SELECT is different: it writes data and commits the table and its first snapshot together. If an interviewer asks whether creating a table can conflict, the answer is yes. Two clients creating the same name race at step 5, and the catalog lets only one succeed.
191. What do SnapshotProducer and TableOperations do in Iceberg's Java code?
SnapshotProducer builds a new snapshot for a write operation. TableOperations reads the current table metadata and commits a new version through whatever catalog is underneath.
Operation logic and catalog logic are separate layers.
SnapshotProducer is an abstract class inside Iceberg’s core. Each operation supplies what is specific to it, mainly which manifests make up the new snapshot and what the operation is called. The shared part writes the manifest list, validates and retries.
| Operation | Class that builds on it |
|---|---|
| Fast append | FastAppend |
| Merge append | MergeAppend, through MergingSnapshotProducer |
| Overwrite | BaseOverwriteFiles |
| Delete files | StreamingDelete |
| Row-level changes | BaseRowDelta |
| Compaction | BaseRewriteFiles |
TableOperations is the interface underneath. Its core methods are current(), refresh() and commit(base, metadata). The commit is the compare-and-swap from question 63, and this is where catalogs differ: metastore-style catalogs extend BaseMetastoreTableOperations and implement doCommit, while the Hadoop catalog has HadoopTableOperations, which relies on a rename.
These are internals and can change between releases. Application code should use the public Table API, such as newAppend() or newOverwrite(). Knowing the layers pays off when reading a stack trace. A ValidationException is a conflict between operations. A failure at the commit step needs its type read: CommitFailedException usually means another writer won the swap and Iceberg retries, while an unknown commit state or a service error points at the catalog or storage.
192. How do you inspect a table with the Java API?
Load the table from a catalog, then ask the Table object for its schema, spec, current snapshot, planned files and manifests.
Create a small merge-on-read table for it to read:
DROP TABLE IF EXISTS demo.shop.t PURGE;
CREATE TABLE demo.shop.t (id BIGINT, v STRING) USING iceberg
TBLPROPERTIES ('write.delete.mode' = 'merge-on-read');
INSERT INTO demo.shop.t SELECT /*+ COALESCE(1) */ id, 'a' FROM range(1000);
DELETE FROM demo.shop.t WHERE id = 5;
The program needs only the Iceberg runtime jar and Hadoop classes on the classpath, such as the jars shipped with Spark. Its argument is the warehouse location of a Hadoop catalog, here file:///tmp/iceberg-interview.
import org.apache.hadoop.conf.Configuration;
import org.apache.iceberg.*;
import org.apache.iceberg.catalog.TableIdentifier;
import org.apache.iceberg.hadoop.HadoopCatalog;
import org.apache.iceberg.io.CloseableIterable;
public class InspectTable {
public static void main(String[] args) throws Exception {
try (HadoopCatalog catalog = new HadoopCatalog(new Configuration(), args[0])) {
Table table = catalog.loadTable(TableIdentifier.of("shop", "t"));
System.out.println(table.schema());
System.out.println("operation: " + table.currentSnapshot().operation());
try (CloseableIterable<FileScanTask> tasks = table.newScan().planFiles()) {
for (FileScanTask task : tasks) {
System.out.println("data " + task.file().recordCount() + " rows, "
+ task.deletes().size() + " delete file(s)");
}
}
}
}
}
For that table it prints:
table {
1: id: optional long
2: v: optional string
}
operation: delete
data 1000 rows, 1 delete file(s)
| Type | Represents |
|---|---|
DataFile |
A file of table rows, with its partition and metrics |
DeleteFile |
Position or equality deletes |
ManifestFile |
One manifest, as listed in a manifest list |
FileScanTask |
A data file together with the deletes that apply to it |
Notice that planning reports 1,000 rows: record counts describe files, and deletes are applied only when data is read. currentSnapshot() returns null on a table that has never been written, so check before using it. Close the planned files, since they hold open readers.
193. What are Puffin files and table statistics?
Puffin is a file format for pieces of metadata too large or too binary to live in manifests. Iceberg uses it for deletion vectors and for table statistics.
A Puffin file is a simple container: a series of blobs followed by a footer that records each blob’s type, the fields it describes, the snapshot it belongs to and its position in the file. A reader can fetch just the blob it needs.
The table statistics stored this way are estimates of the number of distinct values per column, kept as Apache DataSketches theta sketches. Manifest bounds can tell an optimiser the smallest and largest customer ID, but not whether there are 100 customers or 10 million. That count drives join size estimates, join order and the choice of which side to build.
CALL demo.system.compute_table_stats('shop.orders');
The result is a real file next to the manifests. After the call on a two-snapshot table, the metadata directory contains:
metadata/6483482206762056802-07defd7c-a9f7-4580-a615-ca91576cec3a.stats
The name starts with the snapshot ID the statistics describe, and the file is a Puffin container holding the sketches. The procedure’s own output is the path of that file in a column called statistics_file.
compute_table_stats covers all top-level primitive columns unless you name some in the columns argument, and returns the location of the statistics file it wrote. Partition statistics are a separate file holding per-partition counts, produced by compute_partition_stats.
The sketches describe one snapshot and don’t refresh themselves, so recompute them after the data changes significantly. They also only help if your engine reads them. Compare query plans before and after rather than assuming an improvement.
194. How do Iceberg's transactions differ from Hive's transactional tables?
Hive transactional tables depend on the metastore’s transaction manager and ORC delta files. Iceberg commits by atomically swapping a metadata pointer, which any engine implementing the specification can do.
Two designs for atomic writes.
| Hive transactional tables | Iceberg | |
|---|---|---|
| State kept in | Metastore transaction tables and delta directories | Metadata files and a catalog pointer |
| Concurrency | Locks managed by the metastore | Optimistic validation at commit |
| Planning | Metastore partitions plus file listings | Manifests |
| File format | ORC | Parquet, ORC or Avro |
| Maintenance | Hive’s own compaction | Procedures run from your engine |
The architectural consequence is portability. A Hive table’s guarantees hold only if every writer uses Hive’s transaction manager correctly, so support in other engines has been uneven. Iceberg puts the protocol into an open specification and keeps the central service small.
Iceberg can still use a Hive Metastore, but only to hold the pointer to the current metadata file. The transaction machinery isn’t involved.
Migration has one catch: a transactional Hive table can’t simply be registered as Iceberg, because its delta files record changes and are not plain data files. Compact it and rewrite the data into the new table.
195. What are the Iceberg equivalents of Delta Lake's OPTIMIZE and VACUUM?
Delta Lake’s OPTIMIZE corresponds to Iceberg’s rewrite_data_files. VACUUM is split into two procedures, expire_snapshots and remove_orphan_files.
| Delta Lake | Iceberg |
|---|---|
OPTIMIZE |
rewrite_data_files |
ZORDER BY |
Z-order sort strategy inside the rewrite |
| Log checkpoints | rewrite_manifests reorganises metadata |
VACUUM |
expire_snapshots, then remove_orphan_files |
The split of VACUUM is the part people get wrong. Expiry deletes files that expired snapshots stop referencing. It never looks for files that no snapshot ever knew about, such as those from a killed job. Only orphan removal does that.
CALL demo.system.expire_snapshots(table => 'shop.orders', retain_last => 3);
CALL demo.system.remove_orphan_files(table => 'shop.orders', dry_run => true);
Defaults differ too. Delta retains seven days. Iceberg keeps five days of snapshots and treats unreferenced files older than three days as orphans, and that three-day limit should exceed your longest running write.
To reclaim space after a large delete, remember that two things may hold it. With merge-on-read the rows are still inside data files, so rewrite the affected files first. Then expire the old snapshots that reference the previous versions.
196. One platform on object storage must serve BI and machine learning. Iceberg, Delta Lake or Hudi?
Choose from the workload: which engines are involved, how often rows change, what governance already exists and how fresh the data must be.
Let the dominant requirement lead, then test.
| If this dominates | Favour |
|---|---|
| Several independent engines and a vendor-neutral catalog API | Iceberg |
| A Spark and Databricks platform | Delta Lake |
| High-rate keyed upserts and incremental pipelines | Hudi |
Engine support usually separates the options most sharply, so start by listing every system that must read and every system that must write. An existing catalog or permission model often settles the question before performance is considered. Freshness then determines the write mode and how much compaction work you are signing up for.
Machine learning raises reproducibility. All three offer time travel, so the real requirement is to pin the training data version and keep it, for example with an Iceberg tag that stops the snapshot expiring.
A good answer ends with a test, not a verdict. Take the two hardest workloads, run them on the actual engines with realistic data and measure both performance and operational effort. Metadata translation tools can delay the decision for read-only consumers, at the price of one more moving part to operate.
197. When would you not use Iceberg?
Avoid Iceberg when you need row-level transactions or millisecond lookups, when the data is small and simple, or when nobody will run the maintenance.
Three signs that Iceberg is the wrong tool.
| Requirement | Better fit | Why not Iceberg |
|---|---|---|
| Application database with constraints and fast row updates | PostgreSQL or similar | No row index or constraints; every commit writes files |
| High-rate point lookups | A key-value store | A lookup still plans and scans files |
| Small dataset, one reader | Parquet files or a database | The overhead buys little |
| Events between services | A log such as Kafka | Commits are not designed for per-message delivery |
| Sub-second, highly concurrent dashboards | A serving store or warehouse | Query latency depends on file scans |
| No one to compact and expire | A managed warehouse | Tables degrade without maintenance |
Iceberg’s costs are a catalog, maintenance jobs, care over small files in streaming and testing across engines. Large analytic data with long history and several consumers repays those costs comfortably.
The signals that it is time to adopt it are repeated partial-write incidents, painful schema or partition changes, planning slowed by huge partition counts, or a second engine needing the same tables. An interviewer usually wants to hear that you can name the cases where you would say no.
198. Design a lakehouse that spans an on-premises cluster and a cloud.
Give each table exactly one writer and one authoritative catalog, and replicate curated data between the two sites.
One writer per table, replicated across sites.
Decide ownership before choosing any tool. For each table, where does it live and which site writes it? Committing from both sides, through separate catalogs, forks the table’s history.
Then design around the link between sites:
- replicate curated tables instead of every raw file
- plan for rewriting absolute paths in replicated metadata
- account for latency and egress charges on cross-site reads
- use one identity and policy model on both sides
Migrate in phases: replicate first, move readers once they can be validated against the replica, then move writers table by table, keeping a way back at every step.
Assume things will go wrong in predictable ways: the link fails, one side upgrades its engine and starts writing features the other can’t read, or maintenance deletes files the other side still uses. Querying a table across the link is possible, but heavy readers are usually better served by a local replica.
199. Design Iceberg storage for many tenants.
Choose between a table per tenant, one shared table partitioned or bucketed by tenant, and a mix, based on tenant size and how much isolation they require.
| Design | Gains | Costs | Fits |
|---|---|---|---|
| Table per tenant | Strong isolation; separate retention, keys and restore | Very many tables to maintain | A few large or regulated tenants |
| Shared table | One thing to operate | Only logical isolation | Many small tenants |
| Hybrid | Large tenants get their own tables | Two patterns to support | Mixed sizes, the common case |
Isolation and operating effort rise together.
In a shared table, don’t partition by tenant ID if tenants are numerous or uneven: small ones produce tiny files and large ones produce skew. Bucket on a high-cardinality key to spread writes, sort by tenant so that a tenant filter skips most files, and enforce that filter through views or engine policies so no query can forget it.
Think about the lifecycle. Cost and quotas per tenant can be reported from files and partitions. Removing a tenant from a shared table needs deletes, file rewrites and snapshot expiry, while dropping a dedicated table is trivial. A tenant that outgrows the shared table can be copied to its own, rerouted and verified before its rows are deleted from the old one.
200. How would you design an Iceberg lakehouse for 10 PB of data?
Start from the workload and failure requirements, then design ingestion, layout, catalog, compute, maintenance and recovery so that each can scale and be observed on its own.
One catalog, one storage layer, independent compute and maintenance.
Ask first: daily ingest volume, freshness targets, update rate, number of tables, consumers and how much data loss or downtime is acceptable.
The numbers guide the layout. At 512 MB a file, 10 PB is around 21 million data files. Spread over hundreds of tables that is ordinary; concentrated in a few badly partitioned ones it is a planning problem.
| Area | Decision |
|---|---|
| Ingestion | Streaming and batch jobs with idempotent writes and controlled commit rates |
| Layout | Partition by how data is queried and retired; sort within partitions; keep partitions well filled |
| Catalog | One highly available catalog that owns every commit |
| Compute | Engines sized per workload, reading the same tables |
| Maintenance | A service that compacts, expires and cleans based on table metrics |
| Governance | Access through the catalog, owners and retention per table |
| Recovery | Versioned storage, catalog backups, cross-region copies where required, rehearsed restores |
| Observability | Freshness, planning time, file counts, delete share, commit failures, cost per table |
The usual failures at this size are organisational: nobody owns maintenance, one engine lags on features or retention grows unchecked. Assign owners early, and prove the design with a load test at realistic file counts and concurrency before migrating everything into it.
References
- Iceberg table specification
- Iceberg configuration for table properties and defaults
- Iceberg Spark procedures
- Iceberg reliability for the concurrency model
- Iceberg Spark writes
- Apache Iceberg architecture
- Apache Iceberg on Spark: the complete cheat sheet
- Running Iceberg in production
- The Iceberg write path
- Top Apache Spark interview questions
Trademarks
Apache Iceberg, Apache Spark, Apache Flink, Apache Kafka, Apache Hive, Apache Hudi, Apache Parquet, Apache ORC, Apache Avro, Apache Impala, Apache Polaris and Apache are either registered trademarks or trademarks of The Apache Software Foundation in the United States and other countries. Delta Lake is a trademark of the Linux Foundation.
Found this useful?
These posts and tools are free. If one saved you an afternoon, you can buy me a coffee.
Comments
Questions, corrections and reviews are welcome. Sign in with GitHub to post; comments are stored in this site's public GitHub Discussions.