Part 8 · Data layout · Chapter 28
Compaction, OPTIMIZE and VACUUM
Keeping a table healthy: what small files cost, how OPTIMIZE picks and bin-packs files and commits with dataChange=false, auto compaction and optimized writes, and how VACUUM decides what is safe to delete given tombstones, retention and time travel. Iceberg's rewrite, snapshot expiry and orphan removal for comparison.
After this chapter you should be able to:
- Trace which files OPTIMIZE compacts and how it packs them into bins.
- Explain why OPTIMIZE commits with dataChange=false and when it can retry after a conflict.
- Derive the set of files VACUUM deletes, and choose retention settings that keep time travel and long readers safe.
- Map Delta's maintenance commands to Iceberg's.
Chapters 25 to 27 decided which rows go in which file. This chapter is about the files themselves over time. Writes leave too many of them, too small. Rewrites leave old ones behind, and failed jobs leave files that no version references. Two commands handle this. OPTIMIZE rewrites small files into large ones, which is a commit. VACUUM deletes files no retained version needs, which touches storage but not the log. The code is in src/sim/layout/maintenance.ts, and the tests pin each rule below.
Small files
Every write task writes at least one file per partition it touches (chapter 25). A streaming query that commits every few seconds writes small files at a steady rate. Each file costs the same overhead whatever its size:
- Metadata. One
addaction, with its stats JSON, per file. Log replay, checkpoints and planning (chapter 26) all scale with the count. - Storage requests. At least one GET for the footer and one per column chunk read, with the latencies of chapter 3. A thousand 1 MB files take far more requests than one 1 GB file.
- Encoding. Small row groups give dictionary and run-length encoding less to work with, and each file repeats its footer.
The fix is to rewrite them as fewer, larger files. Each layout chapter touched this in its own way: Z-order and liquid clustering rewrite for locality. Plain compaction rewrites only for size.
Q1. A streaming job wrote 50,000 files of 2 MB. Which costs grow with the file count rather than the data size? (Select all.) (select all that apply)
OPTIMIZE: bin-packing
OPTIMIZE t [WHERE partition_predicate] without ZORDER BY on an unclustered table runs the compaction strategy. OptimizeExecutor.optimize does this, in order:[Delta OptimizeExecutor.optimize]
// OptimizeExecutor.optimize (trimmed)
val candidateFiles = snapshot.filesForScan(partitionPredicate).files
val filesToProcess = filterCandidateFileList(minFileSize, maxDeletedRowsRatio, candidateFiles)
val partitionsToCompact = filesToProcess.groupBy(_.partitionValues).toSeq
val jobs = groupFilesIntoBins(partitionsToCompact) // bins of <= maxFileSize
val batches = optimize.batchSize match { // default: all bins in one batch
case Some(size) => binPackBySize(jobs, size); case None => Seq(jobs) }
batches.map(runOptimizeBatch(_, maxFileSize)) // one commit per batch
- Candidates.
filterCandidateFileListkeeps a file ifsize < optimize.minFileSize(1 GiB), or if its deletion vector hides too much. That means a DV withoutnumRecordsstats, or deleted rows over physical rows aboveoptimize.maxDeletedRowsRatio(0.05).[Delta filterCandidateFileList][Delta DeltaSQLConf: optimize][Delta DeltaSQLConf: maxDeletedRowsRatio] The second rule is how OPTIMIZE purges deleted rows (chapter 13). - Per partition, by size. Files are grouped by partition values, and the default
prepareFilesPerPartitionsorts them by size, smallest first.[Delta OptimizeTableStrategy] - Greedy bins.
groupFilesIntoBinsadds files to the current bin until the next one would exceedmaxBinSize, then starts a new one. For compaction,maxBinSizeisoptimize.maxFileSize, 1 GiB.[Delta CompactionStrategy] Bins of a single file are dropped, because rewriting one file alone changes nothing. REORG is the exception.[Delta groupFilesIntoBins] - One file per bin.
runOptimizeBinJobreads the bin andcoalesce(1)s it, orrepartition(1)ifoptimize.repartition.enabledis set, then writes it withtxn.writeFiles. The old files becomeremoveactions withdataChange = false.[Delta runOptimizeBinJob] Up tooptimize.maxThreads(15) bins run in parallel.
So 200 streaming files of 8 MB (1,600 MB) become two bins: 128 files (1,024 MB) and 72 files (576 MB). The next OPTIMIZE does nothing. The 1,024 MB file is not small, and the 576 MB one would be alone in its bin. Compaction is idempotent and incremental by construction: it only reads small files.
Q1. Which files does a plain OPTIMIZE (compaction) consider, with default settings? (Select all.) (select all that apply)
Q2. A partition has candidate files of 600, 500 and 300 MB, with maxFileSize = 1 GiB. Which bins does OPTIMIZE rewrite?
Why OPTIMIZE commits with dataChange false
The protocol defines the flag: dataChange = false “indicate[s] that an action when combined with other actions in the same atomic version only rearranges existing data or adds new statistics”. On an add, it means the records are contained in remove actions of the same version, and the reverse on a remove.[PROTOCOL.md: add and remove] Three consequences:
- Streaming readers skip it. “Streaming queries that are tailing the transaction log can use this flag to skip actions that would not affect the final results.” A stream reading the table would otherwise see the same rows twice (chapter 35).
- Append-only tables allow it. With
delta.appendOnly, “new log entries may rearrange data (i.e.addandremoveactions wheredataChange=false)”. - Concurrency is narrow.
runOptimizeBatchregisters the compacted files as read. If the commit loses a race,commitAndRetryopens a new transaction and checks thatcandidateSetOld.subsetOf(candidateSetNew). Every compacted file, keyed by path and deletion vector, must still be in the table, and the partition schema must be unchanged. Then it retries on top of the winner.[Delta runOptimizeBatch] A concurrent append passes the check. A DELETE or MERGE that removed a compacted file, or gave it a new DV, fails it, and OPTIMIZE aborts rather than resurrect deleted rows.
With optimize.batchSize set, bins are grouped into batches of that total size, and each batch commits on its own. A long OPTIMIZE then makes progress in steps instead of losing everything to one conflict at the end.
Q1. What does dataChange = false on OPTIMIZE's add and remove actions allow? (Select all.) (select all that apply)
Q2. OPTIMIZE loses a commit race. When does it retry on top of the winner instead of failing?
Write-time fixes
Two features attack small files before or right after they land.
Optimized writes add a shuffle before the write, so each output task gets about a bin’s worth of data for one partition. It exists in open-source Delta as DeltaOptimizedWriterExec, off by default, with a 512 MB bin size (optimizeWrite.binSize).[Delta DeltaOptimizedWriterExec] It costs a shuffle on every write. Chapter 25 covers it.
Auto compaction is a post-commit hook (AutoCompact). It is off unless delta.autoOptimize.autoCompact (or the older delta.autoOptimize) is set on the table, or the session conf overrides it.[Delta AutoCompact.getAutoCompactType] When enabled:[Delta AutoCompact.compact][Delta DeltaSQLConf: autoCompact]
- The target is
autoCompact.maxFileSize, 128 MB, much smaller than OPTIMIZE’s 1 GiB so that the hook stays cheap. “Small” is underautoCompact.minFileSize, which defaults to half the target. - It runs only if a partition the commit wrote to holds at least
autoCompact.minNumFiles(50) small files.modifiedPartitionsOnlyandearlySkipPartitionTableare both on by default.[Delta AutoCompactUtils][Delta DeltaSQLConf: autoCompact modes] - It then runs the same
OptimizeExecutorwith those sizes. The commit is a separate version markedauto = truein its operation.
The hook runs synchronously after the writer’s commit, so the writer’s job takes longer. The tests show the effect: ten 4 MB files per commit trigger compaction at the fifth commit, and the table never holds more than about 50 small files.
Q1. In open-source Delta with defaults, when does auto compaction run?
VACUUM
The protocol keeps physical deletion lazy. “Data files that are no longer present in the latest version of the table can be lazily deleted by the vacuum command after a user-specified retention period (default 7 days).” A remove action carries a timestamp. It “should remain in the state of the table as a tombstone until it has expired”, and it expires when the current time exceeds that timestamp plus the threshold. The delay “allows concurrent readers to continue to execute against a stale snapshot of the data”.[PROTOCOL.md: add and remove] Tombstones exist in the snapshot state “only … for the benefit of the VACUUM command”.[PROTOCOL.md: action reconciliation]
VacuumCommand.gc turns that into a set difference:[Delta VacuumCommand.gc]
// VacuumCommand.gc (trimmed, FULL mode)
val deleteBefore = retentionMillis match {
case Some(ms) => clock.getTimeMillis() - ms // RETAIN n HOURS
case None => snapshot.minFileRetentionTimestamp } // now - deletedFileRetentionDuration
val validFiles = snapshot.stateDS.flatMap { // getValidFilesFromSnapshot
case t: RemoveFile if t.delTimestamp < deleteBefore => Nil // expired tombstone: not protected
case fa: FileAction => relativePaths(fa) // live adds, fresh tombstones, their DVs
}
val listed = listRecursively(dataPath).filterNot(hidden) // skips _delta_log and other hidden dirs
listed.where(modificationTime < deleteBefore || isDir) // files too young are never touched
.groupBy(path).count().join(validFiles, "path", "leftanti").where(count === 1)
-> delete
A file is deleted when three things hold:
- It is in the table directory and not hidden.
- It was last modified before
deleteBefore. - No
addin the current snapshot and no unexpired tombstone names it. Deletion vector files are protected the same way.
Empty directories go too.[Delta getValidFilesFromSnapshot][Delta includeRespectiveDirectoriesWithFilesAndSafetyCheck]
The modification-time rule protects writers in flight. A job that has written files but not yet committed has files that no version references. They are young, so VACUUM leaves them alone. Files of a job that failed days ago are just as unreferenced but old, and VACUUM deletes them. That is the “orphan” cleanup that chapter 10 promised.
Some variants:
DRY RUNreturns the list and deletes nothing.LITEreads the log instead of listing storage. It finds files removed in commits since the last VACUUM, so it cannot find orphans.vacuum.lite.enabledis false by default.[Delta DeltaSQLConf: vacuum]USING INVENTORYtakes the file listing from a table, such as an S3 Inventory report.
The vacuumProtocolCheck feature makes every VACUUM run the writer protocol check, so old implementations cannot delete files of features they do not understand (chapter 12).[PROTOCOL.md: VACUUM Protocol Check]
Q1. Which files does VACUUM delete?
Retention and time travel
Two table properties bound history:
| Property | Default | Bounds |
|---|---|---|
delta.deletedFileRetentionDuration | interval 1 week | how long removed data files survive VACUUM |
delta.logRetentionDuration | interval 30 days | how long commit files survive metadata cleanup (chapter 11) |
The doc comment on the first says it “should be larger than the longest possible duration of a job if you decide to run VACUUM when there are concurrent readers or writers”. A streaming query must not stop for longer than it, “otherwise, the query may not be able to restart as it still needs to read old files”.[Delta DeltaConfig: deletedFileRetentionDuration][Delta DeltaConfig: logRetentionDuration] Delta refuses a log retention shorter than the file retention.[Delta DeltaConfig: retention compatibility] The reverse is allowed and is the default. So the log can describe a version 20 days old whose files VACUUM has already deleted. Time travel is reliable only within the file retention, once VACUUM has run.
- Rewrite commits OPTIMIZE adds larger files and tombstones their inputs.
- Retention window Earlier snapshots may still reference the old files. The files remain in storage.
- VACUUM runs An eligible unreferenced file can be deleted from storage.
VACUUM t RETAIN n HOURS overrides the threshold for one run. checkRetentionPeriodSafety throws if n is shorter than the table’s setting, unless spark.databricks.delta.retentionDurationCheck.enabled is false.[Delta checkRetentionPeriodSafety] Its doc says the check prevents “a very short retention period, which may end up corrupting the Delta Log”.[Delta DeltaSQLConf: retentionDurationCheck] With RETAIN 0 HOURS and the check off, VACUUM deletes every file of every older version at once. A query reading the previous snapshot fails with missing files, and so does a writer whose files are not yet committed. The lab shows both.
To size retention, take the longest of: the time travel window you need, the longest-running query or job, and the longest a stream may be stopped. Then add margin, since deleteBefore is computed from the VACUUM node’s clock.
Q1. What happens on VACUUM t RETAIN 0 HOURS with default settings?
Q2. deletedFileRetentionDuration is 7 days and logRetentionDuration 30 days. After VACUUM, how far back can time travel reliably go?
Iceberg: rewrite, expire, remove orphans
Iceberg splits the same jobs differently, because its metadata is a tree of snapshots (chapter 16) rather than a log with tombstones.
- Rewrite data files. The Java action’s
SizeBasedFileRewritePlannertargetswrite.target-file-size-bytes, 512 MB by default. It picks files under 75% or over 180% of the target, so it also splits oversized files. Candidates are bin-packed into groups of up to 100 GB. The checksenoughInputFiles(at least 5 files,min-input-files),enoughContent(more than a target’s worth) andtooMuchContent(more than the maximum) decide whether a group is worth rewriting.[Iceberg SizeBasedFileRewritePlanner][Iceberg planFileGroups][Iceberg TableProperties] The commit is areplacesnapshot. - Expire snapshots. The spec’s retention policy keeps each branch’s and tag’s referenced snapshot. It then keeps ancestors until a snapshot is both older than
max-snapshot-age-msand not among the firstmin-snapshots-to-keep. Everything else expires. “A file may be deleted from the file system when the snapshot in which it was deleted is garbage collected, assuming that the file is not live in any remaining snapshot”.[Iceberg spec: snapshot retention] The table defaults are 5 days and 1 snapshot.[Iceberg TableProperties: expiry] Expiry deletes the data files it frees, so it does the job of Delta’s tombstone-based VACUUM. - Remove orphan files. A separate action lists storage and deletes files that no metadata references. It deletes only files older than a cutoff, by default “a timestamp 3 days ago”, “to avoid removing files that are being added to the table”.[Iceberg DeleteOrphanFiles]
| Job | Delta | Iceberg |
|---|---|---|
| merge small files | OPTIMIZE (1 GiB), auto compaction (128 MB) | rewrite_data_files (512 MB) |
| drop old versions | metadata cleanup at checkpoints, logRetentionDuration | expire_snapshots, max-snapshot-age-ms |
| delete unreferenced data | VACUUM (tombstones and listing) | expire_snapshots (freed files), remove_orphan_files (listing) |
Q1. Which Iceberg maintenance defaults are right for the Java library at the pinned commit? (Select all.) (select all that apply)
Try it
The lab is one unpartitioned table, with sizes in MB and time in hours. Squares are files in storage, sized by bytes. The table on the right tries to read each version. Things to try:
- Five streaming writes, then OPTIMIZE: 50 files become one. The 50 old files stay in storage as tombstones.
- VACUUM now: nothing goes. Advance 8 days and VACUUM: the old files go, and the early versions become unreadable.
- A failed job, then VACUUM after 8 days: its files go too, though no commit ever named them.
RETAIN 0 HOURS: refused. Untick retentionDurationCheck and run it right after an OPTIMIZE, and the previous version breaks at once.- Tick auto compaction and keep writing: compaction commits appear by themselves.
day 0, 00:00 An empty table. Write some data.
live removed, within 7 days removed, tombstone expired never committed
Summary
- Small files cost per-file metadata, requests and worse encoding. Compaction rewrites them; it does not change which rows are near each other.
- OPTIMIZE takes files under 1 GiB, or with more than 5% deleted rows, groups them by partition, sorts them by size and packs them greedily into 1 GiB bins. It drops single-file bins and writes one file per bin.
- Its actions have
dataChange = false. Streams skip them, append-only tables allow them, and a lost race is retried only if every compacted (path, DV) is still live. - Optimized writes (a pre-write shuffle) and auto compaction (a post-commit hook, 128 MB, 50 small files) are off by default in open-source Delta.
- VACUUM deletes listed files older than now − retention that no live add and no unexpired tombstone references, including orphans of failed jobs. The retention check refuses shorter than 7 days by default.
- Time travel is reliable only within
deletedFileRetentionDurationonce VACUUM runs. Iceberg’s expire_snapshots and remove_orphan_files split the same work.
Concepts in this chapter
Explained here
Primary sources
Review this chapter
This chapter has 10 quiz questions.