How to Run Apache Iceberg Table Maintenance: Compaction, Snapshot Expiry, Orphan Files

How to Run Apache Iceberg Table Maintenance: Compaction, Snapshot Expiry, Orphan Files

How to Run Apache Iceberg Table Maintenance: Compaction, Snapshot Expiry, Orphan Files

A streaming job that commits to an Apache Iceberg table every minute will write about 1,440 snapshots, 1,440 metadata files and tens of thousands of small Parquet files per day. Nothing breaks on day one. By week three, queries crawl, the planner chews through thousands of manifests, and the storage bill includes data you deleted weeks ago. Iceberg table maintenance is the routine work that stops this decay: compacting data files, expiring snapshots, rewriting manifests and delete files, and sweeping up orphaned objects. It matters more in late 2026 because managed services now run some of this for you, and their defaults can quietly fight with your own jobs. This guide gives you the five procedures in the order to run them, the exact Spark SQL calls for Iceberg 1.12, the table properties that control each one, and the monitoring queries that tell you when a table needs attention.

What this covers: the Iceberg metadata tree, a numbered maintenance runbook, runnable Spark and PyIceberg code, concurrency with streaming writers, small-file cost math, and how S3 Tables and AWS Glue optimizers compare to running it yourself.

Context and Background

Apache Iceberg is an open table format. A table is a tree of immutable files on object storage plus a pointer in a catalog that says which metadata file is current. Every write creates new files and a new snapshot rather than changing anything in place. That design gives you snapshot isolation, time travel and safe concurrent writers. It also means nothing is ever cleaned up unless someone runs a job to clean it up.

The current Java release is Apache Iceberg 1.12.0, published on 30 September 2026 according to the project’s GitHub releases page. That release removed Spark 3.4 support, so the Spark procedures in this guide assume Spark 3.5 or 4.x with the Iceberg runtime jar and the Iceberg SQL extensions enabled. If you are still choosing a table format, our Iceberg vs Delta vs Hudi architecture decision record covers that choice. This post assumes Iceberg is already in production.

The project documentation splits upkeep into two groups. The Iceberg maintenance guide lists expiring snapshots, removing old metadata files and deleting orphan files as “recommended”. It lists compacting data files, rewriting manifests and rewriting position delete files as “optional”. In practice, any table fed by streaming, CDC (change data capture) or frequent small batches needs all six. The optional label really means “depends on your write pattern”, and most production write patterns are bad for file layout.

Three groups of tooling for Iceberg table maintenance exist today. Self-managed jobs use the Spark stored procedures, the Java SparkActions API, or Flink’s TableMaintenance API. PyIceberg, the Python library, now supports snapshot expiration but not compaction or orphan cleanup. Managed services include Amazon S3 Tables, which runs compaction, snapshot management and unreferenced-file removal by default, and AWS Glue Data Catalog table optimizers, which do the same for Iceberg tables in general-purpose S3 buckets. Other vendors and catalogs offer similar features, but this guide verifies only the AWS ones in detail.

The thesis of this guide is simple. Maintenance is not five separate chores. It is one pipeline with an order that matters, a retention window that has to match your writers, and a single owner. Most production incidents with Iceberg upkeep come from two systems both thinking they own a table.

Iceberg Table Maintenance Step by Step: The Runbook

Iceberg table maintenance means running five jobs in order: compact small data files with rewrite_data_files, compact delete files with rewrite_position_delete_files, regroup metadata with rewrite_manifests, drop old snapshots with expire_snapshots, and delete unreferenced objects with remove_orphan_files. Compaction runs hourly to daily, expiry daily, and orphan cleanup weekly.

Iceberg table maintenance metadata tree showing catalog pointer, metadata files, manifest lists, manifests and data files, with the maintenance procedure that acts on each layer

Figure 1: The Iceberg metadata tree and which maintenance procedure cleans each layer.

Figure 1 shows the layers from top to bottom. The catalog points at the current metadata.json. That file lists every snapshot still kept. Each snapshot points at a manifest list, each manifest list points at manifest files, and each manifest tracks data files and delete files. Each maintenance procedure targets one layer. Compaction works at the bottom, manifest rewrites in the middle, snapshot expiry near the top, and orphan removal on whatever no layer references any more.

Why every layer grows on its own

