≈ The Lake

Part 4 · Delta Lake protocol · Chapter 10

Delta commit and optimistic concurrency

How a Delta transaction turns into exactly one new version, what happens when two writers race for it, and the precise sequence of conflict checks that decides who has to give up.

complete ~75 min

After this chapter you should be able to:
  • State the one storage guarantee the Delta protocol needs, and name how it is provided on HDFS, S3 (three ways) and catalog-managed tables.
  • Walk through a commit from snapshot pinning to put-if-absent, including what the loser does on FileAlreadyExistsException.
  • List the conflict checks in ConflictChecker in order, and predict which exception a given pair of operations produces.
  • Explain Serializable, WriteSerializable and the SnapshotIsolation downgrade in terms of exactly which added files are checked.
  • Use txn actions to make an external writer idempotent, and know what the protocol does and does not guarantee about them.

Every Delta table is a single, serial history of versions 0, 1, 2, and so on. Each version is one file. Concurrency control in Delta is the answer to one question: when several writers each want to create the next version, who gets it, and what must everyone else do? This chapter answers that question all the way down to the order in which ConflictChecker runs its checks.

Where this comes from

Optimistic concurrency control is older than most of the systems in this book. Its premise is that conflicts are rare, so instead of locking up front, a transaction reads freely, does its work in private, and only at the end validates that nothing it depended on changed. If validation fails, it aborts and retries.

  1. 1981-06 On Optimistic Methods for Concurrency Control · H. T. Kung and John T. Robinson, ACM TODS 6(2)
  2. 1995-05 A Critique of ANSI SQL Isolation Levels (defines snapshot isolation and write skew) · Berenson, Bernstein, Gray, Melton, E. O'Neil, P. O'Neil, SIGMOD
  3. 2006-03 Amazon S3 launches (eventually consistent for overwrites and LIST) · AWS
  4. 2017-10 Databricks Delta announced as a proprietary Databricks feature · Databricks
  5. 2019-04 Delta Lake open-sourced at Spark + AI Summit · Databricks, later the Linux Foundation
  6. 2020-08 Delta Lake: High-Performance ACID Table Storage over Cloud Object Stores · Michael Armbrust et al., PVLDB 13(12), VLDB 2020
  7. 2020-12 S3 becomes strongly consistent for all operations, including LIST · AWS
  8. 2022-04 S3DynamoDBLogStore: multi-cluster writes to S3 (Delta Lake 1.2.0) · delta-io
  9. 2024-08 S3 conditional writes: PUT with If-None-Match · AWS
  10. 2024–25 Coordinated commits, then the catalogManaged table feature: a catalog ratifies commits · delta-io, Delta 4.x

Delta is a direct application of the idea. The 2020 paper describes it plainly: writers write data files optimistically, then try to add a log record atomically, and on failure check whether the concurrent commits actually conflict with what they did. The interesting part is entirely in “actually conflict”. That is where most of this chapter goes.

The contract: one file, one version

Start with what the protocol actually promises and requires. Three sentences in PROTOCOL.md carry the whole design.

First, the log is a sequence of numbered files:

Delta files are the unit of atomicity for a table, and are named using the next available version number, zero-padded to 20 digits.[PROTOCOL]

Second, a delta file for version v is a set of actions applied to version v-1. Each line of the file is one JSON action: add, remove, metaData, protocol, txn, commitInfo, domainMetadata, cdc. Replaying them in version order gives the snapshot: the latest protocol and metaData win, the newest action per (path, deletionVector.uniqueId) decides whether a logical file is live or a tombstone.[PROTOCOL]

Third, the single storage requirement:

Writers MUST never overwrite an existing log entry. When ever possible they should use atomic primitives of the underlying filesystem to ensure concurrent writers do not overwrite each other’s entries.[PROTOCOL]

That is all Delta needs from storage: create N.json if and only if it does not exist yet, atomically, so exactly one writer wins each version. Everything else in this chapter is software running on the client.

Here is a real-shaped commit. Note that commitInfo comes first: the Spark writer always puts it there “so we can extract it easily from a commit without having to parse an arbitrarily large file”.[src]

