Partitioning, Compaction, and Table Maintenance

A table that performed well in its first week often performs worse in its fourth with no change to the query and no growth in data that explains it. The usual cause is layout: a streaming job has committed thousands of small files, a partition scheme that suited the first month no longer suits the data, and every write has left an old snapshot behind. None of this is a bug, because the commit protocol of an open table format makes each change safe, and safety is bought by never editing files in place. The price is that someone has to keep the layout healthy.

This article covers that work in the order a table owner meets it: how big files should be and why, how to choose partitions, how a reader prunes what it does not need, how compaction repairs layout, how snapshot expiry releases the storage that compaction and updates leave behind, and how to check that all of it paid for itself. It builds on Open Table Formats: Snapshots, Transactions, and Catalogs, which explained snapshots, manifests, atomic commits, and why a replace operation such as compaction must validate that the files it removes are still present. Iceberg is the main worked example because its documentation specifies the operations and defaults precisely; Delta Lake equivalents are noted where they differ. Defaults and procedure options were read from the Iceberg and Delta Lake documentation on October 3, 2026. Every numeric workload in this article is an assumption chosen for illustration, labeled as such, and the code listings are small models written for this article. Your tables will give different numbers, which is the reason the last section is about measuring.

File sizing: why both extremes cost

The fixed cost of a file

Reading data from object storage has a cost per request and a cost per byte. The per-byte cost is what a column format and compression reduce. The per-file cost does not shrink with the file: a planner must find the file in metadata, a task must be scheduled for it, the reader must open it and fetch its footer before reading any column chunk (as the file formats article described), and the engine must track it. A file compaction glossary entry gives the same account from the engine side. When files are large, these fixed costs are a negligible fraction of the work. When files are tiny, they dominate.

There is also a metadata cost. In Iceberg, each data file is one entry in a manifest, with its partition tuple and column metrics. The maintenance documentation says more data files lead to more metadata in manifest files, and that small files add unnecessary metadata and make queries less efficient because of file-open costs (Iceberg maintenance, Compact data files). A table with a million tiny files has a million manifest entries to read before any data is read.

Why very large files also cost

  • Parallelism. A file is the unit of parallel work unless the reader can split it by row group. A table of four enormous files cannot keep 100 executors busy.
  • Skipping granularity. File-level min/max statistics skip whole files. The coarser the file, the more likely its range overlaps any given filter.
  • Rewrite cost. Under copy-on-write, deleting or updating one row rewrites the file that contains it. Iceberg’s row-level commands default to copy-on-write mode (write.delete.mode, write.update.mode, and write.merge.mode default to copy-on-write), and the amount rewritten per change grows with file size (Iceberg configuration).
  • Memory. Writers buffer a row group before flushing it, so larger row groups need more memory per task.

What the documentation sets as defaults

SettingValueSource
Iceberg write.target-file-size-bytes536,870,912 (512 MB)Iceberg configuration
Iceberg write.parquet.row-group-size-bytes134,217,728 (128 MB)Iceberg configuration
Iceberg rewrite_data_files min-file-size-bytes, max-file-size-bytes75% and 180% of the target file sizeIceberg Spark procedures
Delta Lake auto compaction target file size when enabled with true128 MBDelta Lake optimizations
Parquet documentation’s recommended row-group size512 MB to 1 GB, in a configuration aimed at HDFS-block-aligned layoutsParquet configurations

The values disagree on purpose, because they answer different questions and assume different storage. The Parquet recommendation comes with a setup of 1 GB row groups aligned with 1 GB HDFS blocks, and the same page notes that larger row groups allow larger column chunks, which makes reads more efficient. Iceberg’s 128 MB row groups inside 512 MB files are a default for general use. The earlier article treated a 128 MB row group and files of a few hundred MB as starting hypotheses rather than universal answers. This article takes the same stance: choose a target in the hundreds of megabytes, then test it against your queries. No source read for this article establishes a single best size.