Each commit adds at least one new metadata JSON file, one manifest list and one or more manifests. With fast appends, which PyIceberg uses by default, each commit adds a new manifest instead of merging into existing ones. The data layer grows with every writer task, because each task writes at least one file per partition it touches. A Spark job with 200 shuffle partitions writing into 24 hourly partitions can produce thousands of files in one commit.

The layers also decay at different speeds. Small data files hurt scan time right away. Extra manifests mostly hurt query planning, and the cost grows with table age. Old snapshots cost storage because they keep replaced data files alive. Orphans cost storage too, and nothing ever references them again. That is why one schedule for everything is wrong. Use one schedule per layer, with a fixed order inside each run.

The order matters

The order of operations follows from what each step creates and frees. Compaction writes new large files and a new snapshot. The small files it replaced are still referenced by earlier snapshots, so compaction alone saves no storage. In fact it temporarily adds storage. Rewriting manifests after compaction regroups the new file entries in one pass instead of two. Expiring snapshots after that drops the old snapshots, along with the old manifests and replaced small files they alone referenced. Orphan cleanup comes last because it is the only step that deletes files no metadata knows about, and it should see the table after the other steps have settled.

Ordered Iceberg maintenance pipeline from compaction through delete file rewrite, manifest rewrite, snapshot expiration and orphan file removal

Figure 2: The recommended run order for one maintenance cycle and the cadence of each step.

Figure 2 is the runbook in picture form. The first three steps add files and snapshots. The last two remove them. If you reverse the order and expire before compacting, the snapshots made by compaction will survive until the next expiry run. Storage stays high for one extra cycle.

Step 1: Compact data files with rewrite_data_files

Iceberg compaction is the step that fixes query speed. The Spark procedure is rewrite_data_files. With no options it uses the binpack strategy. It targets the table’s write.target-file-size-bytes, which defaults to 536,870,912 bytes (512 MB).

-- Bin-pack yesterday's partitions only; commit in batches so a failure keeps progress
CALL lake.system.rewrite_data_files(
  table   => 'telemetry.sensor_readings',
  where   => 'event_date >= current_date() - INTERVAL 1 DAY',
  options => map(
    'target-file-size-bytes',              '536870912',
    'min-input-files',                     '5',
    'partial-progress.enabled',            'true',
    'partial-progress.max-commits',        '10',
    'max-concurrent-file-group-rewrites',  '8',
    'remove-dangling-deletes',             'true'
  )
);

The selection rules matter more than the target size. A file is a candidate if it is under min-file-size-bytes (default 75% of target) or over max-file-size-bytes (default 180% of target). A candidate is also any data file whose deletes meet delete-file-threshold or delete-ratio-threshold, which defaults to 0.3. Candidates are grouped by partition, then split into file groups of at most max-file-group-size-bytes (default 100 GB). A group is rewritten only if it has at least min-input-files files (default 5) or meets the size or delete rules. That is why a partition with three tiny files may not be touched. Lower min-input-files to 2 if that matters to you.

The where argument is your main cost lever. It limits the rewrite to files that might match the predicate, so a daily job only touches recent partitions. Without it, every run re-plans the whole table. partial-progress.enabled commits finished file groups as it goes. A job that fails at 80% then keeps its work instead of losing it. It also makes conflicts with concurrent writers less costly, as the concurrency section explains.

For read-heavy tables, use the sort strategy. You can sort by the table’s sort order, by explicit columns, or by a space-filling curve. The current docs list zorder(c1,c2) and a hilbert(c1,c2) option, and note that the two cannot be combined in one sort_order. Sorting costs more compute than bin-packing. It pays off when queries filter on the sort columns, because min/max statistics in each file become tight enough to skip most files.

CALL lake.system.rewrite_data_files(
  table      => 'telemetry.sensor_readings',
  strategy   => 'sort',
  sort_order => 'zorder(site_id, sensor_id)',
  where      => 'event_date = current_date() - INTERVAL 1 DAY'
);

The output tells you what happened: rewritten_data_files_count, added_data_files_count, rewritten_bytes_count, failed_data_files_count and removed_delete_files_count. Log all five. A run that rewrites the same bytes every night with no drop in file count is a sign of a bad where clause or a writer that keeps re-fragmenting the table.

Step 2: Compact delete files with rewrite_position_delete_files

Tables written in merge-on-read mode, which most CDC and upsert pipelines use, build up position delete files. In format v3 they also build up deletion vectors. Each delete file is small, and every reader must open it and apply it. rewrite_position_delete_files merges small position delete files toward write.delete.target-file-size-bytes (64 MB by default). It also drops delete records that point at data files that are no longer live.