{"commitInfo":{"timestamp":1764196801000,"operation":"UPDATE","readVersion":41,"isolationLevel":"WriteSerializable","isBlindAppend":false}}
{"remove":{"path":"date=2026-11-25/part-00000-3935a07c.c000.snappy.parquet","deletionTimestamp":1764196801000,"dataChange":true}}
{"add":{"path":"date=2026-11-25/part-00000-8d1f2b44.c000.snappy.parquet","partitionValues":{"date":"2026-11-25"},"size":1048576,"modificationTime":1764196800000,"dataChange":true,"stats":"{\"numRecords\":5000,...}"}}

Two fields in commitInfo are not decoration. readVersion is the snapshot the transaction started from, and isBlindAppend changes how other transactions treat this commit when they check for conflicts. Hold on to both.

Quiz The contractAnswers are scheduled for spaced review on the Review page.

Q1. In the Delta protocol, what is the unit of atomicity for a table?

How sure are you?

Q2. What single storage primitive does Delta need to make concurrent writers safe on a path-based (filesystem) table?

How sure are you?

A commit, step by step

A transaction in the Spark connector is an OptimisticTransaction. Its life has five phases: pin a snapshot, read and record the read set, write data files, prepare, and commit. The first four can happen in any number of writers at once without any coordination at all.

The sequence below shows all of it, including the case where another writer gets to the log first. Press Step through to walk it one message at a time.

One commit, with a lost race
Writer AOptimisticTransactionDeltaLogsnapshot stateTable directoryParquet data files_delta_log/through a LogStoreWriter Bsame snapshot v1. startTransaction()2. snapshot v3. filterFiles(predicates)4. PUT part-<uuid>.parquet5. prepare: isBlindAppend, isolation6. PUT v+1.json if absent7. PUT v+1.json if absent8. FileAlreadyExistsException9. read v+1 … latest10. ConflictChecker: checks 1–711. PUT v+2.json if absent12. created: version v+2
  1. startTransaction(). Pin a snapshot. deltaLog.startTransaction() calls update() and captures snapshot v. All reads in the transaction are against this snapshot.
  2. snapshot v. The transaction now has a fixed view of the table: the file set, metadata and protocol at version v.
  3. filterFiles(predicates). Read, and record what was read. txn.filterFiles(predicates) returns the matching AddFiles and records the predicates in readPredicates and the files in readFiles. An operation that looks at everything calls readWholeTable(). A plain INSERT reads nothing. OptimisticTransaction.scala ↗
  4. PUT part-<uuid>.parquet. Write data files. New Parquet files go straight into the table directory under fresh UUID names. No reader can see them: readers only see files that a committed version references.
  5. prepare: isBlindAppend, isolation. commitImpl computes isBlindAppend (only adds, and nothing read) and picks the isolation level for this commit. OptimisticTransaction.scala ↗
  6. PUT v+1.json if absent. Meanwhile Writer B, which pinned the same snapshot v, gets to the log first and creates v+1.json. PROTOCOL.md ↗
  7. PUT v+1.json if absent. Commit. Writer A tries to create v+1.json with put-if-absent. Writers must never overwrite an existing log entry. PROTOCOL.md ↗
  8. FileAlreadyExistsException. Someone else won v+1. The transaction is not aborted: the retry loop sets shouldCheckForConflicts = true and goes round again. doCommitRetryIteratively ↗
  9. read v+1 … latest. checkForConflicts lists the log from the attempted version to the tip and builds a WinningCommitSummary for each winning commit, in order. ConflictChecker.scala ↗
  10. ConflictChecker: checks 1–7. Protocol, metadata, domain metadata, app ids, added files, deleted-read, deleted-deleted, in that order. The first failure throws and the transaction aborts with that exception. ConflictChecker.scala ↗
  11. PUT v+2.json if absent. No conflict. The transaction is rebased onto the winner and tries the next free version, with the same data files.
  12. created: version v+2. Done. Readers that list the log now see v+2, and with it Writer A's files.
Steps 1 to 5 need no coordination; step 7 is the only point where writers contend. Follows OptimisticTransaction at 25561a5.

Step 3 is the one to internalize. The read set is the transaction’s own declaration of what its result depends on. Conflict detection never inspects data. It only intersects the read set with what the winners wrote.

Quiz Commit lifecycleAnswers are scheduled for spaced review on the Review page.

Q1. A writer has written its Parquet files but crashes before writing its delta file. What is the state of the table?

How sure are you?

Q2. When does a Delta transaction fix the snapshot that all of its reads use?

How sure are you?

Q3. What does txn.filterFiles(predicates) record in the transaction, besides returning the matching files? (select all that apply)

How sure are you?

Mutual exclusion on real storage

The put-if-absent requirement looks trivial and was, for years, the hard part on the most popular store. How each storage system provides it is the job of a LogStore implementation in the connector.

StorageHow N.json is created exactly once
HDFS (HDFSLogStore)Write a temp file, then FileContext.rename to N.json, which is atomic and fails if the destination exists.
Azure (AzureLogStore)Same approach: it assumes rename without overwrite is atomic.
Google Cloud Storage (GCSLogStore)“Preconditions are used to handle race conditions”: creating an object that already exists fails, through the gcs-connector.
S3, single cluster (S3SingleDriverLogStore)The fallback. No storage support before 2024. Mutual exclusion only inside one JVM, using an in-process lock. Two clusters writing the same table can silently lose commits.
S3, multi-cluster (S3DynamoDBLogStore)A DynamoDB conditional put claims the version; S3 holds the bytes. Below.
S3 with conditional writes (S3LogStore)PUT with If-None-Match: * fails with 412 Precondition Failed if the key exists. At the pin, DelegatingLogStore picks this store for S3 paths when the S3A filesystem supports conditional create (Hadoop 3.4.2+), and falls back to S3SingleDriverLogStore with a warning otherwise. Chapter 4 walks through it.[src]
Catalog-managed tableThe catalog ratifies version v. Covered in the next section.

The DynamoDB design is worth studying because it shows how to build an atomic, crash-safe commit out of a store that has no atomic create at all. The key trick: separate deciding who owns version N (a tiny conditional write in DynamoDB) from publishing the bytes (an S3 copy that any process can finish).

Step 1/6 · W1

Step 0: does N.json already exist?

W1 wants version 10. fs.exists(00000000000000000010.json) is false, so it continues. (If it were true, W1 would throw FileAlreadyExistsException immediately.)

↳ source

DynamoDB key: (tablePath, fileName)

fileNametempPathcomplete
…9.json.tmp/…9.json.…true (expires now + 1 day)

S3 _delta_log/

  • 00000000000000000009.json

Two details make it correct. The DynamoDB entry names the exact temp file, so “finish the commit” has only one possible outcome, whoever does it. And every writer of version N first checks that N-1 is complete and repairs it if needed, so a crash can never leave a gap. The entry expires after a day rather than immediately; the source comments walk through the data-loss interleaving that a shorter delay would allow on an eventually consistent store.[src]

Quiz StorageAnswers are scheduled for spaced review on the Review page.

Q1. In S3DynamoDBLogStore, at which step does a writer actually win version N?

How sure are you?

Q2. Why does the DynamoDB entry that claims version N in S3DynamoDBLogStore record the exact temp file path?

How sure are you?

Catalog-managed tables: the catalog becomes the arbiter

The newest answer moves the decision out of storage entirely. With the catalogManaged table feature, “the catalog that manages the table becomes the source of truth for whether a given commit attempt succeeded.”[PROTOCOL] A client can stage its commit as _delta_log/_staged_commits/<version>.<uuid>.json, and the catalog ratifies it by atomically recording that this file is version v. Or it sends the commit inline to the catalog. Or, for a catalog that uses put-if-absent itself, it writes the published file directly. The rules the catalog must follow are the same ones you have already seen, restated:

A catalog must not ratify version v until it has ratified version v - 1, and it must ratify version v at most once.[PROTOCOL]

Ratified commits are later published as ordinary N.json files, so the log still ends up in the familiar shape. The difference for you: readers must ask the catalog for recent, possibly unpublished commits, and filesystem-based writers are blocked. This is how Unity Catalog managed tables work, and it is what makes multi-statement and multi-table transactions possible later. Chapter 14 covers it fully.

Quiz Catalog commitsAnswers are scheduled for spaced review on the Review page.

Q1. For a table with the catalogManaged feature, what decides whether a commit for version v succeeded?

How sure are you?

Losing the race and checking for conflicts

Now the core, steps 8 to 10 of the diagram. Writer A tried to create v+1.json and got FileAlreadyExistsException. Here is the relevant part of the retry loop, trimmed:

// OptimisticTransaction.doCommitRetryIteratively (trimmed)
for (attemptNumber <- 0 to maxRetryAttempts) {
  try {
    if (!shouldCheckForConflicts) {
      doCommit(commitVersion, ...)                 // try to write commitVersion.json
    } else {
      val rebase = rebaseCurrentTransactionInfo(commitVersion, ...)  // runs checkForConflicts
      commitVersion = rebase.commitVersion         // next free version
      doCommit(rebase.commitVersion, ...)
    }
    return (commitVersion, postCommitSnapshot, ...)
  } catch {
    case _: FileAlreadyExistsException if readSnapshotTableCommitCoordinatorClientOpt.isEmpty =>
      shouldCheckForConflicts = true               // someone else won; check and retry
    case ex: CommitFailedException if ex.getRetryable && ex.getConflict =>
      shouldCheckForConflicts = true               // same signal from a commit coordinator
  }
}
[src]

The default for maxCommitAttempts is 10,000,000: in practice, retry until a conflict check fails. A transaction is never aborted for losing the race. It is aborted only if the race it lost actually invalidated its work.

What happens after a Delta writer loses a version
  1. Version already taken Read the winning commits in order and check them against the current transaction.
Compatible changes
  1. Rebase Update the transaction and try the next available version.
Conflicting changes
  1. Fail the transaction Report the conflict that invalidated its work.
Several commits may win while a writer is preparing its attempt. The next attempt accounts for every intervening commit.[Delta commit retry]

Conflict checking (checkForConflicts) lists the log from the attempted version to the current tip. There may be several winning commits; each one is checked in order, and the transaction’s info is updated as if it had started at that version. For each winning commit the loser builds a WinningCommitSummary. The important fields:[src]

val metadataUpdates: Seq[Metadata]
val protocol: Option[Protocol]
val appLevelTransactions: Seq[SetTransaction]
val removedFiles: Seq[RemoveFile]
val addedFiles: Seq[AddFile]
val isBlindAppendOption = commitInfo.flatMap(_.isBlindAppend)
val blindAppendAddedFiles  = if (isBlindAppendOption.getOrElse(false)) addedFiles else Seq()
val changedDataAddedFiles  = if (isBlindAppendOption.getOrElse(false)) Seq() else addedFiles

Notice that the winner’s added files are split into two buckets based on the winner’s own isBlindAppend flag. That split is what isolation levels act on.

Quiz The retry loopAnswers are scheduled for spaced review on the Review page.

Q1. In the Spark connector, what exception tells doCommitRetryIteratively that another writer took the version, so it should run conflict checks and try the next version?

How sure are you?

Q2. With default settings, when does a transaction that keeps losing the race give up?

How sure are you?

Q3. Writer A pinned version 10 and tried to create 11.json, but versions 11, 12 and 13 already exist. What does conflict checking do?

How sure are you?

Q4. In WinningCommitSummary, what decides whether the winner's added files go into blindAppendAddedFiles or changedDataAddedFiles?

How sure are you?

The checks, in order

ConflictChecker.checkConflicts is a fixed sequence. The first check that fails throws, and the transaction aborts with that exception.[src]

#MethodFails whenException
1checkProtocolCompatibilityBoth transactions change the protocol; the winner drops a feature; or the winner adds a feature marked failConcurrentTransactionsAtUpgrade. Otherwise the loser adopts the new protocol, if it supports it.ProtocolChangedException
2checkNoMetadataUpdates (or attemptToResolveMetadataConflicts)The winner changed metadata (schema, properties, partitioning). Newer versions can resolve an allow-list of property-only changes.MetadataChangedException
3checkIfDomainMetadataConflictBoth touch the same metadata domain and no feature-specific resolver exists.ConflictingMetadataDomainException
4checkForUpdatedApplicationTransactionIdsThatCurrentTxnDependsOnThe winner wrote a txn for an appId whose version this txn read.ConcurrentTransactionException
–row tracking, type widening reconciliationNot checks: these rewrite the loser’s actions (fresh row IDs, versions) so it can commit on top.–
5checkForAddedFilesThatShouldHaveBeenReadByCurrentTxnThe winner added a file that matches this txn’s read predicates (which adds count depends on isolation level).ConcurrentAppendException
6checkForDeletedFilesAgainstCurrentTxnReadFilesThe winner removed a file this txn read, or removed anything while this txn read the whole table.ConcurrentDeleteReadException
7checkForDeletedFilesAgainstCurrentTxnDeletedFilesBoth remove the same file.ConcurrentDeleteDeleteException
8resolveTimestampOrderingConflictsIn-commit timestamps: bumps this commit’s timestamp to stay monotonic.–

Check 5 is where nearly all real-world conflicts come from, so here it is in full:

protected def checkForAddedFilesThatShouldHaveBeenReadByCurrentTxn(): Unit = {
  val addedFilesToCheckForConflicts = isolationLevel match {
    case WriteSerializable if !currentTransactionInfo.metadataChanged =>
      winningCommitSummary.changedDataAddedFiles // don't conflict with blind appends
    case Serializable | WriteSerializable =>
      winningCommitSummary.changedDataAddedFiles ++ winningCommitSummary.blindAppendAddedFiles
    case SnapshotIsolation =>
      Seq.empty
  }
  val fileMatchingPartitionReadPredicates =
    getFirstFileMatchingPartitionPredicates(addedFilesToCheckForConflicts)
  if (fileMatchingPartitionReadPredicates.nonEmpty) {
    throw DeltaErrors.concurrentAppendException(...)
  }
}
[src]

And the matcher it calls has an early exit you should memorize:

// Blind appends do not read the table.
if (currentTransactionInfo.commitInfo.flatMap(_.isBlindAppend).getOrElse(false)) return None
// There is no reason to filter files if the table is not partitioned.
if (currentTransactionInfo.readWholeTable ||
    currentTransactionInfo.readSnapshot.metadata.partitionColumns.isEmpty) {
  return files.headOption
}
// otherwise: evaluate the partition part of readPredicates against the added files
[src]

So on an unpartitioned table, any non-blind add by the winner conflicts with any reading loser. The open-source checker evaluates only the partition part of the read predicates. It does not look at data predicates or file statistics.

Now run it. Pick two operations, choose who wins the race, and step through. The left panel is the object store; files are colored by writer, dashed while uncommitted, struck through once removed. Click any _delta_log entry to see its JSON.

A
B
A UPDATE t SET v = v + 1 WHERE date='d1'
B DELETE FROM t WHERE date='d1' AND id = 7

Table directory (object store)

  • date=d1/part-000.parquetin table
  • date=d1/part-001.parquetin table
  • date=d2/part-002.parquetin table

_delta_log/

  • CREATE TABLE AS SELECT

Step 1 / 12: Both writers start from version 0

Each transaction calls deltaLog.update() and pins snapshot v0. Writer A plans UPDATE, writer B plans DELETE. Neither knows the other exists: there is no lock and no coordinator.

↳ PROTOCOL.md: Overview (MVCC, two-phase writes)

Things to try:

  • UPDATE d1 vs DELETE d1: the append check fires before the delete-read check, so you get ConcurrentAppendException, not the exception you might expect.
  • Move B to d2: both commit. Partitioning is a concurrency boundary.
  • Switch the table to unpartitioned: the same pair conflicts again, even though the rows could be disjoint.
  • ALTER TABLE as the winner: everyone loses on check 2.
  • Two streaming appends: they are blind appends that touch disjoint partitions, and still the loser fails at check 4.
Quiz Conflict checksAnswers are scheduled for spaced review on the Review page.

Q1. Which check runs first in ConflictChecker.checkConflicts?

How sure are you?

Q2. A partitioned table. Two UPDATE ... WHERE date = 'd1' statements start from the same version. The first commits. With the default isolation level, what does the second one get?

How sure are you?

Q3. ALTER TABLE t ADD COLUMNS (c INT) commits first. A concurrent INSERT into t, started from the same version, then tries to commit. What happens?

How sure are you?

Blind appends

A blind append is a transaction that adds files without having read anything. The definition, from commitImpl:[src]

isBlindAppend = {
  val dependsOnFiles = !readPredicates.isEmpty || !readFiles.isEmpty
  val onlyAddFiles =
    preparedActions.collect { case f: FileAction => f }.forall(_.isInstanceOf[AddFile])
  onlyAddFiles && !dependsOnFiles
}

It matters in both directions:

  • When the loser is a blind append, check 5 is a no-op (it read nothing, so nothing it read can be stale), and checks 6 and 7 cannot fire (it read and removed nothing). A blind append can fail only on protocol, metadata or appId. That is why many concurrent INSERT jobs scale without conflicts.
  • When the winner was a blind append, its added files land in blindAppendAddedFiles, which WriteSerializable ignores. That is the entire difference between the two user-selectable isolation levels.

An INSERT OVERWRITE ... REPLACE WHERE is not a blind append: it reads the partition it replaces in order to remove its files.

Quiz Blind appendsAnswers are scheduled for spaced review on the Review page.

Q1. Which conditions make a transaction a blind append (isBlindAppend = true)? (select all that apply)

How sure are you?

Q2. A blind append loses the race. Which kinds of check can still make it fail?

How sure are you?

Isolation levels

Delta has three isolation levels. You can set two of them on a table with delta.isolationLevel; the third is chosen automatically per commit.[src]

Serializable. The outcome of every commit is consistent with the visible commit order, for reads and writes. In check 5 the loser is compared against all files the winner added.

WriteSerializable (default). Writes are serializable, but not necessarily in commit order. The loser ignores files from blind-append winners. The source’s own example: an UPDATE may commit even if a concurrent INSERT already added data the UPDATE would have read; “it will be as if the UPDATE was executed before the INSERT even if the former was committed after the latter.”

SnapshotIsolation. Not settable on a table. A commit is downgraded to it when it does not change data:[src]

// canDowngradeToSnapshotIsolation (trimmed)
actions.foreach {
  case f: FileAction => if (f.dataChange) dataChanged = true
  case d: DomainMetadata if RowTrackingMetadataDomain.isSameDomain(d) => // ok
  case _ => hasIncompatibleActions = true   // metaData, protocol, txn, ...
}
if (hasIncompatibleActions) return false
defaultIsolationLevel match {
  case Serializable      => !dataChanged
  case WriteSerializable => !dataChanged && !opChangesData
}

OPTIMIZE writes remove and add with dataChange = false, so it runs at SnapshotIsolation and skips check 5 entirely. Concurrent appends can never fail a compaction. A concurrent UPDATE that removes a file OPTIMIZE was compacting still does, via check 6.

Every cell in this matrix is computed by the same engine as the simulator: the row commits first, then the column tries to commit. Click a cell to see the check-by-check reasoning.

winner ↓ · loser →INSERT (blind append)Streaming append (appId=s1)INSERT OVERWRITE / replaceWhereUPDATEDELETEMERGE (no partition filter)OPTIMIZE (compaction)ALTER TABLE ADD COLUMN
INSERT (blind append)
Streaming append (appId=s1)
INSERT OVERWRITE / replaceWhere
UPDATE
DELETE
MERGE (no partition filter)
OPTIMIZE (compaction)
ALTER TABLE ADD COLUMN
Quiz Isolation levelsAnswers are scheduled for spaced review on the Review page.

Q1. Under WriteSerializable (the default), an INSERT commits while a DELETE on the same partition is running. The DELETE then tries to commit. What happens, and why is that allowed?

How sure are you?

Q2. Why does OPTIMIZE (compaction) never fail because of a concurrent INSERT into the partition it is compacting?

How sure are you?

Q3. Can you set delta.isolationLevel = SnapshotIsolation on a table?

How sure are you?

Why partitioning and predicates matter

Since check 5 uses only partition predicates, the practical rules follow directly:

  • Put the partition filter in the statement. MERGE INTO t USING s ON t.id = s.id with no partition condition registers a read predicate of true. Any non-blind add anywhere in the table conflicts with it. Adding a partition literal to the condition (for example AND t.date = '2026-11-25') narrows the read predicate to that partition. A join condition like t.date = s.date alone is not a literal filter on the target, so do not count on it to narrow the read set.
  • Unpartitioned tables serialize all non-blind writers. With copy-on-write and the open-source checker, two UPDATEs on disjoint rows of an unpartitioned table conflict.
  • Operation order changes the exception, not only whether there is one. The same pair can give ConcurrentAppendException one way round and ConcurrentDeleteReadException the other. Don’t build retry logic that matches on just one of them. Catch io.delta.exceptions.DeltaConcurrentModificationException, their common superclass.
Quiz Layout and conflictsAnswers are scheduled for spaced review on the Review page.

Q1. Same two UPDATEs, but the table is unpartitioned and the statements touch completely different rows (id = 1 vs id = 2). Copy-on-write, no deletion vectors. Result for the second writer?

How sure are you?

Q2. Target t is partitioned by date. Which MERGE condition reliably narrows the read predicate to one partition?

How sure are you?

Q3. Your job retries on write conflicts. Which exception should it catch?

How sure are you?

Idempotent writes with transaction identifiers

Optimistic concurrency answers “may I commit?”. It does not answer “did I already commit this?”. After a crash and restart, a streaming sink cannot tell whether its last batch made it into the table. Delta solves that with the txn action, {"txn":{"appId":"…","version":364475}}, committed atomically in the same version as the data.[PROTOCOL]

The Structured Streaming sink uses it like this, as described in the spec:

  1. Record the batch and its monotonically increasing id in the stream’s write-ahead log.
  2. Read txnVersion(appId = queryId) from the table. If it is already ≥ this batch id, the batch is committed: skip it.
  3. Write the data files.
  4. Commit the adds together with txn(appId, batchId).

Step 2 is a read, so the appId goes into readAppIds, and check 4 protects it. Two running copies of the same query cannot both commit the same batch. The protocol is careful about what it does not promise: it “does not, for example, assume monotonicity of the version”; it only guarantees that the latest version for each appId is in the snapshot. Monotonicity is the writer’s convention.

Batch writers can use the same mechanism through the DataFrame writer options txnAppId and txnVersion, which turn an at-least-once job into an exactly-once one.

Quiz IdempotenceAnswers are scheduled for spaced review on the Review page.

Q1. Two copies of the same Structured Streaming query (same checkpoint, so same appId) append to a Delta table. Both are blind appends. What stops duplicate data?

How sure are you?

Q2. Does the Delta protocol require the version in a txn action to increase monotonically for a given appId?

How sure are you?

Q3. Why must a streaming sink commit its txn(appId, batchId) action in the same version as the batch's data files?

How sure are you?

Summary

  • A Delta version is one file. The only thing storage must provide is creating N.json at most once. On S3 that took DynamoDB until conditional writes arrived in 2024, and catalog-managed tables move the decision into the catalog.
  • Writers never lock. They record a read set (readPredicates, readFiles, readAppIds), write data optimistically, and race for the next version.
  • Losing the race only triggers validation. ConflictChecker checks the winner’s protocol, metadata, domains, app ids, added files, removed files, in that order, and the first failure aborts.
  • The isolation level only changes which of the winner’s added files check 5 considers: all of them (Serializable), non-blind ones (WriteSerializable), or none (SnapshotIsolation for no-data-change commits like OPTIMIZE).
  • Partition predicates are the unit of concurrency in the open-source checker. Databricks row-level concurrency refines that for unpartitioned tables with deletion vectors.

Up next, chapter 11: checkpoints, and how a reader gets from _last_checkpoint to a snapshot without replaying a million JSON files.

Concepts in this chapter

Explained here

See how the book's concepts connect →

Primary sources

Review this chapter

This chapter has 32 quiz questions.

Review this chapter's cards → Review all due cards