View a markdown version of this page

Self-managed maintenance - AWS Prescriptive Guidance

Self-managed maintenance

Iceberg ships a set of system procedures you can call from Apache Spark to perform table maintenance. When you host self-managed Iceberg tables on Amazon S3, running these procedures on a schedule (from Amazon EMR, AWS Glue, or any Spark environment configured against your catalog) is the most flexible option — you control every parameter, the compute size, and the cadence. Amazon Athena exposes equivalent SQL commands (OPTIMIZE, VACUUM) for the most common operations.

This section describes the three procedures you typically use: rewrite_data_files (compaction), expire_snapshots, and remove_orphan_files. The examples assume that your Spark session has a catalog named iceberg_catalog — see Catalog configuration for Iceberg on Amazon EMR Spark or Catalog configuration for Iceberg on AWS Glue Spark for how to set that up.

Compaction — rewrite_data_files

rewrite_data_files merges small data files into fewer larger ones and, on merge-on-read tables, applies delete files into the corresponding data files. It's the workhorse for keeping read performance high after many small writes (streaming ingestion, high-frequency updates, and so on).

What compaction does

Iceberg compaction can perform four tasks:

  • Bin packing — combining small files into larger files that are generally over 100 MB in size. This is the default strategy.

  • Merging delete files with data files — delete files are generated by updates or deletes that use the merge-on-read approach. Compacting them back into the base data files removes the reader-side (and writer-side) cost of resolving deletes at query time. Applying deletes does not remove the delete files themselves from table metadata; set remove-dangling-deletes => true or run rewrite_position_delete_files afterwards.

  • (Re)sorting the data according to query patterns — data can be written without any sort order, or with a sort order that's suitable for writes and updates but not for reads.

  • Clustering the data with space-filling curves for distinct query patterns, particularly Z-order sorting.

The sort strategy extends bin packing with an additional step that sorts the rewritten data. Z-order is not a separate strategy in the Spark procedure: use strategy => 'sort' with a sort_order such as zorder(customer_id, order_ts).

How file groups work

When you run rewrite_data_files, Iceberg groups candidate files into file groups. A file group is an Iceberg abstraction for a collection of files that a single Spark job will process — the Spark application creates one job per file group.

Diagram showing how the Iceberg rewrite_data_files procedure plans file groups per partition: a 178 GB partition is split into two file groups (100 GB and 78 GB), an 83 GB partition becomes one 83 GB file group, a 40 MB partition is skipped with "No file group", and a 70 MB partition made up of many small files is consolidated into a single 70 MB file group.

In the example above the table has four partitions of different sizes and file counts:

  • month=01 exceeds the 100 GB maximum file-group size, so it's split into two file groups.

  • month=02 fits under 100 GB and produces one file group.

  • month=03 doesn't meet the minimum-input-files threshold (5) and is skipped.

  • month=04 holds only small files but has more than 5 of them, so all of them are compacted into a single file group.

The property that controls per-file-group size (max-file-group-size-bytes, default 100 GB — see the options table below) is especially important for tables without partitions or with partitions that span hundreds of gigabytes: it lets Iceberg break the work into pieces the cluster can make progress on without exhausting memory. Because each file group is sorted independently, if you want a partition-level sort, set max-file-group-size-bytes to the partition size.

Invocation and parameters

Basic invocation (bin-packing on the whole table with defaults):

CALL iceberg_catalog.system.rewrite_data_files( table => 'sales.orders' )

Common parameters:

Parameter

Purpose

Typical values

strategy

Rewrite strategy. binpack merges files based on size; sort also re-sorts data by a sort order; z-order applies a Z-order sort useful for multi-dimensional locality

binpack (default), sort. For Z-order use sort with sort_order => 'zorder(col_a, col_b)'

sort_order

Sort or Z-order key expression (required for sort / z-order strategies)

'category ASC NULLS LAST, order_ts DESC'

where

SQL predicate that limits compaction to specific partitions

'order_ts >= DATE ''2026-01-01'''

options

Map of tuning options (see below)

see next table

Key entries under options (Spark map syntax):

Option

Purpose

Default

target-file-size-bytes

Target size for compacted output files. Falls back to table property write.target-file-size-bytes if not set

512 MB

min-file-size-bytes

Files smaller than this are candidates for compaction. Falls back to 75% of target if not set

75% of target

max-file-size-bytes

Files larger than this are candidates for compaction. Falls back to 180% of target if not set

180% of target

min-input-files

Skip a partition unless it has at least this many candidate files

5

delete-file-threshold

On merge-on-read tables, rewrite a data file if it has at least this many delete files pointing at it

2^31-1 (never) — set explicitly to compact deletes

max-file-group-size-bytes

Data limit per Spark job in the rewrite

100 GB

max-concurrent-file-group-rewrites

Number of file groups (Spark jobs) processed in parallel

5

partial-progress.enabled

Commit each file group as it finishes instead of one big commit at the end

false

rewrite-job-order

Order in which file groups are processed

none

remove-dangling-deletes