One practical point from the Iceberg Spark documentation: Spark cannot write a file larger than a Spark task’s data, and a file cannot span an Iceberg partition boundary. A 100 MB Spark task writes a file much smaller than 100 MB, because the on-disk data is compressed and columnar while the in-task data is row-based and uncompressed, and a task that writes to several partitions makes proportionally smaller files (Iceberg Spark writes, Controlling File Sizes). Setting the target file size property alone does not produce large files if the tasks are small. The write distribution mode (default hash since Iceberg 1.2.0) shuffles rows so each task receives the data for a limited set of partitions.

How small files accumulate: a calculation

Take a hypothetical streaming table, payment_events, that receives 4 GB per hour, and a job that commits once per minute using 8 write tasks. Assume the table is partitioned by 50 country values with roughly uniform volume, and that each task writes one file per partition it holds rows for, as happens when no shuffle groups rows by partition. All inputs are assumptions. The script models only the arithmetic of file counts.

import math
ingest_gb_per_hour = 4.0                  # assumed input rate
mb_per_commit = ingest_gb_per_hour * 1000 / 60      # one commit per minute
tasks, countries = 8, 50                  # assumed writer tasks and partition values
target_mb, open_cost_s, readers = 512, 0.05, 100

for label, parts in (("unpartitioned", 1), ("partitioned by country", countries)):
    files_per_commit = tasks * parts      # every task writes one file per partition it sees
    files_per_day = files_per_commit * 1440
    print(f"{label:24s} files/commit={files_per_commit:4d}  avg file={mb_per_commit / files_per_commit:6.2f} MB"
          f"  files/day={files_per_day:7d}  open time on {readers} readers={files_per_day * open_cost_s / readers:7.1f} s")

day_gb = ingest_gb_per_hour * 24
files_after = countries * math.ceil(day_gb * 1000 / countries / target_mb)
print(f"after compaction to {target_mb} MB: {files_after} files/day, open time {files_after * open_cost_s / readers:.2f} s")
unpartitioned            files/commit=   8  avg file=  8.33 MB  files/day=  11520  open time on 100 readers=    5.8 s
partitioned by country   files/commit= 400  avg file=  0.17 MB  files/day= 576000  open time on 100 readers=  288.0 s
after compaction to 512 MB: 200 files/day, open time 0.10 s

Two lessons come out of this. The first is multiplication: files per commit equal write tasks times the partitions each task touches, so adding a partition column multiplied the file count by 50 without changing the data volume. The second is the size of the effect. Under an assumed 50 ms of fixed cost per file, opening a day’s files costs 288 executor-seconds spread across 100 readers, compared with 0.1 s after compaction to roughly 512 MB files. The 50 ms figure is an assumption, as the true fixed cost depends on storage, region, caching, and the engine. The arithmetic shows the shape, which is linear in file count, and is not a prediction. Note too that compaction cannot create a 512 MB file out of a partition that holds 80 MB. With these assumptions each country-hour holds about 82 MB, so a plan to compact to 512 MB must first decide how to define partitions that are big enough to fill one.

Partition design

What partitioning is for

Partitioning groups rows into separate files by a function of their values. It does four useful things. It lets a reader skip groups that cannot match a filter, it co-locates data that is queried and written together, it keeps concurrent operations on different groups from conflicting (the Delta documentation’s recommendation for avoiding conflicts), and it lets whole groups be dropped when data expires. It also has costs: every partition value produces at least one file per writer, and partition boundaries cap file size.

Iceberg adds a distinction that changes how partitioning is used. In Hive-style tables, the partition value is a visible column that writers must supply and queries must filter on correctly. The Iceberg documentation describes the failure modes: a wrong format such as 2018-12-01 instead of 20181201, a wrong source column, or a wrong time zone produce silently incorrect results, and queries that do not filter on the partition column scan everything. Iceberg’s hidden partitioning derives partition values from a column through a transform, so the partition layout is configuration the user never sees in queries (Iceberg partitioning).

TransformEffectTypical use
identityThe value itselfLow-cardinality categories
year, month, day, hourTruncates a date or timestamp to that granularityEvent time
bucket[N]32-bit Murmur3 hash of the value, modulo NHigh-cardinality keys when only equality lookups matter
truncate[W]Value truncated to width W (integers, strings, binary, decimals)Prefix grouping of strings or numeric ranges

The transforms are listed in the specification (Iceberg table spec, Partition Transforms). In Spark DDL they are used like this, with days as the Spark spelling of the daily transform:

CREATE TABLE prod.db.payment_events (
    event_id   bigint,
    user_id    bigint,
    country    string,
    event_ts   timestamp,
    amount     decimal(12, 2))
USING iceberg
PARTITIONED BY (days(event_ts), bucket(16, user_id));

This statement follows the syntax shown in the Iceberg Spark DDL documentation; it was not executed for this article. Its meaning: queries filtering on event_ts can prune by day, queries with user_id = ... can prune to one of 16 buckets, and no query has to mention the derived values. A range filter on user_id gets no benefit from bucket(16, user_id), because hashing destroys ordering. That is the cost of the transform, so bucket only when equality lookups are the access pattern.

A rule of thumb with arithmetic

A partition scheme is healthy when each partition is large enough to fill at least a few target-sized files and the filters of important queries select a small fraction of partitions. Test candidates with the data volume. Using the same assumed 96 GB per day:

SchemePartitions per dayAverage partition sizeFiles at 512 MB targetAssessment under these assumptions
day196 GBabout 188Good file sizes; day-granular filters prune; an intra-day filter scans a whole day unless files are sorted
hour244 GBabout 8 per partitionGood file sizes; hour filters prune
hour and 50 country values1,200about 82 MBless than 1 per partitionPartitions smaller than the target file; every partition is a small-file source
identity(user_id) with 10 million users10,000,000 or moreunder 10 KBfar less than 1Pathological: one or more files per user

The third row is the usual accident. Each added dimension multiplies the partition count and divides the size. Country might be a perfectly sensible filter column, but making it a partition column at this volume produces partitions smaller than one target file. Sorting or clustering by country within an hourly partition gives most of the filtering benefit through file statistics, without creating partitions. The Delta Lake documentation says the same in its own words: partitioning by a high-cardinality column can lead to other performance issues through a large number of subdirectories (Delta concurrency control).

Skew is the other thing to check. If one country holds 40% of the data, a country-partitioned layout has one big partition and many tiny ones, and the data skew that results shows up in compaction tasks as well as in queries.

Changing your mind later

Iceberg partition evolution is metadata-only: an ALTER TABLE ... ADD PARTITION FIELD, DROP PARTITION FIELD, or REPLACE PARTITION FIELD changes how new data is written, and existing files keep the layout they were written with. A table can hold data under several partition specs at once, and each spec is planned separately. The DDL documentation warns that dynamic partition overwrite changes behavior when the partitioning changes. Its example: after moving from daily to hourly partitioning, an overwrite replaces hourly partitions but no longer daily ones. Dropping a partition field also changes the schema of metadata tables such as files and can break queries against them (Iceberg Spark DDL). To bring old data into the new layout you must rewrite it, and compaction with an output spec ID is the documented way to do that.

Pruning: three levels of not reading

A query engine can discard data at three levels, and they use different metadata. Each level can only discard what its metadata proves cannot match, so each produces a candidate set, and rows inside candidates are still evaluated.

LevelMetadata usedWhat is skippedNeeds the layout to cooperate when
ManifestPartition summaries and counts in the manifest listWhole manifestsManifests group files with similar partition values
Data filePartition tuple and per-column bounds in manifest entriesWhole filesFiles have narrow value ranges for the filtered column
Row groupPer-chunk statistics in the Parquet footerRow groups inside an opened fileRows are ordered so that groups have narrow ranges

The Iceberg specification describes scan planning this way: scan predicates are converted to partition predicates by an inclusive projection, which means a file is selected if it may contain matching rows. Its example is an events table partitioned by day(ts) and queried with ts > X: the inclusive projection is ts_day >= day(X), so files from the day containing X are still read even though many of their rows do not match (Iceberg table spec, Scan Planning). Partition pruning selects candidates, and statistics narrow them further, as the partition pruning and predicate pushdown entries describe. The footer-level skipping inside a file is the row-group and column-chunk mechanism from the earlier Parquet article.

Statistics only help if the layout narrows ranges

