advanced29 min studyLesson 299 in Engineering

Compact files without publishing duplicates or losing readers

Estimate metadata amortization and rewrite costs while preserving snapshot visibility, row semantics, and safe reclamation of replaced files.

On this page

What you’ll understand

  • Estimate the fixed per-file cost compaction can amortize.
  • Separate writing replacement files from atomically publishing a new table snapshot.
  • Preserve row multiplicity, deletes, schema, and active-reader references during maintenance.

A dataset made of thousands of tiny columnar files can spend more effort opening, inspecting, and scheduling files than scanning their payload. Compaction rewrites data into a more useful layout, but it is also a transactional maintenance operation. Simply placing larger files beside smaller ones can duplicate answers, and deleting the originals too early can break active readers. Plan the performance gain and the publication protocol as parts of the same change.

Amortize fixed costs without assuming one ideal file size

Every file can introduce metadata discovery, footer reads, request setup, task scheduling, and decoder initialization. These costs can dominate very small payloads, especially across a remote storage interface. Combining files can amortize them and create more useful row groups. Yet overly large files can reduce task granularity, complicate balanced work, or weaken selective scans if clustering is lost. Choose target sizes from representative scans, available task parallelism, writer memory, and the table's partition boundaries rather than declaring one universal megabyte value optimal.

Compaction is not necessarily simple byte concatenation. Valid output requires new file metadata, page and chunk boundaries, encodings, and statistics. If it changes row order, keep every column aligned. If the table has deletes or other row-level change semantics, use the table engine's supported rewrite operation so those changes remain correctly applied. Preserve duplicates unless the table's explicit semantics call for deduplication; two identical rows can be legitimate observations. Row count alone is a useful check but cannot prove value equality, multiplicity, or correct treatment of deletes.

Tsetup≈Fτ,ΔTsetup≈(Fold−Fnew)τT_{\rm setup}\approx F\tau,\qquad \Delta T_{\rm setup}\approx(F_{\rm old}-F_{\rm new})\tau
F counts files visited and tau is an assumed non-overlapped fixed setup cost in seconds per file. The estimate excludes concurrent overlap, caching, discovery differences, data transfer, decoding, and changed pruning. It identifies one opportunity rather than predicting a complete query speedup.↔ Scroll wide equations horizontally.

Create outputs privately, then change the visible snapshot

A table snapshot identifies the data-file set readers should use. A compactor can write new immutable output files, validate them, and propose a new metadata state that replaces selected old files with their outputs. Publication must use the table/catalog's atomic commit and concurrency checks so a concurrent writer's changes are not overwritten. Iceberg's specification separates immutable data/metadata files from the atomic metadata update. The exact commit mechanism depends on the catalog; neither listing a directory nor assuming object-store rename behaves like a local transaction establishes equivalent guarantees.

A failed or uncertain commit needs inspection through the table protocol, not an immediate deletion of anything whose name looks temporary. After success, older snapshots or active readers can still reference replaced files. Reclamation therefore follows retention, snapshot-expiration, and orphan-cleanup rules with enough safety for in-flight work. Deleting all files absent from the newest listing can destroy valid older views or an uncommitted writer's outputs. Keep identifiers and metadata evidence that distinguish unreferenced debris from files still protected by another valid table state.

Trewrite≈DrBr+DwBw+TCPU,qbreak-even>TrewriteΔTqueryT_{\rm rewrite}\approx\frac{D_r}{B_r}+\frac{D_w}{B_w}+T_{\rm CPU},\qquad q_{\rm break\text{-}even}>\frac{T_{\rm rewrite}}{\Delta T_{\rm query}}
The serialized model reads D_r bytes and writes D_w bytes at effective rates B_r and B_w, plus CPU time. If every equivalent future query saves positive Delta T_query seconds, more than this ratio of queries repays rewrite time under the same time-cost model. Resource prices and overlap need separate treatment.↔ Scroll wide equations horizontally.

Validate benefit, semantics, and maintenance pressure

Compare pre- and post-compaction query results against the same snapshot contents, including nulls, nested values, duplicates, and deleted records. Check output statistics, row groups, encodings, and compatibility before publication. Then measure scan setup, fetched bytes, decode CPU, peak memory, and end-to-end latency on a workload of queries. A sorted rewrite may improve one predicate while hurting another; a denser codec may reduce storage while increasing decode cost. Include temporary space, I/O contention with ingestion, and the expected lifetime over which benefits can accumulate.

The queue lab isolates maintenance pressure with equal-sized compaction jobs. Reset, set both arrival λ=4 and service μ=2, predict growth from the initial four jobs, then Play or Step. For a separate adequately provisioned case, Reset, re-enter both λ=2 and μ=3, predict drainage from four, then inspect. Slider edits retain elapsed time and recompute from the initial four; they do not switch the accumulated queue to new rates. This fluid model has no files, snapshots, concurrency checks, or storage-cost estimates; it only illustrates whether maintenance demand outruns completion.

Estimate a metadata-driven compaction opportunity

An eight-decimal-GB partition contains 4,000 equal two-MB files. Compaction produces sixteen 500-MB files. Assume serialized per-file setup is 2 ms and rewriting reads and writes all eight GB at 1 GB/s each, with no CPU or overlap cost.

  1. The original fixed setup term is 4,000 × 0.002 = 8 seconds. The compacted term is 16 × 0.002 = 0.032 seconds, saving 7.968 seconds for a query that visits the entire partition under this model.

  2. The rewrite reads eight GB in eight seconds and writes eight GB in another eight, totaling sixteen seconds. Before old files are reclaimed, old plus new payload can occupy sixteen GB, excluding other temporary and metadata space.

  3. Sixteen divided by 7.968 is about 2.008, so at least three equally benefiting full-partition queries are needed to exceed the modeled rewrite time. Verify unchanged answers and successful atomic publication before counting any gain.

The result

Compaction can repay fixed setup cost quickly in this hypothetical workload, but pruning, concurrency, CPU, retention, and actual catalog publication can change the tradeoff.

Explore the model

Interactive lab

Interactive lab · queue

Can maintenance finish faster than it arrives?

Reset, set both λ=4 and μ=2 for equal-sized compaction jobs, predict growth from four jobs, then Play or Step. Reset and re-enter both λ=2 and μ=3 for a separate drainage case. Edits retain elapsed time and recalculate from initial four. The fluid queue does not rewrite files, publish snapshots, or model compaction I/O and CPU.

Can maintenance finish faster than it arrives?Fluid backlog starts at 4 and follows max(0, 4 + (λ − μ)t). The separate M/M/1 residence-time formula assumes Poisson arrivals, exponential service and λ < μ. Current readings: Fluid backlog: 4; Net rate · λ − μ: −1 /s; M/M/1 mean residence: 1 s. All parameters are adjustable with the labeled controls below.02.557.51001.534.56Elapsed time · sFluid backlogλ < μ
Fluid backlogCurrent time
Fluid backlog
4
Net rate · λ − μ
−1 /s
M/M/1 mean residence
1 s
t = 0 s

Fluid backlog starts at 4 and follows max(0, 4 + (λ − μ)t). The separate M/M/1 residence-time formula assumes Poisson arrivals, exponential service and λ < μ. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.

Look forAmortizing file setup does not remove rewrite work or the need to keep maintenance demand within its service capacity.

Check your understanding

A compactor has written valid replacement files while readers still use an older table snapshot. Which next action best preserves the stated table semantics?

Try it yourself

A rewrite costs thirty seconds and saves five seconds on each equivalent future scan under the same serialized time model. How many scans are needed to exceed the rewrite cost, and name one semantic check required before claiming the gain?

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

Distinguish matching the cost from exceeding it, then consider row contents rather than only file count.

Compare with the solution

Six scans exactly match thirty seconds; seven exceed it at thirty-five seconds of modeled savings. Before claiming an equivalent improvement, verify preserved query results and row multiplicities, including nulls and applicable deletes, and confirm correct table publication. Real economics can differ because rewrite I/O competes with ingestion and query savings may vary.

Take it with you

  • Compaction can amortize per-file overhead while creating rewrite, memory, and temporary-space costs.
  • New immutable files become table state through a checked atomic metadata publication.
  • Retain replaced files for valid older views and verify semantic equivalence before measuring gains.

Read further

Original sources and deeper explanations to follow at your own pace.

Optional progress, saved in this browser when available. Revisit any lesson at any time.

Lesson not marked complete.