Remove delete files that no longer apply to any live data file; adds one extra commit

false

Examples

Bin-packing compaction that also applies delete files, targeting 512 MB files:

CALL iceberg_catalog.system.rewrite_data_files( table => 'sales.orders', options => map( 'target-file-size-bytes', '536870912', 'delete-file-threshold', '2', 'max-concurrent-file-group-rewrites', '10', 'partial-progress.enabled', 'true' ) )

Sort compaction on a specific partition:

CALL iceberg_catalog.system.rewrite_data_files( table => 'sales.orders', strategy => 'sort', sort_order => 'customer_id ASC NULLS LAST, order_ts DESC', where => 'order_ts >= DATE ''2026-06-01''' )

Sizing the Spark cluster on Amazon EMR or AWS Glue

The file-group-to-Spark-job mapping is what you plan cluster resources against. To process file groups sequentially at the default 100 GB per file group, a reasonable starting point is:

  • spark.dynamicAllocation.enabled = false

  • spark.executor.memory = 20 GB

  • spark.executor.instances = 5

To speed compaction up, scale horizontally by increasing the number of file groups processed in parallel — either manually or with Spark's dynamic allocation.

Manual scaling — for example, by a factor of 4:

  • max-concurrent-file-group-rewrites = 4

  • spark.executor.instances = 5 × 4 = 20

  • spark.dynamicAllocation.enabled = false

Dynamic scaling:

  • spark.dynamicAllocation.enabled = true

  • max-concurrent-file-group-rewrites = N — align with spark.dynamicAllocation.maxExecutors. With spark.executor.instances = 5, N = 20 is a reasonable start.

These are starting points; monitor your Spark jobs and adjust until they fit your workload. On Amazon EMR, dynamic allocation is enabled by default and spark.dynamicAllocation.maxExecutors has no upper bound unless you set one; set it explicitly and align max-concurrent-file-group-rewrites with it. On AWS Glue, size with the job's worker count and Auto Scaling instead.

Running compaction with Amazon Athena

Amazon Athena exposes Iceberg's compaction as the OPTIMIZE statement — a fully managed alternative that doesn't require sizing a Spark cluster:

OPTIMIZE sales.orders REWRITE DATA USING BIN_PACK;

OPTIMIZE groups small files into larger files using bin packing and merges delete files with existing data files. For hierarchical sorting or Z-order clustering, use Spark on Amazon EMR or AWS Glue instead.

You can override the defaults per table by passing optimize_* table properties (e.g., optimize_rewrite_data_file_threshold, optimize_rewrite_delete_file_threshold) in CREATE TABLE, or with ALTER TABLE after creation — see Iceberg table properties in the Athena documentation.

Recommendations by use case

Use case

Recommendation

Scheduled bin-packing compaction

Use Athena OPTIMIZE if you don't know how many small files the table contains — Athena bills on data scanned, so if there's nothing to compact there's no cost. Run per partition to avoid Athena query timeouts on large tables. For larger volumes of small files, use Amazon EMR or AWS Glue with dynamic scaling.

Event-driven bin-packing compaction

Use Amazon EMR or AWS Glue with dynamic scaling.

Sort compaction

Use Amazon EMR or AWS Glue — sorting is expensive and may need to spill to disk.

Z-order clustering

Use Amazon EMR or AWS Glue — Z-order sorting is very expensive and may spill to disk.

Partitions still receiving late-arriving writes

Use Amazon EMR or AWS Glue and enable partial-progress.enabled. If a data file is updated mid-compaction, retry cost is limited to the affected commit instead of the whole job.

Cold partitions (no active writes)

Use Amazon EMR or AWS Glue and pass a where predicate that excludes actively-written partitions. This avoids data conflicts between writers and compaction, leaving only metadata conflicts that Iceberg resolves automatically.

Snapshot expiration — expire_snapshots

Iceberg keeps every historical snapshot until you expire it explicitly. Snapshots are what let you time-travel and roll back, but they also keep the underlying data files alive. Expire snapshots regularly to release storage and to control the size of the table history metadata.

Basic invocation (expire everything older than 7 days but keep the last 5 snapshots):

CALL iceberg_catalog.system.expire_snapshots( table => 'sales.orders', older_than => TIMESTAMP '<now minus 7 days>', retain_last => 5 )

Common parameters:

Parameter

Purpose

Default

table

Table to expire snapshots from

required

older_than

Only expire snapshots older than this timestamp

5 days ago (Iceberg default), overridable by table property history.expire.max-snapshot-age-ms

retain_last

Minimum number of most-recent snapshots to keep, even if they're older than older_than

1, overridable by table property history.expire.min-snapshots-to-keep

snapshot_ids

Explicit list of snapshot IDs to expire

not set (use age-based rules)

stream_results

Stream file-deletion work rather than collecting to the driver

false

max_concurrent_deletes

Number of concurrent file-delete threads

none (deletes run single-threaded unless set)