File-level min/max statistics skip a file only when the file’s range excludes the filter value. Rows written in arrival order scatter a column like user_id across every file, so every file’s range spans nearly the whole domain. Sorting the same rows by the column before writing makes ranges narrow and disjoint. The following model, written for this article with only the standard library, builds 100 files from 200,000 synthetic user_id values (1 to 100,000) in two layouts and counts how many files could contain the queried values according to min/max alone.

import random
rnd = random.Random(11)
rows = [rnd.randint(1, 100_000) for _ in range(200_000)]      # synthetic user_id values
FILES = 100

def stats(layout):
    size = len(layout) // FILES
    return [(min(c), max(c)) for c in (layout[i:i + size] for i in range(0, len(layout), size))]

def candidates(file_stats, lo, hi):
    return sum(1 for mn, mx in file_stats if mx >= lo and mn <= hi)

arrival = rows                              # files cut in arrival order
clustered = sorted(rows)                    # same rows, rewritten sorted by user_id
for name, layout in (("arrival order", arrival), ("sorted by user_id", clustered)):
    s = stats(layout)
    print(f"{name:18s} point lookup candidates: {candidates(s, 4242, 4242):3d}/{FILES}"
          f"   range 4000-4999 candidates: {candidates(s, 4000, 4999):3d}/{FILES}")
arrival order      point lookup candidates: 100/100   range 4000-4999 candidates: 100/100
sorted by user_id  point lookup candidates:   1/100   range 4000-4999 candidates:   2/100

The same rows, in a different order, change a point lookup from 100 candidate files to one, and the range query from 100 to two. Compression, file sizes, and values are identical across the two cases, so the difference comes entirely from ordering. Real tables have more nuance: statistics are optional, and Iceberg exposes metrics modes (none, counts, truncate(length), full) that decide which bounds are kept, so a column with metrics set to counts offers no min/max to skip with. Also, a sort on one column cannot give narrow ranges for every column, which is why multi-column sorts degrade quickly.

When more than one column is filtered, both Iceberg and Delta offer space-filling-curve orderings. Iceberg’s rewrite_data_files accepts strategy => 'sort' with zorder(c1,c2) or hilbert(c1,c2) as the sort order. Delta’s ZORDER BY colocates related values, and its documentation notes two limits: effectiveness drops with each additional column, and Z-ordering is not idempotent, because each run tries to create a new clustering across all files in a partition (Delta Lake optimizations). Warehouses have the same idea under other names, covered by the clustered table, micro-partition, and clustering depth entries: BigQuery clustering sorts within storage blocks, and Snowflake tracks how much value ranges overlap across micro-partitions.

Ways pruning silently fails

  • Filter shape. A filter that wraps the column in a function (for example casting or formatting it) may not be translatable into a predicate against statistics. Check the query plan for the number of files scanned rather than assuming.
  • Time semantics. Partitioning by ingestion time does not prune an event-time filter, since late-arriving events land in later partitions. Use the column the filters use.
  • Metadata skew. If manifests mix files from all partitions, manifest-level skipping cannot discard anything. The maintenance documentation says manifests are compacted in the order they are added, which suits write patterns that align with read filters (hourly data written as it arrives), and that a mismatch can be repaired with rewriteManifests.
  • Overlapping specs. After partition evolution, old data is planned under its old spec. A filter that prunes well under the new spec may not prune old files.

Compaction: repairing layout

Compaction reads small files and writes larger ones with the same logical rows. In an open table format that is an ordinary replace commit. The new files are added and the old ones are removed in one atomic snapshot, so readers on earlier snapshots are unaffected and the table’s contents do not change. The Delta documentation states that a read before and after OPTIMIZE returns the same results and that readers use snapshot isolation, so they are not interrupted when files are removed from the log.

Iceberg’s rewrite_data_files

The Spark procedure reads files, groups them, rewrites each group, and commits. The grouping step matters: the rewrite is split into file groups by partition and size so very large partitions can be rewritten within cluster limits. Selection decides which files are worth rewriting. The documented defaults are:

