Delta commits, conflicts and checkpoints

Part of the free LogicWiz Data Engineering course, Module 13: The lakehouse on Databricks. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 2:00 a.m. The nightly MERGE into silver.orders fails with ConcurrentAppendException: a backfill someone started by hand committed first. The retry fails the same way. Yet a plain INSERT job that writes the same table has never failed once. At 8:00 Nora asks: "Same table, same night. Why does one writer keep losing and the other never does?"

You'll learn to

  • Walk through a Delta commit: read, write, create the next log file
  • Predict which concurrent writes conflict, and name the error
  • Explain how deletion vectors narrow conflicts to rows, and their cost
  • Explain how checkpoints keep a long log quick to read

Learn

Nobody takes a lock

When two jobs write one table, a database would normally make one of them wait for a lock. A Delta table is files in object storage. There is no lock to take.

So every Delta write is an optimistic transaction: go ahead as if you were alone, and check at the very end. Three steps:

  1. Read. Take the latest snapshot, the table as it stands at version v, and note which files you read.
  2. Write. Write new Parquet files. Nobody can see them yet.
  3. Commit. Create the log file for version v+1, but only if it does not exist yet.

Think of two people reaching for the same numbered ticket. Only one gets ticket 8. The other looks at what the winner did and, if nothing clashes, takes ticket 9.

Two writers race for version 8

A sequence between an INSERT job, the _delta_log and a MERGE job: both read version 7 and write files; the INSERT creates version 8 first; the MERGE finds 8 taken, reads it, sees a blind append, and commits as version 9.

  1. Both read version 7. Each job takes the latest snapshot. The MERGE also notes the files it read: f1 to f4.

  2. Both write files. The INSERT writes one new file. The MERGE rewrites f2 as a new file. Neither is in the log yet, so no reader sees them.

  3. The INSERT asks for version 8 first. 00008.json does not exist, so it is created. The INSERT has committed.

  4. The MERGE asks for version 8 too. The file is already there, and a log file is never overwritten. The MERGE has lost the race.

  5. The MERGE reads commit 8. It only added a file and read nothing. Such a write is called a blind append. Nothing the MERGE read was touched, so it takes the next number, 9, without redoing its work.

Time runs downwards, and each step adds lines at the bottom. The MERGE lands as version 9, but its commitInfo records readVersion: 7. That is how DESCRIBE HISTORY shows who raced whom.

Two races on one table

import minidelta

t = minidelta.DeltaTable('lake/orders')
t.write("SELECT * FROM 'data/orders.csv' WHERE order_id <= 1040")    # version 0
t.write("SELECT * FROM 'data/orders.csv' WHERE order_id > 1040")     # version 1

a, b = t.begin(), t.begin()            # both read version 1
a.write("SELECT * FROM 'data/orders.csv' WHERE order_id = 1001")
b.write("SELECT * FROM 'data/orders.csv' WHERE order_id = 1002")
print('A committed', a.commit(), '| B committed', b.commit())

c, d = t.begin(), t.begin()            # both read version 3
c.delete("status = 'cancelled'")
d.delete("customer_id = 7")
print('C committed', c.commit())
try:
    d.commit()
except minidelta.DeltaConcurrentModificationException as e:
    print(type(e).__name__ + ':', e)
for h in t.history()[:3]:
    print(h['version'], h['operation'], 'readVersion', h['readVersion'], 'isBlindAppend', h['isBlindAppend'])

begin() opens a transaction on the latest snapshot. Staging an operation writes its files, and commit() races for the next number. The two appends both win. The second DELETE loses, with the same error as last night. The next two sections say why.

What the loser checks

The loser of a race does not give up at once. It opens every commit that beat it and asks one question after another: did you change something I relied on?

There are six questions, always in the same order. The first yes ends the transaction with an error, and each question has its own error name. Those names are what you find in a failed job's log at 2:00 a.m., so it pays to know which question each one answers.

Six questions, in this order

Seven steps from top to bottom: the six checks a losing writer runs against each winning commit, each with the exception it raises, from protocol change to deleting the same file twice, and then the commit if every answer is no.

Read it top to bottom: the checker stops at the first yes. Questions 1 to 3 are about the table and the writer, questions 4 to 6 about data files.

Why the MERGE lost, never the INSERT

Look at question 4 again: did the winner add files my read should have seen?

The INSERT job never reads the table. It only adds a file. With nothing read and nothing removed, questions 4 to 6 cannot catch it. That is why it has never failed.

The MERGE read the whole table. At 2:00 the backfill, a DELETE, won the race. A DELETE is no blind append: it rewrote a file, and the rewritten file is data the MERGE never read. On a table without partitions, any file added by a commit that was not a blind append counts. So question 4 says yes: ConcurrentAppendException.

For the same reason, two MERGEs on one unpartitioned table usually fail each other.

