Iceberg Snapshot Expiration: SQL Checks for Safe Cleanup
Plan Iceberg snapshot expiration with SQL inspection checks. Protect retained history, review branches and tags, and validate cleanup safely.
By jackey.ye · Updated: 2026-11-27
expire_snapshots removes snapshots committed before older_than, while preserving at least retain_last ancestors of the current state and every snapshot still reachable from a branch or tag. The safe sequence runs read-only first: inspect snapshots, history and refs, record what must survive, then run a gated CALL.
Three names get conflated here. Apache Iceberg is the open table format; expire_snapshots is the Spark SQL stored procedure in the system namespace (primary reference checked 2026-11-27); the Java API exposes ExpireSnapshots for the same operation. An Iceberg snapshot is a complete table state captured at a point in time — it's recorded as one row in the snapshots metadata table and points to a manifest list, which in turn points to the files that make up the table at that moment. It isn't a single data file, a metadata JSON file, or a commit sequence number.
Everything below applies to an Apache Iceberg table read and written through a configured Iceberg catalog with a supported Spark integration. Behavior on other engines, or on catalogs that don't expose the system namespace procedures, may differ.
This guide recommends no universal retained-hours figure and reports no benchmark or production measurement.
What does expire_snapshots actually remove?
The procedure removes snapshots committed before older_than (default: 5 days ago), except the retain_last most recent ancestor snapshots (default: 1) and any snapshot still anchored by a branch or tag, subject to that reference's own retention properties. Everything committed after older_than survives.
Expiration is metadata work first. Iceberg's maintenance guidance states that expiring old snapshots removes them from metadata, so they are no longer available for time travel, and that data files are not deleted until no snapshot usable for time travel or rollback still references them. That is why a table can lose snapshots without immediately losing storage.
The Spark action makes the ordering explicit. It computes which manifest lists, manifests and data files are no longer reachable, commits the new table metadata first, and only then issues deletes for the files the expiration released. Because the commit lands before any delete, a delete-phase failure leaves orphan files behind rather than a table pointing at files that no longer exist — which is exactly why a follow-up orphan cleanup matters.
The practical limitation is that expiration is not instantaneous, and on large tables the delete phase can be interrupted by a job restart or a lost executor.
What are the prerequisites for running Iceberg SQL procedures in Spark?
Prerequisites come before SQL, and each of these fails differently:
Configure an Iceberg catalog in the Spark session that the maintenance host can reach, and confirm your table resolves through it.
Qualify the procedure. Procedures are callable from any configured Iceberg catalog with
CALL, and all of them live in thesystemnamespace, so the shape iscatalog_name.system.procedure_name(...).Enable the Iceberg SQL extensions on Spark 3.x. Per the Spark procedures page, stored procedures require those extensions in Spark 3.x, while Spark 4.0 supports them natively — with case-sensitive procedure names (checked 2026-11-27).
Hold write permission on the table and its metadata location, because expiration commits table metadata.
Reserve a maintenance window with a single maintenance lane long enough to cover the delete phase.
Record a rollback or restore decision before the first run, including what you would do if a snapshot you needed is gone.
# Example configuration — validate in your target environment.
spark.sql.extensions=org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions
spark.sql.catalog.CATALOG_NAME=org.apache.iceberg.spark.SparkCatalog
spark.sql.catalog.CATALOG_NAME.type=REST
spark.sql.catalog.CATALOG_NAME.uri=<catalog-endpoint>
Catalog type is deployment-specific — REST, Hive, Glue and Nessie are all in use — so nothing below assumes one of them.
How do you inspect snapshots, history and refs before cleanup?
Build a small deterministic fixture so the inspection queries return something you can reason about, then read all three metadata tables before touching anything.
-- Example configuration — validate in your target environment.
CREATE TABLE demo.db.orders (order_id bigint, amount decimal(10,2)) USING iceberg;
INSERT INTO demo.db.orders VALUES (1, 10.00), (2, 20.00);
INSERT INTO demo.db.orders VALUES (3, 30.00);
INSERT INTO demo.db.orders VALUES (4, 40.00);
Metadata tables can use the Iceberg table name as a namespace, as documented in Spark queries, so the read-only checks take this form:
SELECT committed_at, snapshot_id, parent_id, operation, summary
FROM demo.db.orders.snapshots ORDER BY committed_at;
SELECT made_current_at, snapshot_id, parent_id, is_current_ancestor
FROM demo.db.orders.history ORDER BY made_current_at;
SELECT name, type, snapshot_id, max_reference_age_in_ms,
min_snapshots_to_keep, max_snapshot_age_in_ms
FROM demo.db.orders.refs;
Read them together. snapshots gives the current snapshot, its parent chain and the age spread; history marks the ancestry chain that retain_last protects through is_current_ancestor; refs names every branch and tag plus the retention properties keeping its snapshot alive. The refs layout below reproduces the documentation's example values only to fix column order — it is not a captured run:
name | type | snapshot_id | max_reference_age_in_ms | min_snapshots_to_keep | max_snapshot_age_in_ms |
|---|---|---|---|---|---|
main | BRANCH | 4686954189838128572 | 10 | 20 | 30 |
testTag | TAG | 4686954189838128572 | 10 | NULL | NULL |
Before any cleanup, record the current snapshot ID, a row-count baseline for the table, and the time both were taken. Everything you validate after the run is compared against that.
What survives expiration — retain_last, branches and tags?
retain_last protects only the ancestor chain of the current snapshot. Branches and tags protect the snapshots they reference, each according to its own retention properties. A snapshot ID from one table means nothing in another table's metadata, so protection rules are evaluated per table.
Protection mechanism | What it protects | Documented default | Check before running |
|---|---|---|---|
older_than | Everything committed after this timestamp survives | 5 days ago | Compare with the longest in-flight write |
retain_last | Ancestor snapshots of the current state, and nothing else | 1 | Count rows in history where is_current_ancestor is true |
snapshot_ids | Only the snapshots you name are expired | Not set | Confirm none of the named IDs is referenced by a ref |
Branch | Snapshots on that branch lineage | Reference retained forever by default | Read max_reference_age_in_ms, min_snapshots_to_keep, max_snapshot_age_in_ms from refs |
Tag | The single snapshot the tag anchors | Reference retained forever by default | Read max_reference_age_in_ms; confirm no other consumer depends on it |
Unreferenced snapshot past older_than | Nothing — it is removed | Not applicable | Confirm time-travel and incremental-read consumers do not use it |
The Branching and Tagging documentation supplies the reference retention properties: branches and tags carry a maximum reference age that controls when the reference itself expires, branches additionally define how many snapshots to retain and the maximum age of individual snapshots on the branch, and the default retention for both is forever. One more difference is easy to miss when you validate afterwards: querying a branch uses the table's current schema, while querying a tag uses the snapshot's own schema.
What do you lose after expiration — time travel, rollback, incremental reads?
Once a snapshot is expired you lose time travel to it, rollback to it, and any incremental read that uses it as an endpoint. A tag changes the answer for exactly one snapshot: it re-anchors that snapshot so expiration leaves it alone, for as long as the tag's own retention declares.
Concretely, SELECT ... VERSION AS OF <snapshot_id> fails once that snapshot is gone. rollback_to_snapshot accepts a snapshot_id or a ref, so a surviving tag still gives you a rollback target — but a snapshot expiration removed is no longer a target either way. An incremental read whose start or end snapshot no longer exists has no metadata to anchor the range, so it fails rather than returning partial data.
Two recovery paths are worth separating. "Recoverable by rollback" means the snapshot still exists in table metadata, so a rollback or time-travel query reconstructs the state; that is an operation on live history, with the same storage behind it. "Recoverable from an external copy" means you rebuild from data and catalog state you deliberately keep elsewhere. Iceberg's rollback is not a backup: it cannot restore a snapshot that expiration removed, and it does not protect against a deleted or corrupted object store.
To hold one snapshot across cleanup, anchor it with a tag. AS OF VERSION takes an actual snapshot ID, not a position in the commit sequence — so you must first read a real ID from the snapshots query and substitute it:
-- Example configuration — validate in your target environment.
-- 1) Read a real snapshot ID first, e.g.:
-- SELECT snapshot_id, committed_at FROM demo.db.orders.snapshots ORDER BY committed_at;
-- 2) Paste that ID in place of <snapshot_id_from_inspection> below.
ALTER TABLE demo.db.orders CREATE TAG `eow-01`
AS OF VERSION <snapshot_id_from_inspection> RETAIN 30 DAYS;
The placeholder is not a runnable value. A small literal such as 3 will almost never match a real Iceberg snapshot ID, and the statement will fail because no such snapshot exists. Always take the ID from the inspection query output.
Once created, the tag reference and the snapshot it points to are retained according to the tag's own retention policy — the declared RETAIN period above — for as long as that policy keeps them. A tag created without RETAIN follows the default reference retention until you remove it.
How do expire_snapshots and remove_orphan_files differ in risk?
Expiration is metadata-aware and preserves references that metadata still shows as reachable. Orphan-file removal is not: it compares a filesystem listing against metadata and can delete files a live write has produced but not yet committed. That difference, not the command syntax, is the risk.
Operation | What it inspects | Default age guard | Dangerous conditions | Verification signal |
|---|---|---|---|---|
expire_snapshots | Snapshot metadata, manifest lists, manifests and the data files they reference | older_than = 5 days ago; retain_last = 1 | older_than shorter than the longest write; a consumer still reading an expired snapshot ID; an interrupted delete phase leaving orphan files | Post-run snapshots, history and refs match the set you intended to keep |
remove_orphan_files | The filesystem listing under the table location, compared against metadata references | older_than = 3 days ago; dry_run = false | Age guard shorter than the longest write; scheme or authority mismatch between metadata paths and current listings; prefix_mismatch_mode set to DELETE | orphan_file_location rows from a dry_run => true pass, reviewed before any deletion |
The two procedures also return different things, which is worth knowing before you look at a result set. expire_snapshots returns a row of deletion counters, all typed long: deleted_data_files_count, deleted_position_delete_files_count, deleted_equality_delete_files_count, deleted_manifest_files_count, deleted_manifest_lists_count and deleted_statistics_files_count. Those counters tell you how many files the delete phase removed, by category — useful run evidence, but not proof of which snapshots survived; that still comes from re-reading snapshots, history and refs. remove_orphan_files returns something else entirely: a column named orphan_file_location, one row per file it judged to be an orphan.
The Spark procedures reference carries these arguments, including equal_schemes, equal_authorities, prefix_mismatch_mode and prefix_listing for orphan removal. The maintenance guide adds the two warnings that matter most: it is dangerous to remove orphan files with a retention interval shorter than the time expected for any write to complete, because in-progress files can be treated as orphaned and deleted, and Iceberg compares path strings, so a changed authority or scheme can make live files look orphaned and lead to data loss.
Note where that in-flight hazard attaches. It belongs to orphan-file removal, which reasons from a filesystem listing and therefore cannot see a file a writer is still uploading. Snapshot expiration reasons from committed metadata instead, so it doesn't hunt uncommitted files. That difference doesn't make expiration risk-free — it can strand files after an interrupted delete phase, and it can remove a snapshot a live query or job still references — but the failure mode is a different one.
The engineering limitation is structural. No inspection query can prove a filesystem holds no in-flight files, because an in-flight file is by definition absent from committed metadata. The age guard is the control that covers it.
How do you run a gated expire_snapshots safely?
Work through these steps in order, and treat step 7 as the gate — nothing before it writes to the table.
Record the table identity and current snapshot ID from the
snapshotsquery.Record every ref and its retention properties from
refs, including branchmin_snapshots_to_keepandmax_snapshot_age_in_ms.Record the snapshot count and age spread you intend to keep, and the
older_thanvalue that follows from them.Re-run the read-only metadata queries and save the output as the pre-change baseline.
Confirm nothing longer than
older_thanis in flight — no write job, compaction commit or streaming micro-batch.Confirm downstream consumers that time-travel or backfill between snapshots, and that no scheduled job names an ID you are about to remove.
Run the gated statement, after a reviewer or change ticket approves it.
Capture the procedure's printed result.
expire_snapshotsreturns the documented countersdeleted_data_files_count,deleted_position_delete_files_count,deleted_equality_delete_files_count,deleted_manifest_files_count,deleted_manifest_lists_countanddeleted_statistics_files_count(alllong); store them as run evidence. Older Iceberg or Spark versions may print a different set of columns, so confirm the shape your versions produce. By contrast,remove_orphan_filesreturnsorphan_file_locationrows, and withstream_resultsenabled its output contains a sample of up to 20,000 file paths.Re-run
snapshots,historyandrefsand diff them against the baseline to confirm the intended set survived.
-- Example configuration — validate in your target environment.
-- Replace CATALOG_NAME with your configured catalog alias, and the timestamp
-- with a value derived from the snapshot age spread recorded in step 3.
-- Approval: <change-ticket-id> Operator: <name> Reviewed-by: <name>
-- CALL CATALOG_NAME.system.expire_snapshots(
-- table => 'demo.db.orders',
-- older_than => TIMESTAMP '2026-11-01 00:00:00.000',
-- retain_last => 3,
-- stream_results => true
-- );
The statement stays commented out until the gate is signed off, and none of the read-only queries above is a dry run of it: dry_run is an argument of remove_orphan_files, not of expire_snapshots.
How do you coordinate expiration with concurrent writers, compaction and streaming readers?
Iceberg's commit protocol keeps concurrent writers from corrupting the table while expiration runs, but it doesn't track whether an operator's choice of older_than matches how long the longest write actually takes. The conservative practice — one maintenance lane, orphan cleanup in a separate later job, no write or compaction commit outliving older_than — is an operational recommendation, not a guarantee that every schedule is safe.
Two arguments protect the driver rather than the data. max_concurrent_deletes sizes the delete thread pool, and stream_results sends files to the Spark driver by RDD partition instead of collecting them all at once — the reference recommends it to prevent driver out-of-memory errors on large file lists. Treat both as capacity controls, not safety controls.
Log every run as an operational event with a job identifier and a correlation ID, so a later question about which run deleted a path can be answered from records. This site's guide to AI SQL query audit trails and correlation IDs describes that recording practice and, importantly, what such a trail can and cannot prove.
Keep compaction out of the window. Rewriting small files commits new snapshots and new files, which is the workload most likely to produce short-lived, apparently unreferenced files; if the two must run close together, see the measurement notes on lakehouse small-file compaction and streaming latency.
No article can promise a safe concurrency configuration. Catalog commit retry behavior and writer duration vary by implementation and workload, and both have to be measured in your environment.
What retention window should you choose?
There is no universal retained-hours recommendation. Iceberg's own defaults — 5 days for expire_snapshots and 3 days for remove_orphan_files — are defaults, not recommendations for your table. Choose per table, from five inputs:
Longest possible write duration. If a write, compaction or micro-batch can run for six hours, an
older_thanmeasured in minutes is unsafe.The incident-recovery window the business actually uses. How far back do incident reviews really query? A window nobody uses buys nothing.
Downstream time-travel and backfill SLAs. Ask consumers which snapshot IDs their jobs reference before you remove them.
Compaction cadence. Frequent rewrites create more snapshots, which grows metadata and raises the value of expiring it.
Metadata size and storage cost. Expiration shrinks metadata; data-file savings depend on how much is genuinely unreferenced.
Illustrative inference, not observed data: for a table whose longest write is four hours, whose consumers backfill up to three days, and which compacts nightly, an older_than of 7 days with retain_last of 10 covers both the write window and the backfill window with margin. A streaming table with minute-level micro-batches usually justifies a different pair of values than a nightly batch table, because its failure modes and its file churn both differ.
Record the chosen values as per-table properties with a named owner, so the decision is reviewed on a schedule rather than inherited by default.
Safe dry inspection checklist before you expire anything
Run these read-only checks and attach the output to the change record. Each item is verifiable from a query or a documented decision, never from intuition.
Catalog and table identity confirmed — the fully qualified name resolves through the catalog the maintenance job will use.
Current snapshot ID recorded — taken from
snapshots, with the timestamp of the reading.Every ref recorded with its retention properties — the
refsoutput saved, includingmax_reference_age_in_ms,min_snapshots_to_keepandmax_snapshot_age_in_ms.Snapshot count and oldest snapshot age recorded — so the intended post-run set is a number, not an impression.
Longest in-flight write duration known and compared with
older_than— with the pipeline or job that owns it named.Downstream time-travel and backfill consumers confirmed — a named owner has confirmed no job depends on a snapshot due for removal.
Rollback and restore path documented and tested externally — a restore test that does not depend on the snapshot being removed.
Single maintenance lane confirmed — no overlapping expiration, compaction or orphan cleanup.
Result and post-run metadata recaptured and diffed — the same three queries, before and after, compared line by line.
For the broader set of implementation gates this checklist sits inside, see the medallion implementation checklist hub.
What are the most common expiration mistakes?
Most failures come from reading one argument as broader than it is, or from letting two maintenance jobs overlap. The corrections are small and specific.
Reading
retain_lastas "keep this many snapshots anywhere." It preserves the ancestor chain of the current state; snapshots on other lineages are untouched by it.Assuming a tag protects more than the snapshot it anchors, or longer than its retention. A tag anchors one snapshot, and its
max_reference_age_in_msdecides how long the reference itself lives.Running orphan cleanup immediately after expiration with a short age guard. Wait past the longest expected write, and run
remove_orphan_fileswithdry_run => truefirst.Using orphan removal as routine disk hygiene. It compares a filesystem listing against metadata, and a scheme or authority change can make live files look orphaned.
Treating rollback as a backup. Rollback needs the snapshot to still exist; only an external copy outlives expiration.
Overlapping compaction with expiration. Rewrite commits create snapshots and files during the window you are cleaning.
Ignoring driver memory on large tables. Enable
stream_resultsand sizemax_concurrent_deletesdeliberately.
One limitation closes the list: some behaviors vary by Iceberg version, Spark version and catalog implementation, so identify the versions in use before the runbook is finalized.
Frequently asked questions about Iceberg snapshot expiration
Short answers to the questions reviewers ask most often, kept to the same scope as the sections above.
Which snapshots does expire_snapshots delete, and which are protected?
Snapshots committed before older_than are removed, except the retain_last ancestor snapshots of the current state and any snapshot still referenced by a branch or tag. The defaults are 5 days ago and 1 snapshot.
What output should I expect so I can validate the run?
expire_snapshots returns one row of long counters: deleted_data_files_count, deleted_position_delete_files_count, deleted_equality_delete_files_count, deleted_manifest_files_count, deleted_manifest_lists_count and deleted_statistics_files_count (Spark procedures). Those tell you what the delete phase removed by file category — they don't tell you which snapshots survived, so still compare the post-run refs, history and snapshots output against your baseline. Older Iceberg or Spark versions may print a different set of columns. remove_orphan_files is separate: it returns orphan_file_location rows, and with stream_results enabled the output contains a sample of up to 20,000 file paths.
Why is remove_orphan_files more hazardous than expire_snapshots?
Expiration works from snapshot metadata and preserves references that metadata still shows as reachable, while orphan cleanup compares filesystem listings against metadata and can delete files a live write has produced but not yet committed. That in-flight hazard is why its age guard must exceed the longest expected write (maintenance guide).
What do I lose after expiration, and how do tags change that?
You lose time travel to that snapshot, rollback to it, and incremental reads that use it as an endpoint. A tag anchors the snapshot and keeps it alive for the tag's retention period, but only that snapshot and only for the window the tag declares.
How should expiration be timed against concurrent writers and compaction?
Run it in one maintenance lane, avoid overlapping compaction, confirm no write lasts longer than older_than, and stream results to protect the driver. That serial schedule is a conservative recommendation rather than a proven universal guarantee, so measure commit and write durations in your own environment.