CALL lake.system.rewrite_position_delete_files(
  table   => 'erp.work_orders',
  options => map('partial-progress.enabled', 'true')
);

Two caveats apply. First, data-file compaction already applies deletes to the files it rewrites, so on many tables step 1 does most of this work. Second, the Java removeDanglingDeleteFiles action has no Spark SQL procedure. In SQL you get the same effect through remove-dangling-deletes in step 1. Iceberg 1.12 also made rewrite_position_delete_files fail loudly on position deletes that carry row data. Treat that error as a signal to review old writers, not something to work around.

Step 3: Rewrite manifests

Manifests are the index of the table. Iceberg merges manifests automatically on commit when commit.manifest-merge.enabled is true (the default). Merging starts once at least commit.manifest.min-count-to-merge manifests exist (default 100), and merged manifests target commit.manifest.target-size-bytes (8 MB). Automatic merging keeps entries in write order. That works well when write order matches the query filter, such as hourly data queried by time. It works badly when a late-arriving CDC feed spreads each commit across hundreds of old partitions.

Rewriting manifests in Iceberg regroups entries by partition so the planner can skip whole manifests:

CALL lake.system.rewrite_manifests(
  table   => 'erp.work_orders',
  sort_by => array('plant_id')
);

sort_by clusters manifests by the partition transforms you name. Pick the one most queries filter on. use_caching defaults to false. Enabling it speeds the job but raises executor memory. The docs warn that the procedure invalidates cached Spark plans for the table, so run it outside peak query hours.

Step 4: Expire snapshots

Iceberg expire snapshots is the step that actually frees storage. The procedure removes snapshots older than older_than (default: five days ago) while keeping at least retain_last ancestors (default 1). It then deletes the data, delete, manifest, manifest-list and statistics files that only those snapshots referenced. It never deletes a file that a surviving snapshot still needs.

CALL lake.system.expire_snapshots(
  table                  => 'telemetry.sensor_readings',
  older_than             => TIMESTAMP '2026-11-26 00:00:00',
  retain_last            => 50,
  max_concurrent_deletes => 16,
  stream_results         => true,
  clean_expired_metadata => true
);

If you leave out both older_than and retain_last, the procedure falls back to table properties. Those are history.expire.max-snapshot-age-ms (default 432,000,000 ms, which is 5 days) and history.expire.min-snapshots-to-keep (default 1). Setting them as properties is useful because every engine can read them. However, as we will see, S3 Tables treats those same properties as a reason to stop expiring at all.

Branches and tags change the picture. Snapshots referenced by a branch or tag are not removed. Non-main references never expire by default, unless you set history.expire.max-ref-age-ms. A forgotten audit branch will therefore pin every file it references forever. stream_results => true sends file lists to the driver by partition instead of all at once. The docs recommend it to avoid driver out-of-memory errors on large tables.

Step 5: Remove orphan files

Iceberg remove orphan files is the only step that deletes objects no metadata references. These are leftovers from failed tasks, killed jobs and commits that lost a conflict. They also include old metadata.json files that fell off the metadata log. The procedure lists the table location and compares it with every file reachable from metadata. It deletes the difference if the objects are older than older_than, which defaults to three days ago.

-- Always dry-run first on a new table or after a storage migration
CALL lake.system.remove_orphan_files(
  table   => 'telemetry.sensor_readings',
  dry_run => true
);

CALL lake.system.remove_orphan_files(
  table          => 'telemetry.sensor_readings',
  older_than     => TIMESTAMP '2026-11-26 00:00:00',
  stream_results => true,
  prefix_listing => true
);