2:00 a.m., step by step

A sequence between a backfill DELETE, the _delta_log and the nightly MERGE: both read version 40; the DELETE rewrites a file and commits 41; the MERGE finds 41 taken, sees added data it never read and throws ConcurrentAppendException; the job retries from a fresh snapshot and commits 42.

  1. Both read version 40. The backfill is a DELETE for one old day. The nightly MERGE reads the whole table.

  2. The backfill commits first. Its DELETE rewrote a file, so commit 41 removes f7 and adds a new file, part-0300.

  3. The MERGE asks for version 41. It exists. The MERGE opens it and finds an added file it never read. Question 4 says yes, and the MERGE throws its work away.

  4. The right retry. A new transaction reads version 41 and does the whole MERGE again. With no rival this time, it commits as version 42.

A retry must start a new transaction: read the snapshot again and redo the work. Committing the old staged files again would fail the same check every time. Last night the retry lost for a second reason: the backfill was still running and won the next race too.

Remember: a writer loses when a winner changed data it read. A plain INSERT read nothing, so another job's data never makes it lose.

Two levels of strictness

How strict question 4 is depends on the table's isolation level. There are two.

WriteSerializable is the default. A blind append by the winner is let through: your MERGE may commit although the INSERT's rows were not in the snapshot it read. The writes can still be put in one sensible order, but that order may differ from the order in the table's history.

Serializable is stricter. Any file added since your read counts, so the same MERGE fails with ConcurrentAppendException and has to run again. You set it per table: ALTER TABLE ... SET TBLPROPERTIES ('delta.isolationLevel' = 'Serializable').

In both, the one that fails is the operation that read the data, never the INSERT. So put the retries on the MERGE, UPDATE or DELETE.

Which pairs can conflict

PairWriteSerializableSerializableWith row-level concurrency
INSERT + INSERTnonono
INSERT + UPDATE/DELETE/MERGEnoyes: the DML failsno; Serializable: same row only
INSERT + OPTIMIZEnonono
UPDATE/DELETE/MERGE + the sameyesyesonly on the same row
UPDATE/DELETE/MERGE + OPTIMIZEyes; with deletion vectors only with ZORDER BYas WriteSerializableonly with ZORDER BY
OPTIMIZE + OPTIMIZEyes; with deletion vectors only with ZORDER BYas WriteSerializableonly with ZORDER BY

From the Databricks documentation. Read the first two columns now; the last one is explained two sections down. DML is short for UPDATE, DELETE and MERGE. "Yes" means can conflict: only when the two touch the same files, which partitioning by the columns in their conditions makes rare. A metadata change (ALTER TABLE, a schema-evolving write) can fail any concurrent write, INSERT included.

Race every pair

import minidelta

OPS = {
    'INSERT': lambda x: x.write("SELECT * FROM 'data/orders.csv' WHERE order_id = 1001"),
    'DELETE': lambda x: x.delete("status = 'cancelled'"),
    'OPTIMIZE': lambda x: x.optimize(),
    'ALTER': lambda x: x.set_properties({'delta.appendOnly': 'false'}),
}

def race(first, second, isolation):
    """Two transactions on one snapshot: the first commits, then the second tries."""
    t = minidelta.DeltaTable(f'lake/{first}_{second}_{isolation}')
    t.write("SELECT * FROM 'data/orders.csv' WHERE order_id <= 1040")    # version 0
    t.write("SELECT * FROM 'data/orders.csv' WHERE order_id > 1040")     # version 1
    a, b = t.begin(), t.begin(isolation)
    OPS[first](a)
    OPS[second](b)
    a.commit()
    try:
        b.commit()
        return 'commits'
    except minidelta.DeltaConcurrentModificationException as e:
        return type(e).__name__

for first, second in [('INSERT', 'INSERT'), ('INSERT', 'DELETE'), ('DELETE', 'INSERT'),
                      ('DELETE', 'DELETE'), ('OPTIMIZE', 'DELETE'), ('OPTIMIZE', 'OPTIMIZE'),
                      ('ALTER', 'INSERT')]:
    print(f'{first} won, {second}:', race(first, second, 'WriteSerializable'), '/', race(first, second, 'Serializable'))

Each line shows WriteSerializable, then Serializable. Find the one line where the two differ. OPTIMIZE is not a blind append, so on an unpartitioned table its compacted file counts as data the losing DELETE never read, and the check stops there. Two compactions of the same files read no rows and fail on deleting a file twice. With deletion vectors, Databricks would let OPTIMIZE without ZORDER BY and the DELETE both commit.

The trap: retrying the wrong thing, the wrong way. Retry the MERGE, UPDATE or DELETE that lost, from a new transaction, with backoff and a limit. Never retry by committing old work again. ConcurrentTransactionException is not a retry case at all: it means two instances of one stream write with the same checkpoint, so stop one. And schedule ALTER TABLE and schema-evolving writes away from busy hours: one metaData action fails every concurrent writer.

From the same file to the same row

So far a conflict has meant: we touched the same file. Databricks can narrow that to: we touched the same row.

The tool is the deletion vector from Lesson 13.3. To delete or update rows, a writer does not rewrite the file. It stores the positions of the dead rows in a small bitmap, and commits a remove plus an add of the same file path with the bitmap attached. Two writers can then mark different rows of one file without clashing.

This is row-level concurrency: two MERGEs, UPDATEs or DELETEs conflict only when they change the same row. On Runtime 14.3 LTS and above it is on automatically for unpartitioned tables with deletion vectors. Partitioned tables do not get it.

A 1,000,000-row file with 30% of its rows soft-deleted

Two bars on one scale: before compaction a reader decodes 700 thousand live rows and 300 thousand rows marked deleted; after OPTIMIZE or REORG the file holds only the 700 thousand live rows.

The top bar is the file as a reader meets it today, the bottom bar the same file after a rewrite. Today every scan decodes 1,000 / 700 = 1.43 rows for each row it returns. The write saved a rewrite; every read pays until a compaction does it.

Readers pay for a soft delete

Look at the red block. Those 300,000 rows are still in the file, so every reader decodes them and throws them away.

The rows leave the file only when it is rewritten: by OPTIMIZE, by auto compaction, or by REORG TABLE ... APPLY (PURGE), which rewrites every file that has a deletion vector.

Even then, the old file still holds the deleted rows until VACUUM removes it. That matters when a deletion is a legal duty, such as a customer's erasure request: purge first, then vacuum.

Remember: a deletion vector makes the write cheap and every read a little dearer, until a rewrite clears it.

A bookmark in the log

One more thing keeps this table usable at 2:00 a.m.: the log has to stay quick to read. A busy table makes hundreds of commits a day, and replaying thousands of JSON files on every read would be slow.

So now and then Delta writes a checkpoint: one Parquet file with the whole state of the table at one version. Think of a bookmark that comes with a summary of the story so far.

A tiny file, _last_checkpoint, points at the newest one. A reader that comes to the table fresh, a cold reader, opens that checkpoint, then replays only the commits after it. Open-source Delta writes a checkpoint every 10 commits.

Inside a table folder after 12 commits

A folder tree: the table folder holds Parquet data files, a deletion vector file, the _change_data folder and _delta_log, which holds JSON commits 0 to 12, a checkpoint at version 10, a checksum file, an optional log compaction file and the _last_checkpoint pointer.

Follow the four teal lines: the pointer, the checkpoint it names, then commits 11 and 12. Everything else in _delta_log stays closed. The checkpoint holds the protocol, the metaData, every live add, the remove markers VACUUM still needs and the txn entries, but no commitInfo, which is why 00000000000000000010.json is kept beside it.

A checkpoint every 10 commits

import duckdb
import minidelta

t = minidelta.DeltaTable('lake/events', checkpoint_interval=10)
for i in range(13):
    t.write(f"SELECT * FROM 'data/orders.csv' WHERE order_id = {1001 + i}")
print([n.split('/')[-1] for n in t.ls() if n.startswith('_delta_log') and not n.endswith('.json')])
print(open('lake/events/_delta_log/_last_checkpoint').read())
print(duckdb.sql("""SELECT kind, COUNT(*) FROM 'lake/events/_delta_log/00000000000000000010.checkpoint.parquet'
                    GROUP BY kind ORDER BY kind""").fetchall())
print('to rebuild version 12:', t.log_files_for(12))
print('to rebuild version 7:', len(t.log_files_for(7)), 'JSON commits')

Thirteen appends are versions 0 to 12. The checkpoint at 10 holds the protocol, the metaData and 11 adds; version 12 then needs one Parquet file and two JSON commits, while version 7, older than the checkpoint, still replays from version 0. minidelta stores each action as JSON text; real checkpoints use typed columns.

Why big tables open slowly

Two limits follow from checkpoints.

History ends at the log retention. After a checkpoint, Delta deletes log files older than delta.logRetentionDuration (30 days). It keeps the newest checkpoint before the cut-off, so the table can still be rebuilt. History and time travel end there, whatever VACUUM did.

A checkpoint grows with the table's files. A reader pays for the commits after the checkpoint (at most 9 with an interval of 10) plus the checkpoint itself. A table of 2 million small files carries 2 million add actions, with their stats, in every checkpoint. So compaction (Lesson 13.4) shrinks the log as well as the scan.

Numbers to remember

ThingValueWhat it means
Default isolation levelWriteSerializableWrites are serialisable, reads use snapshot isolation
commitInforeadVersion, isolationLevel, isBlindAppendWhat DESCRIBE HISTORY shows about each commit
Row-level concurrencyRuntime 14.3 LTS and aboveUnpartitioned tables with deletion vectors. OPTIMIZE then conflicts with MERGE, UPDATE and DELETE only with ZORDER BY
A deletion vectorA RoaringBitmap over 64-bit row indexesKept in a deletionvector<uuid.bin file, or inline in the log when small. A file's identity in the log becomes the pair (path, deletion vector id)
Deletion vectors, the featureReader 3, writer 7A reader-writer feature, so enabling it locks out older readers (Lesson 13.2)
spark.databricks.delta.optimize.maxDeletedRowsRatio5%Open-source Delta's OPTIMIZE also picks files with more than this share of rows deleted
delta.checkpointInterval10 commitsOpen-source Delta. Databricks picks the frequency itself
Other checkpoint shapesMulti-part, V2, log compactionMulti-part splits a huge state over several files (deprecated). V2 (delta.checkpointPolicy = 'v2') is UUID-named and can move add and remove actions into sidecars/. Log compaction files, x.y.compacted.json, fold commits x to y into one file a reader may use instead
Liquid clustering keysA domainMetadata action, domain delta.clusteringWhy the writer feature clustering requires domainMetadata, and why a table cannot be clustered and partitioned at once. Its OPTIMIZE never uses ZORDER BY, so with row-level concurrency it does not conflict with concurrent DML
Photon and deletion vectorsRuntime 12.2 LTS with PhotonMERGE, UPDATE and DELETE with deletion vectors came to Photon first; the JVM engine gained UPDATE in 14.1 and MERGE in 14.3 LTS. Photon plans from the snapshot's stats and deletion vectors, skips files, and runs scans, filters, joins and aggregations natively

Teams with many writers on one table design for it: one writer per table where possible, disjoint partitions or ranges where not, max_concurrent_runs: 1, bounded retries on the DML, deletion vectors for row-level concurrency, and compaction left to predictive optimization. DESCRIBE HISTORY (readVersion, isBlindAppend) explains each conflict.

What changed at SwiftKart

Nora gets her answer at 9:00. The INSERT never loses because it reads nothing. The MERGE lost because the backfill rewrote a file it should have seen, and lost twice because the backfill was still running.

Three changes follow. Backfills go through the job queue from Lesson 13.6, so they never run beside the nightly MERGE. The MERGE retries from a fresh snapshot, with a limit. And silver.orders gets deletion vectors, so two writers clash only over the same row.

That completes the lakehouse: a table that is files plus a log, kept fast, loaded in layers, scheduled, governed, and safe with two writers. Module 14 steps down to the cloud underneath it, starting with its building blocks.

In one line

A Delta write takes no lock: it writes files, then creates the next log file only if absent, and the loser of a race fails only if a winner changed data it read; deletion vectors narrow that to rows, and checkpoints keep the log quick to read.

Interview corner

Walk me through what happens when two jobs write the same Delta table at once.

Each job reads the latest snapshot, say version 7, records what it read and writes its new Parquet files. Both then try to create 00008.json only if absent; one wins. The loser reads commit 8 and checks it in order: protocol change, metadata change, a txn for its own app id, added files it should have read, removed files it read, removed files it also removes. If none applies it commits as 9 without redoing work; otherwise it throws the matching exception and the job must restart the operation from a new snapshot.

What is the difference between WriteSerializable and Serializable?

Both give serialisable writes and snapshot-isolated reads. WriteSerializable, the default, ignores files added by blind appends when checking a transaction, so a MERGE can commit after an INSERT it never saw; a reader may then see a state that never existed in the log. Serializable counts every added file, so that MERGE fails with ConcurrentAppendException. In both, only the operation that read the data fails, never the INSERT.

Two nightly MERGEs on one unpartitioned table keep failing with ConcurrentAppendException. What do you do?

First, confirm with DESCRIBE HISTORY which commits overlapped, using readVersion. Then remove the overlap: run them in sequence in one job or with max_concurrent_runs 1, or make them touch disjoint data by partitioning on the column in their conditions and adding that predicate to the MERGE. On Databricks, enable deletion vectors on the unpartitioned table so row-level concurrency applies and only same-row changes conflict. Keep a bounded retry with backoff on the MERGE, starting from a fresh snapshot.

What is in a Delta checkpoint, and why do checkpoints matter?

A checkpoint is a Parquet file holding the reconciled state at one version: the protocol, the metaData, every live add with its stats, the remove tombstones VACUUM still needs, and txn and domain metadata, but no commitInfo. _last_checkpoint points at the newest, so a cold reader opens it plus at most the commits since, about 9 with the open-source interval of 10. They also bound log cleanup: commits older than the log retention are deleted only behind a checkpoint. A table with millions of files has huge checkpoints, so compaction speeds up opening the table as well as scanning it.