Table properties that let you encode the policy on the table itself (so the procedure picks them up automatically when the parameters are omitted):

  • history.expire.max-snapshot-age-ms — sets the default older_than window (in milliseconds).

  • history.expire.min-snapshots-to-keep — sets the default retain_last value.

Example — retain at least 10 snapshots and never expire anything younger than 30 days, using table properties so downstream tooling inherits the same policy:

ALTER TABLE iceberg_catalog.sales.orders SET TBLPROPERTIES ( 'history.expire.max-snapshot-age-ms' = '2592000000', -- 30 days 'history.expire.min-snapshots-to-keep' = '10' ); CALL iceberg_catalog.system.expire_snapshots( table => 'sales.orders' );

Unreferenced file removal — remove_orphan_files

remove_orphan_files scans the table's storage location and deletes files that no snapshot metadata references. Typical sources of unreferenced files are failed writes, files written outside Iceberg (for example, by a hand-crafted job that copied Parquet into the table's location), and residuals from interrupted maintenance runs.

Basic invocation (a safe first run — list-only, no deletes):

CALL iceberg_catalog.system.remove_orphan_files( table => 'sales.orders', dry_run => true )

Common parameters:

Parameter

Purpose

Default

table

Table to scan

required

older_than

Only consider files older than this timestamp (protects concurrent writers)

3 days ago

location

Override the location that is scanned; defaults to the table's location. Set this if you moved data or want to scan a sub-prefix

table location

dry_run

List files that would be deleted without actually deleting them

false

max_concurrent_deletes

Number of concurrent file-delete threads

4

file_list_view

Provide an external list of files to consider instead of listing the location

not set

Important

remove_orphan_files compares the physical listing of the table's storage to the file references in the metadata. If a writer is actively writing new files, they can look like unreferenced files until the writer commits. The scanned location must belong to this table only; never point the procedure at a shared warehouse or shared prefix. Keep prefix_mismatch_mode at ERROR; declare known URI aliases with equal_schemes or equal_authorities instead. Run dry_run => true on every new location or configuration, not only the first time. Use older_than (default 3 days) to give in-flight writers time to finish.

Example — delete unreferenced files older than 7 days from a specific sub-prefix:

CALL iceberg_catalog.system.remove_orphan_files( table => 'sales.orders', location => 's3://<bucket-name>/sales/orders/data/', older_than => TIMESTAMP '<now minus 7 days>' )

Running VACUUM (snapshots expiration and unreferenced files removal) with Amazon Athena

Amazon Athena exposes Iceberg's snapshots expiration and unreferenced files removal as a single VACUUM statement — a fully managed alternative that doesn't require sizing a Spark cluster:

VACUUM sales.orders;

You can override the defaults per table by passing vacuum_* table properties (e.g., vacuum_min_snapshots_to_keep, vacuum_max_snapshot_age_seconds, vacuum_max_metadata_files_to_keep) in CREATE TABLE, or with ALTER TABLE after creation — see Iceberg table properties in the Athena documentation.

Self-managed maintenance can be driven either on a fixed schedule or event-based off table observations. Both approaches use the same procedures — only the trigger differs.

On a fixed schedule

There isn't one right schedule for all workloads, but a common starting point for self-managed Iceberg tables on Amazon S3 is:

  • Compaction – hourly to daily for streaming or high-frequency ingest tables; daily to weekly for batch-ingest tables. Use partial-progress.enabled=true for large tables so that partial progress isn't wasted on retry.

  • Snapshot expiration – daily. Keep enough history to meet your recovery objective (typically 7–30 days).

  • Unreferenced file removal – weekly or monthly. Always start with dry_run => true on a table you haven't cleaned before.

Event-based, driven by monitoring

Instead of running maintenance on a fixed calendar, you can trigger each procedure when the table itself signals that it needs work — using the Iceberg metadata tables (files, partitions, snapshots, manifests, and so on) or metrics reporters described in Monitoring Iceberg workloads. This aligns work with actual table state and avoids paying for no-op runs. Common triggers:

  • Compaction — run when the count of small files in a partition crosses a threshold (query the files or partitions metadata table for files below 75% of write.target-file-size-bytes, which matches Iceberg's min-file-size-bytes default).

  • Compaction (merge delete files) — run when the ratio of delete files to data files (or the count of delete files per partition) crosses a threshold, indicating merge-on-read reads are getting expensive.

  • Snapshot expiration — run when the number of snapshots (snapshots metadata table) or the ratio of total table storage to live data files exceeds a threshold, indicating that old snapshots are pinning significant storage.

  • Unreferenced file removal — run when a scheduled ingestion job reports failed writes, or when object storage totals for the table location grow faster than the referenced-data-files size in the metadata.

See Monitoring Iceberg workloads for the specific metadata-table queries and metrics reporter fields you can use to build these triggers.

AWS-native alternatives

For an AWS-native alternative that runs these operations for you, see AWS Glue Data Catalog table optimizer. For Iceberg tables hosted in Amazon S3 Tables, the service performs all three activities automatically — see Amazon S3 Tables built-in maintenance.