OptionDefaultMeaning
target-file-size-bytes536,870,912 (512 MB)Output size target; defaults to the table’s write target
min-file-size-bytes75% of targetFiles below this size are candidates regardless of other criteria
max-file-size-bytes180% of targetFiles above this size are candidates (they are split)
min-input-files5A file group with at least this many files is rewritten regardless of other criteria
max-file-group-size-bytes100 GBLargest amount of data rewritten in one file group
max-concurrent-file-group-rewrites5File groups rewritten simultaneously
partial-progress.enabledfalseCommit groups of files before the entire rewrite is done
partial-progress.max-commits10Upper bound on commits when partial progress is on
delete-ratio-threshold0.3Minimum deleted fraction that makes a data file a candidate
use-starting-sequence-numbertrueUse the sequence number of the snapshot at compaction start rather than the new snapshot’s
remove-dangling-deletesfalseRemove delete files that no longer apply, with an additional commit

These values come from the procedure’s documentation (Iceberg Spark procedures, rewrite_data_files). Note the selection logic: a file below 75% of the target is a candidate, a group with at least five files is rewritten whatever its sizes, and a fully tidy partition with files between 75% and 180% of the target is left alone. That is what keeps repeated runs cheap on the parts of the table that are already healthy.

-- Compact only the closed hours of the last day; leave the open hour for the writer.
CALL prod.system.rewrite_data_files(
  table => 'db.payment_events',
  where => 'event_ts >= TIMESTAMP ''2026-10-02 00:00:00'' AND event_ts < TIMESTAMP ''2026-10-03 00:00:00''',
  options => map('partial-progress.enabled', 'true', 'max-concurrent-file-group-rewrites', '10'));

-- Re-sort a partition so min/max statistics prune well on user_id.
CALL prod.system.rewrite_data_files(
  table => 'db.payment_events',
  strategy => 'sort',
  sort_order => 'user_id ASC NULLS LAST',
  where => 'event_ts >= TIMESTAMP ''2026-10-02 00:00:00'' AND event_ts < TIMESTAMP ''2026-10-03 00:00:00''');

These statements use the named-argument syntax from the Iceberg procedure documentation. They were not executed for this article, and the table, dates, and option values are illustrative. The where argument is described as a filter on files, with the note that all files that may contain matching data are selected for rewriting, so a filter on the partition column selects whole partitions while a filter on another column can pull in files that merely overlap it.

Delta Lake’s OPTIMIZE and auto compaction

Delta’s OPTIMIZE coalesces small files into larger ones and accepts a WHERE predicate on partition columns to limit the work. The documentation says bin-packing optimization is idempotent, so a second run over the same data has no effect, and that it aims at evenly balanced file sizes on disk rather than rows per file. Auto compaction (available from Delta Lake 3.1.0) runs synchronously after a successful write on the cluster that did the write, compacts only files not previously compacted, and, when enabled with true, targets 128 MB by default (Delta Lake optimizations). Running compaction inside the write path removes the need for a separate job, and it adds the compaction time to the writer’s critical path.

Compaction and concurrent writers

Compaction is a replace operation, and the previous article’s conflict rules apply. Appends do not conflict with it, because they add files it does not touch. A row-level update, delete, or merge that rewrites one of its input files does conflict, since the compaction’s precondition (that its input files still exist) no longer holds. Delta’s matrix agrees: compaction cannot conflict with an insert, and can conflict with an update, delete, merge, or another compaction. The practical rules follow.

  • Compact partitions that have stopped changing. A closed hour or day cannot be hit by a late update unless the pipeline allows late data, so restricting compaction to closed partitions avoids most conflicts.
  • Avoid running two compactions over the same partition. Delta documents this case as ConcurrentDeleteDeleteException.
  • Use partial progress for large rewrites. Without it, a conflict near the end of a long rewrite discards all the work. With it, completed file groups are committed as they finish, up to the commit limit, so a failure costs only the unfinished groups. The cost is more snapshots, and it is fair to guess the doc’s use-starting-sequence-number default exists so that delete files committed while the rewrite was running, which carry higher sequence numbers, still apply to the rewritten files. That reading follows from the sequence-number rules in the specification but is an inference, not a sentence from the documentation.

Write amplification: how often is too often

Compaction writes bytes that were already written, and the amount depends on the schedule. Using the assumed 4 GB per hour, 96 GB per day, compare compacting each hour once after it closes with recompacting the whole day every hour. The second schedule rewrites hour 1 twenty-four times, hour 2 twenty-three times, and so on.

# All inputs are assumptions chosen for illustration, not measurements.
open_cost_s   = 0.05        # executor-seconds of fixed cost per file opened (list/open/footer)
io_mb_per_s   = 100         # executor throughput for reading or writing data, MB/s
hour_gb       = 4.0         # data landed in one hourly partition
files_before  = 8 * 50 * 60 # 8 tasks x 50 countries x 60 one-minute commits
files_after   = 50          # one ~82 MB file per country after compaction

scan_before = files_before * open_cost_s                  # per-query fixed cost, file opens only
scan_after  = files_after  * open_cost_s
saving      = scan_before - scan_after

compaction  = files_before * open_cost_s + hour_gb * 1000 / io_mb_per_s * 2   # read + write the bytes
print(f"files before/after        : {files_before} / {files_after}")
print(f"per-query open cost       : {scan_before:.0f} s -> {scan_after:.1f} s (saves {saving:.0f} executor-s)")
print(f"one-time compaction cost  : {compaction:.0f} executor-s")
print(f"break-even queries        : {compaction / saving:.2f}")

# write amplification of two schedules for one 96 GB day
hourly_once = 96.0
rolling_day = sum(4.0 * h for h in range(1, 25))
print(f"compact each closed hour once : rewrites {hourly_once:.0f} GB  -> amplification {hourly_once/96:.1f}x")
print(f"recompact whole day hourly    : rewrites {rolling_day:.0f} GB -> amplification {rolling_day/96:.1f}x")

# storage held while old snapshots remain, daily compaction, 5-day expiry window
day_gb, window_days = 96.0, 5
live = 14 * day_gb                     # assume 14 days of live data
extra = window_days * day_gb           # pre-compaction copies still referenced by retained snapshots
print(f"live {live:.0f} GB, extra retained {extra:.0f} GB -> {(live+extra)/live:.2f}x live size")
files before/after        : 24000 / 50
per-query open cost       : 1200 s -> 2.5 s (saves 1198 executor-s)
one-time compaction cost  : 1280 executor-s
break-even queries        : 1.07
compact each closed hour once : rewrites 96 GB  -> amplification 1.0x
recompact whole day hourly    : rewrites 1200 GB -> amplification 12.5x
live 1344 GB, extra retained 480 GB -> 1.36x live size

The script combines three small calculations, and every input is an assumption. The first block compares the fixed cost of opening 24,000 small files per hourly partition (8 tasks times 50 countries times 60 commits) with 50 compacted files, under the assumed 50 ms per file open. A single query saves about 1,198 executor-seconds, and the compaction job costs about 1,280 executor-seconds (the same open cost to read the small files plus reading and writing 4 GB at 100 MB/s), so compaction pays for itself after about one query that reads that hour. That break-even changes with the numbers, but the structure is general: compaction cost divided by saving per query gives the number of queries needed. A partition that is never read again does not repay compaction, which is a reason to compact only partitions that queries actually touch.

The second block shows schedule matters more than tuning. Compacting each closed hour once rewrites each byte once. Recompacting the growing day every hour rewrites 1,200 GB for 96 GB of data, a 12.5x multiple. The third block anticipates the next section: the retained storage consequence of compaction.

Manifests and delete files

Two related kinds of metadata also need attention. Manifest rewriting (rewrite_manifests) re-groups data-file entries so manifests align with how queries filter, which helps when the write pattern differs from the read pattern. For tables using merge-on-read, row-level deletes are stored in delete files that readers must apply. Iceberg can rewrite position-delete files to compact small ones, and compaction of data files can absorb deletes: delete-ratio-threshold (default 0.3) makes a data file a rewrite candidate when enough of its rows are deleted, and remove-dangling-deletes removes delete files that no longer apply to any live data file (Iceberg maintenance). If you use merge-on-read to make updates cheap, plan the compaction that applies the deletes, otherwise read cost grows with every update.

Snapshot expiry: releasing what history holds

Every commit, including every compaction, creates a snapshot, and old snapshots keep their files alive. Iceberg’s maintenance documentation says snapshots accumulate until expired, recommends expiring them regularly to delete data files that are no longer needed and keep metadata small, and notes that expiring snapshots removes them from time travel, with data files deleted only when no snapshot that may be used for time travel or rollback still references them (Iceberg maintenance, Expire snapshots).