The three-day default is a safety margin, not a tuning knob to shrink. The Iceberg docs say plainly that a retention shorter than the longest write can corrupt the table, because files from an in-progress commit look orphaned. prefix_mismatch_mode defaults to ERROR. If a file matches a metadata entry except for its scheme or authority (for example s3a:// against s3://), the job stops rather than guessing. equal_schemes defaults to treating s3a and s3n as s3. Listing a large prefix is slow and costs requests, so weekly is enough for most tables.

Walk-through: Scheduling, Concurrency, Code and Cost

This section turns the runbook into a job you can schedule, then looks at the two things that make Iceberg table maintenance hard in production: concurrent writers and the cost of small files.

A runnable PySpark maintenance job

The script below runs the five steps in order for a list of tables. It logs each procedure’s output and skips orphan cleanup except on the configured weekday. It assumes a Spark session already set up with the Iceberg runtime, the IcebergSparkSessionExtensions SQL extensions and a catalog named lake.

# iceberg_maintenance.py  - run with spark-submit; Iceberg 1.12 runtime on Spark 3.5/4.x
import datetime as dt
import json
from pyspark.sql import SparkSession

CATALOG = "lake"
TABLES = {
    # table: (compaction partition filter, snapshots to retain, retention days)
    "telemetry.sensor_readings": ("event_date >= current_date() - INTERVAL 2 DAYS", 50, 3),
    "erp.work_orders":           (None, 20, 7),
}
ORPHAN_WEEKDAY = 6          # Sunday
ORPHAN_MIN_AGE_DAYS = 3     # must exceed your longest write or commit retry window

spark = SparkSession.builder.appName("iceberg-maintenance").getOrCreate()

def call(sql: str):
    rows = spark.sql(sql).collect()
    print(json.dumps({"sql": " ".join(sql.split()), "result": [r.asDict() for r in rows][:5]},
                     default=str))
    return rows

def ts(days_ago: int) -> str:
    t = dt.datetime.utcnow() - dt.timedelta(days=days_ago)
    return t.strftime("%Y-%m-%d %H:%M:%S")

for table, (where, retain_last, keep_days) in TABLES.items():
    fq = f"{table}"
    where_arg = f", where => '{where}'" if where else ""

    # 1. data file compaction
    call(f"""CALL {CATALOG}.system.rewrite_data_files(table => '{fq}'{where_arg},
             options => map('partial-progress.enabled','true',
                            'partial-progress.max-commits','10',
                            'remove-dangling-deletes','true'))""")

    # 2. position delete compaction (merge-on-read tables only)
    props = {r.key: r.value for r in spark.sql(f"SHOW TBLPROPERTIES {CATALOG}.{fq}").collect()}
    if "merge-on-read" in (props.get("write.delete.mode", ""), props.get("write.merge.mode", "")):
        call(f"CALL {CATALOG}.system.rewrite_position_delete_files(table => '{fq}')")

    # 3. manifest rewrite
    call(f"CALL {CATALOG}.system.rewrite_manifests(table => '{fq}')")

    # 4. snapshot expiry
    call(f"""CALL {CATALOG}.system.expire_snapshots(table => '{fq}',
             older_than => TIMESTAMP '{ts(keep_days)}', retain_last => {retain_last},
             max_concurrent_deletes => 16, stream_results => true)""")

    # 5. orphan cleanup, weekly
    if dt.datetime.utcnow().weekday() == ORPHAN_WEEKDAY:
        call(f"""CALL {CATALOG}.system.remove_orphan_files(table => '{fq}',
                 older_than => TIMESTAMP '{ts(ORPHAN_MIN_AGE_DAYS)}', stream_results => true)""")

spark.stop()

Run one table per job if your tables are large, because Iceberg table maintenance on one huge table should not starve the rest. A failure on table A should not skip expiry on table B. In Airflow, Dagster or Step Functions, a simple pattern works well: one task per table per step, with the steps chained and the tables run in parallel up to your cluster limits.

PyIceberg: what you can and cannot do from Python

PyIceberg 0.12.0 (released on PyPI on 1 September 2026) exposes snapshot expiration through table.maintenance. The API is small:

from datetime import datetime, timedelta, timezone
from pyiceberg.catalog import load_catalog

catalog = load_catalog("lake")
tbl = catalog.load_table("telemetry.sensor_readings")

# Inspect before acting: metadata tables come back as Arrow tables
snaps = tbl.inspect.snapshots()
files = tbl.inspect.files()
print(snaps.num_rows, "snapshots;", files.num_rows, "live files")

# Expire unprotected snapshots older than 3 days
tbl.maintenance.expire_snapshots().older_than(
    datetime.now(timezone.utc) - timedelta(days=3)
).commit()

Three limits stand out. First, there is no retain_last. You choose snapshots by age or by ID, and the heads of branches and tags are always protected. Second, in the current source, the expiry commit removes snapshot entries from metadata, but we found no step that deletes the now-unreferenced data files. You need an orphan sweep afterwards, run either by Spark or by your managed service. Third, compaction is still described in the PyIceberg docs as “planned”. PyIceberg also has no orphan-file procedure. For Python-only stacks, PyIceberg is a good monitoring and expiry tool, but it is not a full maintenance engine yet.

Streaming writers and optimistic concurrency

Iceberg uses optimistic concurrency. Each writer reads the current metadata, writes its new files, and then tries to swap the catalog pointer. If someone else committed first, the writer re-checks for conflicts and retries, up to commit.retry.num-retries times (default 4). Compaction is just another writer. A rewrite of partition P conflicts if a concurrent commit deleted or updated rows in the files being replaced. Pure appends to P usually do not conflict, because the new files are not among the ones being rewritten.

Sequence of a streaming writer and an Iceberg compaction job committing to the catalog with optimistic concurrency, conflict detection and retry

Figure 3: How a streaming commit and a compaction commit race for the catalog pointer, and why partial progress limits the damage.

Figure 3 walks through the common failure. A long compaction plans against snapshot S1. Meanwhile a CDC job commits S2 and S3, with deletes against two files that compaction is rewriting. When compaction tries to commit, validation fails for those groups. Without partial progress, the whole multi-hour rewrite is thrown away. With partial-progress.enabled, groups that did not overlap have already committed, and only the conflicting groups fail. They are reported in failed_data_files_count.

Practical rules follow from this. Compact partitions that are no longer receiving writes. For time-partitioned streams that usually means “yesterday and older”, which the where clause handles. For CDC tables where any partition can change, keep file groups small and enable partial progress. AWS gives the same advice for S3 Tables: compaction jobs retry on conflict, and your own pipelines should have retry logic too. Avoid running two maintenance systems on one table. Two compactors will conflict with each other far more often than with your writers.

Flink users have another option. The Iceberg Flink TableMaintenance API can run compaction, snapshot expiry and orphan deletion as part of a streaming job. It is triggered by commit count, data file count or time. It uses a lock (JDBC, ZooKeeper or a coordinator lock) so only one maintenance task runs per table. That keeps upkeep next to the writer, which is often the cleanest design for a single-writer stream.

The small-file cost, worked through

The numbers below are illustrative. They show the shape of the problem, not a benchmark. Assume a stream commits every 60 seconds, and each commit writes 8 files of about 4 MB into the current day’s partition.

Quantity per day Before compaction After 512 MB bin-pack
Commits / snapshots 1,440 1,440 + compaction commits
Data files 1,440 × 8 = 11,520 11,520 × 4 MB ÷ 512 MB = 90
Data volume 11,520 × 4 MB = 45 GB 45 GB
Object reads to scan the day (illustrative) 11,520 files × 2 (footer + data) = 23,040 90 files × 5 (footer + 4 row groups) = 450
Request latency at 20 ms, 64 parallel readers 23,040 × 0.02 s ÷ 64 ≈ 7.2 s 450 × 0.02 s ÷ 64 ≈ 0.14 s

The bytes scanned are the same 45 GB either way. The difference is per-object overhead: about 51 times more requests and seconds of pure latency added to every full-day query. Request charges on object storage scale with that count as well. Over a week, the table gains 80,640 small files if nobody compacts it.

Compaction does not free storage by itself, though. The 45 GB of small files rewritten today are still referenced by the earlier snapshots. With a 5-day snapshot retention, a table that rewrites 45 GB a day keeps roughly 5 × 45 = 225 GB of replaced data alive at steady state. That is the price of time travel. If you only need two days of time travel, shortening retention to two days cuts that overhead to about 90 GB. This trade-off between time travel and storage is the single most useful setting to agree with the people who use the table.

Monitor with metadata tables

Metadata tables tell you when a table needs Iceberg table maintenance, so you can schedule by need instead of by clock. These Spark SQL queries cover the main signals:

-- Small-file ratio per partition (data files only; content = 0)
SELECT partition,
       count(*)                                         AS files,
       round(avg(file_size_in_bytes) / 1048576, 1)       AS avg_mb,
       sum(CASE WHEN file_size_in_bytes < 64*1048576 THEN 1 ELSE 0 END) AS under_64mb
FROM lake.telemetry.sensor_readings.files
WHERE content = 0
GROUP BY partition
ORDER BY under_64mb DESC
LIMIT 20;

-- Snapshot pile-up and age
SELECT count(*) AS snapshots, min(committed_at) AS oldest, max(committed_at) AS newest
FROM lake.telemetry.sensor_readings.snapshots;

-- Manifest count and size: many small manifests means slow planning
SELECT count(*) AS manifests, round(avg(length)/1024, 1) AS avg_kb,
       sum(added_data_files_count + existing_data_files_count) AS tracked_files
FROM lake.telemetry.sensor_readings.manifests;

-- Delete-file pressure per partition (merge-on-read tables)
SELECT partition, file_count, position_delete_file_count, equality_delete_file_count
FROM lake.erp.work_orders.partitions
ORDER BY position_delete_file_count + equality_delete_file_count DESC
LIMIT 20;

PyIceberg’s tbl.inspect exposes the same tables (snapshots(), files(), manifests(), partitions(), refs()) as Arrow tables. A lightweight Python job can therefore decide which tables to hand to the Spark maintenance job. Useful triggers are an average file size below a quarter of target in any recent partition, more than a few hundred manifests, delete files above about 10% of data files, or an oldest snapshot well past your retention.

Table properties that shape upkeep

Several table properties make Iceberg table maintenance easier before it even runs:

Property Default What to do with it
write.target-file-size-bytes 512 MB Lower to 128-256 MB for tables queried by small engines or with many tiny partitions
write.distribution-mode engine-specific hash reduces files per partition at write time, so there is less to compact
write.delete.target-file-size-bytes 64 MB Target for delete-file rewrites
commit.manifest.min-count-to-merge 100 Lower for high-commit streams if planning slows
history.expire.max-snapshot-age-ms 432,000,000 (5 days) Default for expire_snapshots; do not set on S3 Tables
history.expire.min-snapshots-to-keep 1 As above
history.expire.max-ref-age-ms forever Set it so stale branches and tags age out
write.metadata.delete-after-commit.enabled false Set true on streaming tables to cap metadata.json growth
write.metadata.previous-versions-max 100 Number of old metadata files kept when the above is true

The metadata-file pair is easy to miss. With deletion off, every commit leaves its old metadata.json behind. The Iceberg docs give an example: with deletion disabled and 10 tracked versions, 100 commits leave 90 untracked files that only orphan cleanup can remove. For a stream committing once a minute, enable write.metadata.delete-after-commit.enabled from the first day.

Managed Options: S3 Tables Maintenance and Glue Optimizers

S3 Tables maintenance and Glue table optimizers replace most of the runbook with configuration. Both are real options in late 2026, and both have sharp edges that the “fully managed” label hides.

Amazon S3 Tables

In S3 table buckets, compaction and snapshot management are on by default for every table. Unreferenced file removal is on by default for every table bucket. The S3 Tables maintenance documentation gives these defaults: compaction targets 512 MB files, configurable from 64 to 512 MB. The auto strategy picks sort if the table has a sort order and binpack otherwise, and z-order is also available. Snapshot management keeps at least 1 snapshot and expires snapshots older than 120 hours. Unreferenced file removal marks objects as noncurrent after 3 days without a reference and deletes them permanently 10 days later.

# Raise snapshot retention for a table that needs two weeks of time travel
aws s3tables put-table-maintenance-configuration \
  --table-bucket-arn arn:aws:s3tables:us-east-1:111122223333:bucket/lake \
  --namespace telemetry --name sensor_readings \
  --type icebergSnapshotManagement \
  --value '{"status":"enabled","settings":{"icebergSnapshotManagement":{"minSnapshotsToKeep":20,"maxSnapshotAgeHours":336}}}'

# Check whether the last maintenance jobs succeeded
aws s3tables get-table-maintenance-job-status \
  --table-bucket-arn arn:aws:s3tables:us-east-1:111122223333:bucket/lake \
  --namespace telemetry --name sensor_readings

Three behaviours deserve attention. First, snapshot management stops working for the whole table if the table has user-defined tags or branches. It also stops if history.expire.max-snapshot-age-ms or history.expire.min-snapshots-to-keep is set as a table property, whatever the value. AWS documents that in these cases snapshots are not expired at all, and storage grows until you fix it. Second, deletes of noncurrent objects are permanent, and recovering them means contacting AWS Support. Third, AWS warns that streaming pipelines which write objects long before committing them must set unreferencedDays longer than that delay. Otherwise S3 marks the objects noncurrent before the commit lands. That is the same corruption risk as a too-short remove_orphan_files window, now as a bucket-wide setting.

On cost, AWS’s S3 pricing page bills compaction per 1,000 objects processed and per GB processed, with a higher per-GB rate for sort and z-order than for binpack. Check the current rates for your region on that page. We do not quote them here because they vary by region. You can disable compaction per table if you would rather run it yourself.

At re:Invent 2026, ITPro’s live coverage of the 2 December storage session reported the launch of “S3 System Tables” as an extension of S3 Tables. At the time of writing we could not find an AWS What’s New post or documentation page for it. Treat it as reported, and check the official docs before relying on it.

AWS Glue Data Catalog table optimizers

For Iceberg tables in ordinary S3 buckets registered in the Glue Data Catalog, Glue offers three optimizers. Compaction supports binpack, sort and z-order, and AWS says it supports Iceberg v3 tables. Snapshot retention defaults to keeping 1 snapshot for 5 days, with cleanExpiredFiles true so expired files are deleted. Orphan file deletion uses a configurable orphanFileRetentionPeriodInDays. One documented detail surprises people: the orphan optimizer only deletes files created after the optimizer itself was created. Enabling it on a three-year-old table will not clean the backlog. Run one manual remove_orphan_files first.

Choosing who owns Iceberg table maintenance

Decision flow for choosing self-managed Spark maintenance, S3 Tables automatic maintenance or AWS Glue table optimizers for Iceberg tables

Figure 4: A decision flow for picking one owner of maintenance per table.

Figure 4 sums up the decision. If the table already lives in an S3 table bucket, use S3 Tables maintenance and remove any history.expire.* properties. If you need custom sort orders per partition, very long retention, or branches and tags, you can still keep S3 Tables but disable the conflicting jobs. If the table lives in a general-purpose bucket on AWS, Glue optimizers are the low-effort path. If you run on several clouds or need tight control over timing, run the Spark job above. Whichever you pick, one system owns each table. For catalog-level context, see our comparison of Iceberg catalogs Polaris, Nessie and Unity.

Concern Self-managed Spark S3 Tables Glue optimizers
Compaction strategies binpack, sort, zorder, hilbert auto, binpack, sort, z-order binpack, sort, z-order
Snapshot expiry default 5 days, keep 1 120 hours, keep 1 5 days, keep 1
Orphan or unreferenced cleanup manual, default 3-day age 3 days + 10 days noncurrent only files newer than optimizer
Respects history.expire.* yes no, and they block expiry not documented here
Branches and tags supported block snapshot management not verified
Billing your compute per object and per GB processed see Glue pricing

Trade-offs, Gotchas, and What Goes Wrong

Most Iceberg table maintenance incidents fall into a handful of patterns.

A too-short orphan window deletes live data. This is the most serious failure. If a Spark job writes files for four hours and then commits, a 1-day window is fine. A 1-hour window deletes files that are about to become part of the table. The commit then succeeds and points at objects that no longer exist. Set the window longer than your slowest write plus all its retries. Never set it per run from a script parameter that someone can shorten.

Path mismatches cause data loss. Orphan detection compares path strings. If old metadata says s3a://bucket/... and the listing returns s3://bucket/..., every file looks orphaned. The default prefix_mismatch_mode = ERROR protects you. Do not switch it to DELETE to make an error go away. The same risk applies after an HDFS authority change or a bucket migration.

Shared locations break assumptions. Glue’s documentation warns that the table location must not contain files from other tables. S3 Tables notes that references from outside the table do not protect an object. Tables created with Iceberg’s snapshot procedure share data files with their source. Running deleteReachableFiles or aggressive cleanup on either side can corrupt the other.

Two owners fight. S3 Tables compaction plus your own nightly rewrite_data_files means double compute and frequent commit conflicts. In the worse case, compaction rewrites the same data twice. Pick one owner.

Compaction can raise storage for days. As the cost section showed, rewritten bytes stay alive for the retention window. Teams that switch on sort compaction across a large table often see a storage jump before the drop.

Time travel ends when you expire. Audits, ML training reproducibility and incident rollback all depend on old snapshots. Tag the snapshots you must keep. On S3 Tables, tags disable automatic snapshot management, so there you would export or copy instead.

Driver memory and listing cost. Expiry and orphan jobs on tables with millions of files can run the Spark driver out of memory. Use stream_results, and use prefix_listing where your FileIO supports it.

Practical Recommendations

Good Iceberg table maintenance starts with one owner per table. Write that decision down next to the table, in the catalog description or a data contract. Then set retention from business need, not habit. Ask the people who query the table how far back they really time-travel, and set snapshot retention to that plus a day. Set the orphan window from your slowest writer, and never go below three days without a documented reason.

Make the table easier to maintain at write time. Use hash distribution, sensible partitioning and a target file size that suits your query engines. Enable metadata-file deletion on streaming tables. Every file you avoid writing is one you never need to compact. Our Iceberg v3 spec features guide explains how deletion vectors change the delete-file side of this work.

Schedule Iceberg table maintenance by signal, not just by clock. A daily compaction of yesterday’s partitions plus a daily expiry covers most append tables. Add the metadata-table checks so that a sudden spike in small files or delete files triggers an extra run. Finally, alert on maintenance failures as you would on ingestion failures. A silently failing expiry job costs nothing for a month and then a great deal.

Checklist:

  • [ ] One maintenance owner per table: Spark job, Flink TableMaintenance, S3 Tables, or Glue.
  • [ ] Order per cycle: compact, delete-file rewrite, manifests, expire, orphans.
  • [ ] where filter on compaction; partial-progress.enabled on tables with concurrent writers.
  • [ ] Snapshot retention agreed with consumers; history.expire.max-ref-age-ms set for branches.
  • [ ] Orphan window at least 3 days and longer than the slowest write; always dry-run first.
  • [ ] write.metadata.delete-after-commit.enabled=true on streaming tables.
  • [ ] No history.expire.* properties and no tags on S3 Tables that rely on automatic expiry.
  • [ ] Metadata-table monitoring and alerts on failed maintenance jobs.

Frequently Asked Questions

How often should I run Iceberg compaction?

Match it to how fast small files appear. A streaming or CDC table usually needs compaction of recent partitions every hour to every day. A table loaded once a day by a well-tuned batch job may need it weekly or never. Watch the files metadata table. When average file size in recent partitions drops below about a quarter of write.target-file-size-bytes, or the file count per partition reaches the hundreds, compact. Use the where argument so each run only touches partitions that changed, which keeps cost proportional to new data.

Does expire_snapshots delete data files?

Yes, in Spark and the Java API. expire_snapshots removes the expired snapshots from metadata, then deletes data files, delete files, manifests and manifest lists that only those snapshots referenced. It never deletes a file that a remaining snapshot, branch or tag still needs. The defaults are five days and at least one retained snapshot. PyIceberg’s table.maintenance.expire_snapshots() is different. In the current source it updates metadata only, so you need a separate orphan cleanup to reclaim the storage.

What is the safe retention period for remove_orphan_files?

The default is three days, and the Iceberg documentation warns against going shorter than the longest time any write takes to commit. Files written by an in-progress job look exactly like orphans until the commit lands. If you delete them, the table ends up pointing at missing objects. Measure your slowest writer, including retries and backfills, and add a margin. S3 Tables applies the same logic through unreferencedDays, which defaults to three days at the table-bucket level.

Do I still need maintenance with Amazon S3 Tables?

You need less manual work but more configuration review. S3 Tables runs compaction and snapshot management on each table by default, and unreferenced-file removal for each bucket. However, snapshot management stops entirely if the table has user tags or branches, or history.expire.* properties. Compaction is billed per object and per GB processed. You should also confirm job status regularly with get-table-maintenance-job-status, and make sure no other system is compacting the same table.

What is the difference between rewrite_data_files and rewrite_manifests?

rewrite_data_files rewrites the actual Parquet, ORC or Avro data. It merges small files into larger ones, applies pending deletes, and can sort or cluster rows. That improves scan speed. rewrite_manifests rewrites only the metadata manifests that list those files. It regroups manifest entries by partition so the query planner can skip whole manifests. That improves planning speed. Data compaction is the higher-value job on most tables. Manifest rewrites matter most when the write pattern spreads each commit across many partitions.

Can PyIceberg compact Iceberg tables?

Not yet. In PyIceberg 0.12.0, the maintenance API offers snapshot expiration by age or by snapshot ID, and the documentation still describes compaction as planned. There is no orphan-file procedure either. Use PyIceberg to inspect metadata tables and to expire snapshots in Python-only pipelines. For compaction, use Spark’s rewrite_data_files, Flink’s TableMaintenance, or a managed option such as S3 Tables or Glue optimizers. Check the PyIceberg release notes before relying on this, because the library moves quickly.

Further Reading

By Riju — about

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *