Part 5 · Apache Iceberg spec · Chapter 17
Iceberg commits and optimistic concurrency
How an Iceberg commit works from the inside: building new metadata, the check-and-put in the catalog, the retry loop that re-applies an operation to a newer snapshot, and the validations that decide whether the retried operation is still correct.
After this chapter you should be able to:
- Walk through a commit from refresh to the catalog swap, naming each file written.
- Explain what a retry rewrites and why sequence-number inheritance makes it cheap.
- Name the validations (new data, new deletes, files exist, required deletes), which operations run each, and which snapshots they look at.
- Explain how Spark maps serializable and snapshot isolation onto those validations.
- Compare Iceberg's commit protocol with Delta's, check by check.
Chapter 16 showed the tree a commit produces. This chapter is about producing it while other writers do the same. Iceberg uses optimistic concurrency, like Delta (chapter 10): writers work without locks, one atomic step decides who wins, and the loser checks whether its change still makes sense on top of the winner’s. The atomic step is different, and so is where the checks run.
Links point to apache/iceberg at 9d2bf51. Spark behavior is from the spark/v4.1 module at the same commit.
Commit: swap the metadata pointer
The spec’s model is short. “An atomic swap of one table metadata file for another provides the basis for serializable isolation.” Readers use the snapshot that was current when they loaded the metadata. Writers “create table metadata files optimistically, assuming that the current version will not be changed before the writer’s commit”, and commit “by swapping the table’s metadata file pointer from the base version to the new version”.[spec]
For a table in a metastore or a REST catalog, the swap is a check-and-put. To commit version V+1, the writer:[spec]
- Creates new table metadata based on the current metadata.
- Writes it to a unique file,
<V+1>-<random-uuid>.metadata.json. - Asks the metastore to swap the pointer from the location of
Vto the location ofV+1. If the swap succeeds,Vwas still current and the commit is done. If it fails, another writer already createdV+1, and this writer goes back to step 1.
The UUID matters. Two writers that started from version 4 both write a file whose name starts with 00005-, and both files exist. Only the one the catalog points at is version 5. The Java client formats the name as %05d-<uuid> from currentVersion() + 1.[src]
BaseMetastoreTableOperations.commit(base, metadata) adds a local guard before calling the catalog-specific doCommit:[src]
public void commit(TableMetadata base, TableMetadata metadata) {
// if the metadata is already out of date, reject it
if (base != current()) {
if (base != null) {
throw new CommitFailedException("Cannot commit: stale table metadata");
} else {
throw new AlreadyExistsException("Table already exists: %s", tableName());
}
}
if (base == metadata) { LOG.info("Nothing to commit."); return; }
doCommit(base, metadata); // the catalog's check-and-put
CatalogUtil.deleteRemovedMetadataFiles(io(), base, metadata);
requestRefresh();
}
The base != current() test only catches staleness this client already knows about. Another process’s commit is caught by doCommit, which each catalog implements with its own atomic operation: for example a conditional update in a database, or a REST catalog’s commit endpoint, whose 409 Conflict the client maps to CommitFailedException (chapter 21).[src] Either way the writer sees CommitFailedException.
The spec also describes an older scheme for file-system tables: write <uuid>.metadata.json, then rename it to v<V+1>.metadata.json. At the pin it is marked deprecated, to be removed in v4, and “unsafe in object stores and local file systems”. It relies on an atomic rename that fails when the target exists, which S3 does not offer (chapter 4).[spec]
Q1. What single step makes an Iceberg commit atomic in a metastore-backed catalog?
Q2. Two writers both build metadata version 5. Why don't their files collide?
Q3. What does the spec at the pin say about committing by renaming a file to v<V+1>.metadata.json?
The retry loop
Every write operation in the Java library (AppendFiles, OverwriteFiles, RowDelta, RewriteFiles, …) is a SnapshotProducer. Its commit() is a retry loop around one body, trimmed here:[src]
Tasks.foreach(ops)
.retry(base.propertyAsInt(COMMIT_NUM_RETRIES, COMMIT_NUM_RETRIES_DEFAULT))
.exponentialBackoff(minWaitMs, maxWaitMs, totalRetryTimeMs, 2.0 /* exponential */)
.onlyRetryOn(CommitFailedException.class)
.run(taskOps -> {
Snapshot newSnapshot = apply();
TableMetadata.Builder update = TableMetadata.buildFrom(base);
update.setBranchSnapshot(newSnapshot, targetBranch);
TableMetadata updated = update.build();
if (updated.changes().isEmpty()) return;
taskOps.commit(base, updated.withUUID());
});
// catch (CommitStateUnknownException e) -> rethrow, no cleanup
// catch (RuntimeException e) -> clean up what was written, rethrow
The defaults are 4 retries, a first wait of 100 ms that doubles up to 60 s, and 30 minutes in total (commit.retry.num-retries, commit.retry.min-wait-ms, commit.retry.max-wait-ms, commit.retry.total-timeout-ms).[src] Only CommitFailedException is retried. Anything else, including a failed validation, ends the commit.
The work happens in apply(), which runs in every attempt, including the first:[src]
public Snapshot apply() {
refresh(); // base = ops.refresh()
Snapshot parentSnapshot = SnapshotUtil.latestSnapshot(base, targetBranch);
long sequenceNumber = base.nextSequenceNumber();
runValidations(parentSnapshot); // the operation's validate(base, parent)
NewSnapshotMetadata result = base.formatVersion() < 4
? writeManifestList(parentSnapshot, sequenceNumber)
: writeRootManifest(base, parentSnapshot, sequenceNumber);
...
return new BaseSnapshot(sequenceNumber, snapshotId(), parentSnapshot.snapshotId(), ...);
}
So the order inside one attempt is: refresh, take the next sequence number, validate against the refreshed state, write a new manifest list, build new metadata, swap. On the first attempt the refreshed state is usually the state the operation was planned against, so the validations have nothing to look at. After a lost swap, the refresh brings in the winner’s snapshot and the same validations now have something to check.
What a retry rewrites is small. The snapshot id is chosen once and kept across attempts.[src] Manifests for new data files are cached and reused, unless files were added after they were written.[src] This works because of sequence-number inheritance (chapter 16). New entries are written with a null sequence number, and the spec reassigns the number on retry: “If the commit fails and must be retried, the sequence number is reassigned and written into new snapshot metadata.” Inheritance “allows writing a new manifest once and reusing it in commit retries. To change a sequence number for a retry, only the manifest list must be rewritten”.[spec] The manifest list’s name includes the attempt number: snap-<snapshotId>-<attempt>-<commitUUID>.avro.[src]
Deletes are re-applied rather than reused. MergingSnapshotProducer.apply(base, snapshot) runs the delete filter over the new base’s manifests on each attempt, so if the winner rewrote a manifest, the loser filters the rewritten one.[src]
- load table → v.metadata.json. The writer reads the current metadata location and loads it. Its scan pins the current snapshot; Spark later passes that snapshot id to validateFromSnapshot. Optimistic Concurrency ↗
- PUT data files + new manifests. Data files and the manifests that list them are written once. Entries carry null sequence numbers, so the same manifests can be reused in every retry. newDataFilesAsManifests ↗
- apply(): refresh, seq = last + 1, validate. Each attempt refreshes the base, takes the next sequence number and runs the operation's validations against snapshots committed after the starting snapshot. SnapshotProducer.apply ↗
- PUT snap-<id>-<attempt>-<uuid>.avro, v+1-<uuid>.metadata.json. A new manifest list per attempt: it carries the optimistic sequence number for the new manifests. Then the new table metadata, built from the base with the new snapshot set as current. manifestListPath ↗
- swap v → v+1 (B got there first). Writer B, which started from the same base, swaps first. Its snapshot is now current.
- swap v → v+1, if still v. Check-and-put: the catalog compares the expected current location with the real one. It no longer matches. Metastore Tables ↗
- CommitFailedException. The only exception the retry loop retries on. It waits (100 ms at first, doubling, capped at 60 s, 4 retries and 30 min in total by default) and runs the loop body again. SnapshotProducer.commit ↗
- apply() again on base v+1. Refresh to v+1, take sequence number + 1, and re-run the validations: now validationHistory finds B's snapshot. A ValidationException ends the commit; it is not retried. validationHistory ↗
- PUT new manifest list + v+2 metadata. Only the manifest list and table metadata are rewritten. Deletes are re-applied to the new base's manifests, so a manifest B rewrote is filtered again.
- swap v+1 → v+2. The swap succeeds. If the response is lost (a timeout), the client cannot know; it checks whether its metadata location became current or entered the metadata log, and otherwise throws CommitStateUnknownException without cleaning up. checkCommitStatus ↗
Q1. Which exception makes SnapshotProducer.commit retry?
Q2. With default table properties, how many times does a commit retry after the first attempt fails?
Q3. When do an Iceberg operation's validations run?
Q4. A commit loses the swap and retries successfully. Which files does the retry write again? (select all that apply)
Q5. The table's last sequence number is 2. Writer A commits; writer B lost the race and retries. What sequence number does B's snapshot get?
What a retry re-checks
The spec states the rules by kind of change:[spec]
- “Append operations have no requirements and can always be applied.”
- “Replace operations must verify that the files that will be deleted are still in the table.” Compaction is the example.
- “Delete operations must verify that specific files to delete are still in the table. Delete operations based on expressions can always be applied.”
- “Table schema updates and partition spec changes must validate that the schema has not changed between the base version and the current version.”
- In v4, constraints add their own retry rules.
It also says the isolation level is a writer’s choice: “The conditions required by a write to successfully commit determines the isolation level. Writers can select what to validate and can make different isolation guarantees.”[spec] The Java library turns that into a set of building blocks in MergingSnapshotProducer that operations switch on.
- Refresh after the swap fails Load the new current snapshot and reapply the operation against it.
- Add the new files An append has no file-removal precondition.
- Validate the input files Every file being replaced must still be in the table.
The window: validationHistory
Every check looks only at snapshots committed after the operation’s starting snapshot, set with validateFromSnapshot(id). validationHistory walks ancestors from the current snapshot back to the starting one, keeps snapshots whose operation is in the check’s set, and collects only the manifests each of those snapshots wrote (manifest.snapshotId() == snapshot.snapshotId()). It then checks that the walk really reached the starting snapshot, so a check cannot silently skip history.[src]
for (Snapshot currentSnapshot : ancestorsBetween(parent.snapshotId(), startingSnapshotId, base::snapshot)) {
lastSnapshot = currentSnapshot;
if (matchingOperations.contains(currentSnapshot.operation())) {
newSnapshots.add(currentSnapshot.snapshotId());
for (ManifestFile manifest : currentSnapshot.dataManifests(io)) // or deleteManifests
if (manifest.snapshotId() == currentSnapshot.snapshotId()) manifests.add(manifest);
}
}
ValidationException.check(lastSnapshot == null || Objects.equals(lastSnapshot.parentId(), startingSnapshotId),
"Cannot determine history between starting snapshot %s and the last known ancestor %s", ...);
Without a starting snapshot the walk covers the whole branch, which is why Spark always passes the scan’s snapshot id.[src] The operation sets are constants:[src]
| Check looks for | Snapshots with operation |
|---|---|
| new data files | append, overwrite |
| removed data files | overwrite, replace, delete (or only overwrite, replace when deletes are skipped) |
| new delete files | overwrite, delete |
A replace snapshot is absent from the first row on purpose: compaction adds files whose rows were already in the table.
The checks
Each check builds a ManifestGroup over the window’s manifests and throws ValidationException if any entry survives. A check that takes a filter uses filterData, the same partition projection and column-metrics pruning as scan planning (chapter 16). So a conflict filter day = 'd1' AND id = 7 is tested against each new file’s id bounds, not only its partition.
validateAddedDataFiles(filter): no ADDED data file in an append or overwrite snapshot can match the filter. Message: “Found conflicting files that can contain records matching …”.[src]validateNoNewDeletesForDataFiles(files): no delete file added since the start applies to a file this operation removes. It indexes the new delete files and asks, per data file, for deletes with a sequence number above the starting snapshot’s. Message: “Cannot commit, found new delete for replaced data file”.[src]validateNoNewDeleteFiles(filter): no new delete file at all matches the filter. Message: “Found new conflicting delete files that can apply to records matching …”.[src]validateDataFilesExist(paths): no file this operation’s delete files point at was removed since the start. Message: “Cannot commit, missing data files”.[src]- Required deletes: an operation that calls
failMissingDeletePaths()fails if a file it deletes is not found while filtering the current manifests. Message: “Missing required files to delete”. This is the spec’s “files that will be deleted are still in the table”, and it runs whileapplywrites the new manifests, aftervalidate.[src] validateAddedDVs: in v3, no other deletion vector was added for the same data file. A data file can have at most one DV, so two concurrent DV deletes of the same file conflict here.[src]
Which operation runs which
OverwriteFiles(copy-on-write DELETE, UPDATE and MERGE;INSERT OVERWRITE).validateNoConflictingData()turns on the new-data check with the conflict filter.validateNoConflictingDeletes()turns on the new-delete checks for the removed files. Both also turn on required deletes.[src]RowDelta(merge-on-read). It checks that the starting snapshot is an ancestor. ThenvalidateDataFilesExistfor the files its delete files reference, skippingdeletesnapshots unlessvalidateDeletedFiles()was called. Then the new-data check ifvalidateNoConflictingDataFiles()was called, the new-delete-files check ifvalidateNoConflictingDeleteFiles()was called, and the DV check.[src]RewriteFiles(compaction). Required deletes are always on, set in the constructor.validateadds the new-deletes-for-replaced-files check.[src][src] Spark’srewrite_data_filescommits withvalidateFromSnapshot(startingSnapshotId), and by default sets the new files’ data sequence number to the starting snapshot’s, so equality deletes committed during the rewrite still apply to the compacted rows.[src]AppendFileshas no validation.
The operation a snapshot records comes from what it did. OverwriteFiles is delete if it only removes data files, append if it only adds, otherwise overwrite.[src] RowDelta is append if it only adds data, delete if it only adds delete files, otherwise overwrite.[src] Since the windows filter on operation, this decides which later checks see a snapshot.
Schema changes take a different path. SchemaUpdate.commit() builds new metadata from its base and calls ops.commit(base, update) once, with no retry loop of its own, so a concurrent commit surfaces as CommitFailedException.[src]
Q1. Which snapshots does validationHistory look at?
Q2. An OverwriteFiles turns on validateNoConflictingData() but never calls validateFromSnapshot. What history do its checks cover?
Q3. What must an append verify before it is re-applied to a newer snapshot?
Q4. validateAddedDataFiles looks for new data files in snapshots with which operations?
Q5. Compaction of day d1 commits first. A merge-on-read DELETE that wrote a position delete file for f-000 (now compacted away) retries. What happens?
Q6. A merge-on-read DELETE commits a position delete for f-000. Compaction, which read f-000 before that, retries. Why must it fail?
Isolation levels in Spark
Iceberg’s Spark integration has two levels, serializable and snapshot, set per command with write.delete.isolation-level, write.update.isolation-level and write.merge.isolation-level. All three default to serializable. The row-level commands default to copy-on-write (write.delete.mode and friends).[src]
For copy-on-write, SparkWrite.CopyOnWriteOperation builds an OverwriteFiles that deletes every scanned file and adds the rewritten ones. Then it configures validation:[src]
// commitWithSerializableIsolation
overwriteFiles.validateFromSnapshot(scan.snapshotId());
overwriteFiles.conflictDetectionFilter(scan.filter());
overwriteFiles.validateNoConflictingData();
overwriteFiles.validateNoConflictingDeletes();
// commitWithSnapshotIsolation: the same, without validateNoConflictingData()
For merge-on-read, SparkPositionDeltaWrite builds a RowDelta:[src]
rowDelta.conflictDetectionFilter(scan.filter());
rowDelta.validateDataFilesExist(referencedDataFiles);
rowDelta.validateFromSnapshot(scan.snapshotId());
if (command == UPDATE || command == MERGE) {
rowDelta.validateDeletedFiles();
rowDelta.validateNoConflictingDeleteFiles();
}
if (isolationLevel == SERIALIZABLE) {
rowDelta.validateNoConflictingDataFiles();
}
So the only difference between the levels is the new-data check. Under serializable, a DELETE fails if a concurrent commit added data that its scan would have read. Under snapshot, it commits, and the concurrently added rows are not deleted. The conflict filter is the scan’s pushed-down filter, which is why the predicate’s selectivity matters as much as the partitioning.
Q1. What is the default write.delete.isolation-level (and update, merge) for Iceberg tables?
Q2. For a copy-on-write DELETE, what does Spark turn off when the isolation level is snapshot instead of serializable?
Q3. Serializable copy-on-write DELETE … WHERE day = 'd1' AND id = 7. A concurrent INSERT adds a d1 file with id bounds [100, 110]. What happens to the DELETE's retry?
Try it: two writers
The simulator runs the algorithm above in src/sim/iceberg/commit.ts, with the same layout as the Delta simulator in chapter 10. The table is format v2, partitioned by day, with one data column id. Snapshot 1 added two d1 files (ids 1–10 and 11–20) and snapshot 2 two d2 files. Both writers plan against snapshot 2. Each runs the attempt body; the winner swaps first; the loser’s swap fails, and its second attempt re-validates against the winner’s snapshot. Try:
- INSERT ids 5–9 then DELETE id = 7 (copy-on-write) in d1, at serializable: the new file can hold id 7, so the DELETE fails. Switch to snapshot isolation: it commits.
- INSERT ids 100–110 then the same DELETE: it commits even at serializable, because the new file’s id bounds rule out
id = 7. - rewrite_data_files then DELETE id = 7 (merge-on-read): the position delete points at a file compaction removed.
- The same pair the other way round: compaction would drop a delete it never saw.
INSERT INTO t VALUES … -- day 'd1', ids 5–9DELETE FROM t WHERE day = 'd1' AND id = 7Catalog (one pointer)
- db.t → 00002-base.metadata.json
metadata/
- 00002-base.metadata.jsoncurrent
Snapshots (in current metadata)
- 1 seq 1 · append
- 2 seq 2 · append · parent 1
Data and delete files
- f-000.parquetid [1, 10]live
- f-001.parquetid [11, 20]live
- f-002.parquetid [1, 10]live
- f-003.parquetid [11, 20]live
Step 1 / 9: Both writers load the table
Each asks the catalog for the table and gets the same metadata location, 00002-base.metadata.json. Both read current-snapshot-id 2 (sequence number 2) and plan against it. A plans AppendFiles, B plans OverwriteFiles. There is no lock.
Every pair of operations
Each cell is computed by the same engine: the row commits first, then the column retries. The labels name the check that failed: new data (validateAddedDataFiles), missing (required deletes), gone (validateDataFilesExist), new delete (validateNoNewDeletesForDataFiles), new deletes (validateNoNewDeleteFiles).
| winner ↓ · loser → | INSERT ids 5–9 | INSERT ids 100–110 | DELETE id = 7 (copy-on-write) | UPDATE id = 7 (copy-on-write) | DELETE id = 7 (merge-on-read) | UPDATE id = 7 (merge-on-read) | rewrite_data_files (compaction) |
|---|---|---|---|---|---|---|---|
| INSERT ids 5–9 | |||||||
| INSERT ids 100–110 | |||||||
| DELETE id = 7 (copy-on-write) | |||||||
| UPDATE id = 7 (copy-on-write) | |||||||
| DELETE id = 7 (merge-on-read) | |||||||
| UPDATE id = 7 (merge-on-read) | |||||||
| rewrite_data_files (compaction) |
rewrite_data_files (compaction) commits first, then DELETE id = 7 (merge-on-read) retries: ValidationException: Cannot commit, missing data files: [f-000.parquet]
validateDataFilesExistA replace snapshot removed f-000.parquet, which this operation's delete file points at. The delete would apply to nothing.validateAddedDataFilesNot reached: an earlier check threw ValidationException.validateAddedDVsNot reached: an earlier check threw ValidationException.
Some cells are worth reading closely:
- Appends never fail, as either winner or loser, and compaction never fails because of an append.
- Two merge-on-read DELETEs of the same file both commit in v2. Each adds a position delete file, and both apply. Two merge-on-read UPDATEs conflict, because each also writes the new version of the rows (
validateNoNewDeleteFiles). In v3 with deletion vectors, the two DELETEs conflict too, invalidateAddedDVs. - Copy-on-write after compaction fails on the missing file, not on new data, because a
replacesnapshot is not in the new-data window. - Snapshot isolation does not remove file-level conflicts. If both writers rewrite or remove the same file, the required-deletes and files-exist checks still fail.
When the outcome is unknown
A swap can fail in a way that hides the outcome: the request times out after the catalog applied it. Retrying could commit twice; cleaning up could delete files of a commit that succeeded. Catalog implementations call checkCommitStatus, which reloads the table and looks for the new metadata location as the current one or in the metadata log. If it cannot confirm either way, the status is UNKNOWN and the client throws CommitStateUnknownException.[src] The REST client goes straight to the same exception when a commit request returns 500, 502, 503 or 504.[src] SnapshotProducer.commit rethrows it without cleaning up.[src]
For other failures, cleanup is complete. The producer deletes the manifests and manifest lists it wrote. In Spark, ValidationException and CommitFailedException are CleanableFailures, so the job abort also deletes the data files the tasks wrote; after CommitStateUnknownException it logs “Skipping cleanup of written files”.[src]
Q1. The catalog request for the swap times out. What can the client do?
Q2. A Spark write fails with ValidationException. What happens to its data files?
Comparison with Delta
| Delta (chapter 10) | Iceberg | |
|---|---|---|
| Atomic step | Create _delta_log/<v>.json if absent (or a catalog commit, chapter 14) | Catalog check-and-put of the metadata location |
| What the loser writes again | The same actions, at the next version | A new manifest list and metadata file; data files and new manifests are reused |
| When checks run | Only after losing, against the winning commits[src] | In every attempt, inside apply(), against snapshots since the starting snapshot |
| What “what I read” means | Read predicates, matched to new files by partition values; the read file set[src] | A conflict filter, matched by partition values and column bounds; the files removed or referenced |
| Default level for UPDATE and DELETE | WriteSerializable: concurrent blind appends are not checked | serializable: concurrent appends are checked against the filter |
| Weaker level | SnapshotIsolation, chosen automatically for commits that change no data | snapshot, chosen per table and command |
| Loser’s data files | Left in storage; VACUUM removes them later | Deleted by Spark’s abort on a cleanable failure |
The checks line up closely. Delta’s checkForAddedFilesThatShouldHaveBeenReadByCurrentTxn is Iceberg’s validateAddedDataFiles. checkForDeletedFilesAgainstCurrentTxnReadFiles corresponds to required deletes and validateDataFilesExist. Delta has no counterpart to the delete-file checks because a Delta DV is attached to the add action of its file, so changing a DV removes and re-adds that file, and the file-level checks cover it (chapter 13). The main difference in shape is that Iceberg checks against a filter and stats where Delta checks against partition values, so Iceberg can accept an append into the same partition that Delta’s Serializable level would reject.
Q1. Which statements about Delta and Iceberg commits are true? (select all that apply)
History
Optimistic concurrency control comes from H. T. Kung and John T. Robinson, “On Optimistic Methods for Concurrency Control”, ACM Transactions on Database Systems 6(2), 1981. Transactions run in three phases: a read phase on private copies, a validation phase that checks for conflicts with transactions that committed meanwhile, and a write phase that makes the changes visible.[doi] Iceberg follows the pattern with one twist: validation and the write phase’s preparation run again on every attempt, and the write phase itself is one pointer swap.
Q1. Kung and Robinson's optimistic concurrency control (ACM TODS, 1981) splits a transaction into which phases?
Concepts in this chapter
Explained here
Primary sources
Review this chapter
This chapter has 21 quiz questions.