The retention rules

Retention is computed from table properties and per-reference settings. The specification’s algorithm starts with an empty retained set, removes references other than main that are older than their maximum age, adds every branch and tag’s snapshot, adds each branch’s ancestors until a snapshot is both older than max-snapshot-age-ms and beyond the minimum count to keep, and expires everything else (Iceberg table spec, Snapshot Retention Policy). The defaults are history.expire.max-snapshot-age-ms = 432,000,000 ms (5 days), history.expire.min-snapshots-to-keep = 1, and history.expire.max-ref-age-ms = forever for non-main references. The main branch never expires. The Spark procedure expire_snapshots defaults to snapshots older than 5 days and retaining the last 1 ancestor, and its documentation states it never removes files still required by a non-expired snapshot (Iceberg Spark procedures, expire_snapshots).

CALL prod.system.expire_snapshots(
  table => 'db.payment_events',
  older_than => TIMESTAMP '2026-09-28 00:00:00',
  retain_last => 20);

This also follows the documented syntax and was not executed. Choose older_than from a requirement, not from the default: how far back must a rollback reach after a bad write is discovered, and how long can the slowest reader or stream hold a snapshot? Time travel needs retained snapshots, so shortening retention shortens how far back an investigation can query. Tags exist for the case where one snapshot must be kept longer than the rest, such as a month-end close.

What expiry costs and what it does not do

Compaction increases storage temporarily. The old small files are still referenced by earlier snapshots, and the new large files are referenced by the new one, so the table holds both until the earlier snapshots expire. Under the assumptions in the script above (14 days of live data at 96 GB per day, daily compaction, and a 5-day expiry window in which each day’s pre-compaction files are still retained) the table holds 480 GB of retained pre-compaction files on top of 1,344 GB of live data, about 1.36 times the live size. A longer expiry window raises that figure in proportion, so retention trades recoverability for storage.

Expiry is also a privacy and deletion consideration. Deleting a row from a table writes a new snapshot without it, but the files containing the row remain in older snapshots and are physically deleted only after those snapshots expire and their files are removed. A policy that promises erasure has to include the expiry schedule, a topic taken up in Access, Retention, and Erasure Across Data Copies.

Orphan files and metadata files

Not every unreferenced file is the result of an expired snapshot. Failed or retried jobs can leave files that no table metadata references, and expiry cannot find those. The documentation describes deleteOrphanFiles for this. Its safety rule is the most important sentence in the maintenance guide: removing orphan files with a retention interval shorter than the time any write can take is dangerous, because in-progress files might be considered orphaned and deleted, which can corrupt the table. The default interval is 3 days (remove_orphan_files older_than defaults to 3 days ago), the procedure offers a dry_run option, and the guide warns that path strings are compared literally, so a change of file system authority can make live files look orphaned and lead to data loss (Iceberg maintenance, Delete orphan files). Run a dry run first and compare the list with what you expect.

Metadata files are separate. Each commit writes a metadata JSON file, and old ones are retained for history. The properties write.metadata.delete-after-commit.enabled (default false) and write.metadata.previous-versions-max (default 100) control tracking and deletion, and files that fall out of the tracked log become orphans removable only by orphan-file cleanup.

Delta Lake’s equivalents

Delta’s VACUUM removes data files that no table version within the retention threshold references; the default threshold is 7 days, and the command is not triggered automatically. The documentation recommends a retention of at least 7 days and requires that it exceed the longest-running transaction and the longest any stream can lag. It deletes data files only: log files are removed automatically and asynchronously after checkpoint operations, with a default log retention of 30 days (delta.logRetentionDuration), so time travel is limited by both. The command also has a dry run and a LITE mode that uses the transaction log instead of listing the directory (Delta Lake utility commands).

Ordering the jobs

Iceberg’s guide does not prescribe a sequence, so the following order is a recommendation, justified by what each step produces. Compaction produces replaced files and new snapshots. Manifest rewriting after compaction organizes the metadata the new snapshots reference. Snapshot expiry then releases the replaced files once retention allows. Orphan-file cleanup comes last, with an interval longer than any write, and removes what no metadata knows. Running orphan cleanup concurrently with long writers or with other jobs that stage files is the risky case.

Validating workload and cost

Maintenance is justified only by its effect on queries and cost, so it needs before-and-after measurements instead of confidence. The following checks cover the layout, the queries, and the bill.

  1. Measure the layout. Iceberg exposes metadata tables. SELECT * FROM prod.db.table.files returns per-file information, including record_count and file_size_in_bytes, so you can compute the distribution of file sizes per partition. The documentation recommends this table for deciding when to compact. The snapshots, manifests, and partitions tables answer the corresponding questions for history, metadata layout, and partition sizes.
  2. Replay representative queries. Pick the queries that matter (a dashboard, a daily aggregation, a point lookup) and record files scanned, bytes read, planning time, and wall time before and after. Bytes and files scanned are less sensitive to cache state than wall time. A result cache can turn a repeated query into a cache hit, so wall time from a second run does not measure the change.
  3. Report percentiles, not just means. A layout fix often helps the tail more than the median. Use the same percentile method before and after, as in the percentile entry’s guidance on stating the calculation method.
  4. Measure the write side. Track commit latency and the rate of commit conflicts and retries for writers. Maintenance that triggers conflicts moves cost from reads to writes.
  5. Account for the maintenance job itself. Record the compute time and bytes read and written by compaction, expiry, and orphan cleanup, and divide by the saving per query as in the break-even calculation.
  6. Track storage separately. Compare live data bytes with total bytes under the table location, because their gap is what snapshots, orphans, and metadata hold. A widening gap means expiry or orphan cleanup is not keeping up.

Treat a measured improvement as specific to the workload that produced it. A layout tuned for last quarter’s filter can be wrong for next quarter’s, so re-run the measurements when query patterns change.

A starting policy, with the reasons

The table below is a recommendation for a table like the hypothetical payment_events, not a documented default. Every row states the evidence a team would use to adjust it.

DecisionStarting pointReasonAdjust when
Target file sizeTable default (512 MB) for large tablesDocumented default; amortizes per-file costPartitions are smaller than the target, or scans are too coarse for the filters
Partition granularityCoarsest time grain that keeps partitions at least a few target filesFewer partitions and fewer small filesQueries routinely filter finer than the grain and cannot use file statistics
Compaction scopeClosed partitions onlyAvoids conflicts with writers and updatesLate data arrives into closed partitions
Compaction triggerFile count or size distribution from the files tableCompacts where the problem is, and the selection options skip healthy filesBreak-even queries per partition is high
Snapshot retentionSet from the longest rollback and reader requirementRetention is a recoverability decisionStorage gap between live and total grows
Orphan cleanupAt least the longest write duration, dry run firstPrevents deleting in-flight filesJobs with long staged writes are added
OwnershipA named owner per table or table group, with alerts on file counts and storage gapMaintenance not run is a silent costOwnership changes

Failure modes

SymptomCauseCheck or fix
Queries slow down although data volume is stableSmall-file accumulation or manifest skewFile size distribution from the files table; compaction and manifest rewrite
Compaction fails or is discardedConcurrent update or delete changed an input fileRestrict to closed partitions; use partial progress; reschedule away from row-level jobs
Storage grows after compactionOld files held by retained snapshotsExpire snapshots according to retention requirement
Reader fails with missing file errorsExpiry or vacuum retention shorter than a running readerRaise retention above the longest reader and stream lag
Table corruption after cleanupOrphan cleanup interval shorter than a write, or path mismatchDry run first; keep interval longer than any write; verify path authorities
Pruning no longer helpsFilter columns changed, or layout drifted after updatesCompare files scanned with files available; re-sort the hot partitions
Old data is not in the new layout after partition changePartition evolution does not rewrite existing filesRewrite old data with the new partition spec if the old layout hurts

Each failure has a measurable signature, which is why a maintenance plan names the metrics it watches. Without them, tuning is guesswork and the first sign of trouble is a slow dashboard.

References


Discover more from Insightful Data Lab

Subscribe to get the latest posts sent to your email.

Similar Posts

Questions, corrections, or additional insights?

This site uses Akismet to reduce spam. Learn how your comment data is processed.