A stream processor is writing a billion events an hour into a table on S3. It writes a new Parquet file every few seconds because that is how often its micro-batch flushes, so after a day the table is four hundred thousand tiny files, each a few hundred kilobytes, and a query that should scan a morning’s data instead opens and closes two hundred thousand objects, pays an S3 GET and an HTTP round trip for every one, and spends its entire runtime in metadata overhead before it reads a single useful byte. So you run a compaction job that rewrites those four hundred thousand little files into four hundred big ones. But the stream never stops: while compaction is rewriting file part-00817, the writer appends part-00911, and a reader that started its query somewhere in the middle sees part-00817 twice (the original and the compacted copy), or sees a compacted file that references inputs a half-finished commit already deleted, or double-counts a row. On a plain file-list-the-directory data lake there is no answer to “which files are the table right now,” so there is no answer to any of this. The table is corrupt and nobody can tell you when it happened.
This post is about the lakehouse - the thing Delta Lake, Apache Iceberg, and Apache Hudi are: a transactional table format layered over cheap object storage, with the query engine (Spark, Trino, Flink) reading and writing through it. I am not designing the object store, the Parquet encoder, or the vectorized scan operators inside the engine - those are givens. I am designing the layer that makes a pile of immutable files on S3 behave like a table: how high-velocity streams land as small files without blocking, how a background compactor rewrites them into large optimized row groups, and - the whole game - how an ACID transaction log serializes compaction commits against concurrent writer appends so that every reader sees a single consistent snapshot of the table and can travel back to any past version. Get the log wrong and nothing else matters. Let me build it properly.
Functional Requirements (FR)
In scope:
- Ingest high-velocity append streams. Multiple writers (Flink/Spark streaming jobs, batch loads) append events to a table continuously, each flushing micro-batches as new immutable Parquet files. Writes are append-heavy; the hot path must not block on compaction or on other writers.
- Commit atomically. A write - one file or a thousand - either becomes visible in full or not at all. A reader never sees a half-written batch, a torn file set, or a partially compacted table.
- Compact small files. A background process rewrites many small Parquet files into fewer large ones with large row groups, without blocking writers or readers and without ever losing or duplicating a row.
- Snapshot-isolated reads. A query pins the table version at the instant it starts and reads a consistent set of files for its whole duration, even as writers append and the compactor rewrites underneath it.
- Time travel. Query the table as of a past version or timestamp (
VERSION AS OF 912,TIMESTAMP AS OF '2026-11-20') for audits, reproducible ML training, and rollback. - Schema evolution. Add, rename, drop, and reorder columns without rewriting existing data; old files read correctly under the new schema.
- Row-level deletes and updates (MERGE/UPSERT). Support
DELETE WHERE,UPDATE, andMERGE(CDC upserts) over an append-oriented store, including GDPR-style deletes.
Explicitly out of scope (own the boundary):
- The object store itself. We assume durable object storage (S3/GCS/ADLS, 11-nines) with read-after-write on new keys. We design the table format and the commit protocol over it; we do not build the blob store.
- The Parquet/columnar format and the scan engine. Column encoding, row-group layout, predicate pushdown, vectorized execution - a separate concern, covered in the columnar-analytical-database design. Here, Parquet files are the opaque unit the table format tracks.
- A full SQL optimizer / distributed join planner. The engine on top (Trino, Spark) plans and executes queries. We provide it a consistent file list and column statistics for pruning; we do not design the cost-based optimizer.
- Sub-millisecond OLTP point lookups. This is an analytical table over object storage. Point reads by key are possible but not the target; latency is seconds, throughput is the goal.
- Streaming exactly-once sinks upstream of us. We give writers an idempotent commit; de-duplicating the source stream before it reaches a writer is the upstream job’s problem.
The single decision that drives everything: a lakehouse is an append-heavy table made of immutable files on dumb object storage, so the table is not the files - it is an ordered, atomic log of commits that says which files are live at each version. Every hard problem here (compaction vs appends, snapshot isolation, time travel, deletes) reduces to how that log is written and read. Get the log right and the files take care of themselves.
Non-Functional Requirements (NFR)
- Scale: a table on the order of tens of TB to low PB, hundreds of billions of rows, growing by billions of rows/day. Dozens of concurrent writers appending micro-batches; a single table can accumulate millions of data files over its life if left uncompacted. Hundreds to low thousands of concurrent read queries.
- Ingest rate: sustain millions of events/sec aggregate across writers, landing as new files every few seconds per writer. Commit throughput on the order of tens to low hundreds of commits/sec per table (the serialization point - sized carefully below).
- Latency: data visible to readers within seconds to a low minute of a writer’s commit (micro-batch cadence). Query planning (figuring out which files to read) in under ~1s even for a huge table - this must not re-list object storage. Scan latency is the engine’s; we target not making it worse.
- Availability: reads target 99.9%+. Because data is immutable files on durable storage and the log is append-only, compute is stateless and restartable; a crashed writer or compactor loses at most its uncommitted work, never committed data.
- Consistency: serializable commits, snapshot-isolated reads. Commits to one table are linearized through a single ordered log; a conflicting commit is rejected and retried, never silently merged. A reader sees exactly the set of files live at one log version for its whole query.
- Durability: 11-nines, inherited from object storage. Data files and log entries are immutable once written; nothing is updated in place. A committed version is reconstructable forever (until explicitly vacuumed).
- Isolation of workloads. Compaction, appends, deletes, and reads must not block one another except at the one true serialization point (the commit). Long-running reads must not pin storage forever; long-running compaction must not stall ingestion.
Back-of-the-Envelope Estimation (BoE)
Grounding the design in numbers before drawing boxes.
Ingest and file counts - the whole reason the system exists:
Event rate (aggregate): 2,000,000 events/sec
Avg event size: ~500 bytes raw, ~150 bytes Parquet-encoded
Writers: 40 streaming tasks, each flushing every 5 sec
Per writer per flush: 2,000,000 / 40 * 5 = 250,000 events
Per-file size (uncompacted): 250,000 * 150 B ≈ 37 MB ... in the good case.
That 37 MB is the optimistic case where one writer owns a whole partition. In reality a micro-batch spreads across many partitions (say event_date x region, ~200 live partitions), so each flush writes ~200 files of ~190 KB each, not one 37 MB file:
Files per flush: 40 writers * 200 partitions = 8,000 files / 5 sec
Files per hour: 8,000 * 720 = 5,760,000 small files/hour
File size (uncompacted): ~190 KB -> the small-file problem, quantified
Nearly six million files an hour, each a fifth of a megabyte. That is the disease. A query over one hour would open ~5.76M objects. Compaction has to collapse this by ~200x into ~128 MB target files with ~16 MB row groups.
Storage/year:
Daily ingest: 2M/sec * 86,400 * 150 B ≈ 25 TB/day encoded
Per year: ~9 PB/year raw append (before dedup/retention)
Compacted + columnar well-encoded (~3x over naive Parquet): ~3 PB/year live
Plus old snapshots retained for time travel (see vacuum below).
The transaction log size - the part people forget:
Each commit adds a log entry listing added + removed files.
Append commit: ~200 file-add entries, ~a few KB each -> ~1 MB/commit? No:
entry = {path, size, partition values, row count, min/max per column}
≈ ~1-2 KB per file entry.
Appends/sec: 40 writers / 5 sec cadence = 8 commits/sec
(each commit batches that writer's ~200 files)
Log growth: 8 commits/sec * 200 entries * 1.5 KB ≈ 2.4 MB/sec of log
≈ ~200 GB/day of raw log entries.
The log grows fast - which is exactly why it gets checkpointed (periodic Parquet snapshot of log state) and why reading the whole log on every query is a non-starter. More on both below.
Commit QPS - the serialization bottleneck:
Append commits: ~8/sec (40 writers, 5-sec cadence, batched).
Compaction commits: a handful/min (big, infrequent, rewrites).
Delete/MERGE commits: workload-dependent, bursty.
Total commits to serialize per table: tens/sec peak.
Tens of commits/sec through one ordered log per table is the number the whole commit protocol has to sustain. That is modest - the hard part is not throughput, it is correctness under concurrency: making those tens of commits/sec strictly ordered, conflict-checked, and atomic on storage that gives you almost no primitives.
Query planning cost:
Table files (post-compaction, 1 year): ~3 PB / 128 MB ≈ 24 million files.
Listing 24M files per query via S3 LIST: minutes. Unacceptable.
Reading the log/checkpoint + column stats to prune: the files that
actually match a predicate are a tiny fraction -> plan in well under 1s.
The log is not just for correctness; it is the metadata index that lets a query prune 24M files down to the few hundred it must read without ever listing the bucket. That is the second reason the table is the log, not the files.
High-Level Design (HLD)
The system is a table format over object storage, mediated by a commit protocol. Writers produce immutable Parquet data files directly into the bucket, then atomically commit a log entry that adds those files to the table. A compactor is just a special writer that commits “remove these small files, add these big ones.” A catalog/commit service linearizes commits per table. Readers resolve the current (or a past) log version to a concrete file list and scan it.
WRITERS (streaming + batch, dozens, append-heavy)
┌──────────────────────────────────────────────────────────────────────┐
│ Flink/Spark task: │
│ 1. buffer micro-batch -> write immutable Parquet data files to S3 │
│ 2. attempt COMMIT: append a log entry {add files, stats} to the log │
│ 3. on conflict: re-read latest log, re-validate, retry │
└───────────────┬────────────────────────────────────┬───────────────────┘
data files │ (written BEFORE the commit) │ commit (the serialized point)
▼ ▼
┌───────────────────────────────┐ ┌────────────────────────────────┐
│ OBJECT STORAGE (S3/GCS) │ │ CATALOG / COMMIT SERVICE │
│ immutable Parquet data files │◄──────►│ linearizes commits per table │
│ /table/data/part-*.parquet │ │ (conditional put / CAS / │
│ │ │ DB txn on current version) │
│ TRANSACTION LOG (same bucket)│ └────────────────┬───────────────┘
│ /table/_log/0000..N.json │ │ resolves version -> files
│ /table/_log/chk-*.parquet │◄────────────────────────┤
│ (ordered commits + checkpoints) │
└───────────────┬───────────────┘ │
│ read log/checkpoint │
▼ ▼
┌───────────────────────────────┐ ┌────────────────────────────────┐
│ COMPACTOR (a special writer) │ │ READERS / QUERY ENGINE │
│ reads small files, writes big │ │ (Trino / Spark / Flink SQL) │
│ ones, commits swap atomically │ │ 1. pin a log version (snapshot)│
│ (rewrite = add+remove in one │ │ 2. prune files via stats │
│ commit, conflict-checked) │ │ 3. scan the exact file set │
└───────────────────────────────┘ └────────────────────────────────┘
Request flow - a writer appending a micro-batch (the hot path):
- The writer buffers a micro-batch in memory, partitions it by the table’s partition columns, and writes new immutable Parquet files directly to object storage under
/table/data/. These files exist in the bucket but are not yet part of the table - no log entry references them, so no reader can see them. Writing data is decoupled from committing it. - The writer reads the current log version
N(from its cached checkpoint + any newer entries), then attempts to commit versionN+1: a log entry listing the files it added, with per-file stats (row count, min/max per column, partition values). The commit is a single atomic operation against the catalog - a conditional put (“create log entryN+1only if it does not exist”) or a transactional update of the table’s current-version pointer. - If the commit succeeds, the files are now live at version
N+1; readers starting after this see them. If it fails (someone else committedN+1first), the writer re-reads the new latest version, re-runs its conflict check (does the other commit invalidate mine?), and retries asN+2. Pure appends almost never truly conflict, so retry is cheap. - The data files written in step 1 for a commit that never lands are orphans - harmless (no log entry points at them) and cleaned up later by vacuum.
Request flow - a reader (snapshot isolation + time travel):
- The query pins a version: the latest committed version for a normal read, or a specific
VERSION AS OF/TIMESTAMP AS OFfor time travel. This version number is the snapshot; it does not change for the query’s lifetime. - The engine reconstructs the file list at that version by reading the latest checkpoint at-or-before it plus the log entries after the checkpoint up to the pinned version, applying adds and removes. It never lists the bucket.
- Using the per-file column stats in the log, it prunes files whose min/max cannot match the query predicate and whose partition values are excluded, down to the few hundred files that matter.
- It scans those exact files. Writers appending and the compactor rewriting in the meantime produce new versions
> pinned; the reader never sees them. Removed files still physically exist (vacuum has not deleted them), so the pinned snapshot stays readable to the end.
The key architectural insight: data files are immutable and written before they are committed; the only mutable, serialized thing in the whole system is the append-only log of commits, and the only hard operation is appending to it atomically. Everything - atomicity, snapshot isolation, time travel, compaction correctness - is a property of that log. The files are just inert bytes the log points at.
Component Deep Dive
Four hard parts: (1) the ACID commit protocol - how you append to the log atomically on dumb storage and serialize compaction against appends; (2) snapshot isolation and time travel - how a reader gets a stable, reconstructable view and how you keep the log cheap to read; (3) small-file compaction - evolving from naive rewrite to a conflict-safe, bin-packed background swap; (4) row-level deletes and MERGE - doing updates over immutable files. I will walk each from naive to scalable.
1. The ACID Commit Protocol: Serializing Writes on Dumb Storage
This is the heart. Object storage gives you PUT, GET, LIST, DELETE - no transactions, no locks, often no cross-key atomicity. We have to build serializable commits on top of that.
Approach A: The table is “whatever files are in the directory” (the naive data lake)
The classic Hive-style lake: the table is a directory, and the files in it are the data. A writer drops a file in; a reader lists the directory.
writer: PUT /table/data/part-00911.parquet
reader: LIST /table/data/ -> scan every file returned
Where it breaks: everything at once. There is no atomic multi-file commit - a writer adding 200 files for one batch exposes them one at a time, so a reader listing mid-write sees a torn, partial batch. LIST on object storage is eventually consistent on many systems, so a reader may miss a just-written file or see a just-deleted one. Compaction is impossible to do safely: the moment the compactor deletes a small file it just rewrote, a reader that already listed it gets a 404; the moment it adds the big file before deleting the smalls, readers double-count. There is no version, so no snapshot isolation and no time travel. And LIST over millions of files is minutes slow. The directory is the table, and a directory is not a transactional object.
Approach B: An ordered, atomic transaction log, committed via compare-and-swap
Stop treating the directory as the table. The table is an append-only log of versioned commits, each an immutable object, and “the table at version N” is the result of replaying commits 0..N.
/table/_log/00000000.json commit 0: {add: [f1,f2], metadata, schema}
/table/_log/00000001.json commit 1: {add: [f3], remove: []}
/table/_log/00000002.json commit 2: {add: [f4], remove: []}
...
each entry: { version, timestamp, operation, add:[{path,size,rowCount,
partitionValues, stats:{col->{min,max,nulls}}}], remove:[path...] }
A commit is “create the next log file.” The entire ACID problem collapses to: make creating 0000000N.json atomic and exclusive - exactly one writer can create version N, everyone else who tries fails and retries. Two ways to get that primitive:
- Conditional put (optimistic, storage-native). Use the store’s “put-if-absent” (S3 now supports conditional writes; GCS/ADLS have preconditions). Writer reads latest version is
N-1, attemptsPUT /_log/0000000N.jsononly if it does not already exist. If it succeeds, it won the commit. If it fails (object exists), someone beat it to N; re-read, re-validate, retry at N+1. No external service needed. - Catalog commit service (a tiny transactional authority). A metadata store (an RDBMS row, DynamoDB conditional update, or a catalog like Iceberg’s REST/Glue/Nessie) holds
(table -> current_version, pointer). A commit is a single transactional compare-and-swap: “set current_version = N where current_version = N-1, and record the new log pointer.” The RDBMS/DynamoDB gives real atomicity; the log file is written first, then the pointer flips to publish it. This is more robust than raw conditional puts and is what production lakehouses use for multi-engine safety.
Either way the commit is optimistic concurrency control: prepare optimistically (write your data files, build your intended log entry), then try to atomically claim the next version; on loss, re-validate and retry. Re-validation is the subtle part and is where compaction-vs-append is decided:
commit(myOp):
loop:
base = latest committed version
if conflicts(myOp, commits since my snapshot base): # the crux
myOp = reconcile(myOp, newer commits) # or abort if irreconcilable
try: atomically create version base+1 with myOp # CAS / conditional put
on success: return
on lost-race: continue # re-read, re-check, retry
The compaction-vs-append serialization, concretely. A compaction commit says “remove small files S = {s1..sk}, add big file B containing the same rows.” An append commit says “add file a.” These must serialize so a reader never sees a row twice or zero times:
- Append then compaction: the compactor snapshotted the table at version N and planned to rewrite files
S. Before it commits, an append lands at N+1 adding filea. The compactor tries to commit at N+2. Conflict check: doesaoverlap the files I rewrote?ais a brand-new file, not inS, so it does not invalidate my rewrite - I am removingSand addingB;ais untouched and stays live. No conflict: the compactor commits at N+2; the table is now(everything - S) + B + a. Correct:a’s rows appear once (ina),S’s rows appear once (inB). - Compaction then append: symmetric and even easier - the append adds a new file, never touches
SorB, always commits. - The real conflict - two writers rewriting the same files. Two compactors both snapshot at N and both plan to rewrite overlapping sets
S1 ∩ S2 ≠ ∅. First commits at N+1 removingS1. The second tries N+2 to removeS2, but some files inS2no longer exist in the table (the first commit removed them). Conflict: the second’sremoveset references files already gone. It aborts and re-plans over the now-current file set. This is the one case that must be serialized, and the conflict check (does myremove/deleteset intersect files removed since my snapshot?) catches it exactly.
The conflict rule generalizes: a commit conflicts only if it depends on files another concurrent commit removed, or if two commits delete the same logical rows. Appends depend on nothing (they only add), so they never conflict with anything - which is why tens of appends/sec sail through, and only compaction/delete commits ever need to retry. That asymmetry is the whole reason this scales: the hot path (append) is conflict-free; the rare path (rewrite/delete) pays the serialization cost.
version N: live = {s1,s2,s3, a0}
compactor snapshots N, plans remove {s1,s2,s3} add {B}
appender A commits N+1: add {a1} -> live = {s1,s2,s3,a0,a1}
compactor commits N+2: check {s1,s2,s3} still present? yes. OK.
remove {s1,s2,s3} add {B} -> live = {B, a0, a1} # correct
concurrent compactor-2 (also from N) tries remove {s2,s3} -> GONE -> abort, replan
2. Snapshot Isolation, Time Travel, and Keeping the Log Cheap
A reader must see a stable table for its whole query, and we must be able to read any past version - without replaying millions of log entries every time.
Approach A: Replay the entire log on every read (naive)
To get the file list at version N, read _log/00000000.json through _log/0000000N.json, apply every add and remove in order.
Where it breaks: the log has millions of entries after a busy week (8+ commits/sec). Reading and folding all of them per query takes many seconds and grows without bound - query planning becomes slower than the scan. Time travel to an old version is fine, but the current version keeps getting more expensive to resolve every single day. The log is correct but unreadable at scale.
Approach B: Checkpoints plus log tail, snapshot by version pin
Periodically checkpoint the log: every K commits (say 100), write a single Parquet file that is the materialized state of the table at that version - the full live file list with stats - so readers never replay from zero.
/table/_log/..010000.json commit entries
/table/_log/..010000.checkpoint.parquet <- full state as of 10000
/table/_log/..010001.json
...
/table/_log/_last_checkpoint -> points at the newest checkpoint (10000)
resolve(version V):
base = latest checkpoint <= V # read ONE Parquet file: full file list
apply log entries (base, V] # fold a handful of small JSON deltas
-> concrete file list + stats. O(commits since last checkpoint), not O(all).
Now resolving any version is “read one checkpoint Parquet (the live file list, already compacted and columnar, prunable itself) + replay at most K recent small JSON deltas.” Constant-ish, fast, and the same mechanism serves current reads and time travel.
- Snapshot isolation = pin the version, period. A reader resolves version V once at query start and reads that exact file list for its whole life. Concurrent commits create V+1, V+2, … which the reader simply never looks at. Because data files are immutable and not physically deleted at commit time (only logically removed from the log; physical deletion is vacuum’s job, below), every file in snapshot V stays on disk and readable until vacuum decides no live-enough snapshot needs it. Isolation falls out for free from immutability plus version pinning - no read locks, no MVCC row versions, no blocking writers.
- Time travel = resolve an old version.
VERSION AS OF 912resolves version 912 exactly as above.TIMESTAMP AS OF '2026-11-20T00:00'maps the timestamp to the latest version whose commit time is<= that(each log entry stamps a commit time), then resolves it. Audits, “what did the model train on,” and rollback (commit a new version whose file list equals an old one) all use this. It is not a special feature - it is the log already being versioned. - Metadata pruning from the checkpoint. The checkpoint/log carries per-file column min/max, null counts, partition values, and row counts. Query planning reads that (small, columnar) and discards files that cannot match the predicate - pruning 24M files to a few hundred without touching the bucket or the data. The log is simultaneously the correctness mechanism and the pruning index.
- Log cleanup and vacuum. Two separate jobs: log compaction (checkpoint + expire old log JSON entries past the time-travel retention window, e.g. keep 30 days), and VACUUM (physically
DELETEdata files that are not referenced by any snapshot newer than a retention horizon). Vacuum is why you cannot time-travel arbitrarily far back - it is the deliberate trade between storage cost and history depth. It must respect in-flight readers: never delete a file a live snapshot still points at, which is enforced by a retention interval longer than the longest allowed query/snapshot age.
RETENTION / VACUUM:
snapshots kept: all within 30 days (time-travel window)
data files kept: any referenced by a kept snapshot
vacuum: DELETE data files unreferenced by any snapshot newer than horizon H
(H > max query duration, so no live reader is pulled out from under)
orphans (files from aborted commits, never in any log entry) also vacuumed.
3. Small-File Compaction: From Blocking Rewrite to Conflict-Safe Bin-Packing
The BoE said ~5.76M files/hour at ~190 KB each. Compaction has to collapse that ~200x into ~128 MB files with large row groups, continuously, without stopping ingestion.
Approach A: Stop-the-world rewrite (naive)
Take a lock on the table (or just “pause writers”), list all small files, rewrite them into big ones, swap, release.
Where it breaks: ingestion is continuous - you cannot pause a firehose without the upstream Kafka backing up and the micro-batches ballooning. A global table lock serializes all writers behind compaction, destroying append throughput. And rewriting the entire table every cycle is quadratic waste: you re-read and re-write big files that were already compacted, just to absorb a few new small ones. It does not finish before the next hour’s six million files arrive.
Approach B: Incremental, partition-scoped, conflict-safe bin-packing
Compaction is a special writer that commits an atomic add+remove, scoped to a slice of the table, selecting only files worth rewriting:
- Select by bin-packing, not everything. For each partition, find the set of files below the target size (e.g. < 128 MB) and bin-pack them into groups that each sum to ~128 MB. Files already at target size are left alone - compaction only touches the small-file debris, so cost is proportional to new ingestion, not table size. This is the fix for Approach A’s quadratic waste.
- Rewrite into large row groups. The output Parquet files use large row groups (~16 MB) so scans get big sequential reads and effective column encoding/compression, and the engine’s predicate pushdown operates on coarse row-group stats. Small input files had tiny row groups (bad compression, metadata-heavy); the rewrite is what makes the data fast to scan, not just fewer files.
- Commit as an atomic swap, conflict-checked. The compactor reads files
S(small) from partition P at snapshot N, writes big file(s)B, and commits{remove: S, add: B}. Per section 1, this conflicts only with another commit that removed a file inS(another compactor on the same partition, or a delete that rewrote those files). Appends to P in the meantime add new small files not inS- no conflict; they just become the next cycle’s input. On conflict, re-plan over the current file set. - Partition-parallel. Different partitions are disjoint file sets, so N compactors each own different partitions and never conflict with each other (their
removesets are disjoint). This is how compaction keeps up with ingestion: scale compactors with partitions. Only two compactors targeting the same partition conflict, which the selector avoids by assigning partitions. - Sort/cluster on write (optional but large win). While rewriting, sort rows within files by a high-selectivity column (or Z-order/space-fill across two columns) so min/max stats are tight and later queries prune aggressively. Compaction is the natural place to pay this cost since you are rewriting anyway.
- Scheduling. A lightweight job watches per-partition file counts (from the log metadata - no listing needed) and triggers compaction on partitions that cross a threshold (e.g. > 50 small files). Hot, recently-written partitions compact often; cold partitions compact once and are left. This targets the exact spots the small-file problem lives.
PER PARTITION P (independent, parallel, conflict-free across partitions):
smalls = files in P with size < 128MB # from log metadata, no LIST
bins = binpack(smalls, target=128MB)
for each bin:
B = rewrite(bin, rowGroup=16MB, sort=clusterCol) # new immutable file(s)
commit {remove: bin, add: B} at version N+1 # atomic, conflict-checked
# appends to P during this add NEW files, not in `bin` -> no conflict
4. Row-Level Deletes and MERGE Over Immutable Files
Files are immutable, but DELETE WHERE, UPDATE, and CDC MERGE need to change rows. The question is how to “delete” a row from a file you cannot modify.
Approach A: Rewrite every file touched (copy-on-write, naive-but-valid)
To delete rows, read each data file containing a matching row, write a new file with those rows removed, and commit {remove: old, add: new}.
Where it breaks: write amplification. Deleting one row out of a 128 MB file rewrites the whole 128 MB. A GDPR delete of one user scattered across thousands of files rewrites thousands of full files - gigabytes written to erase kilobytes. For high-frequency CDC upserts (a MERGE every few minutes touching rows all over the table), copy-on-write rewrites a huge fraction of the table continuously. Correct, but ruinous for delete-heavy or update-heavy tables.
Approach B: Merge-on-read with delete files (deletion vectors)
Decouple “mark deleted” from “physically remove.” A delete file (or a deletion vector - a bitmap of deleted row positions) records which rows of which data files are logically deleted, committed as its own log entry. Readers apply deletes at scan time.
- Position deletes / deletion vectors. For “delete rows 5, 90, 2011 of file
f,” write a compact bitmap keyed by(file, rowPosition)and commit{add-delete-vector: dv_f}. The data filefis untouched. A reader scanningfloadsdv_fand skips those positions. One-row delete = one bitmap entry, not a 128 MB rewrite. - Equality deletes (for CDC/MERGE). For streaming upserts where you do not know positions, write an equality delete (“delete rows where
pk = 42”) committed alongside the new inserted version of the row. Readers filter out rows matching any equality-delete predicate for versions older than the delete. This lets a MERGE commit be “add new/updated rows + add equality-delete for old keys,” cheap and append-only. - Snapshot-consistent with the log. Delete files are log-tracked files like data files, so they participate in versioning: snapshot V sees exactly the delete files committed at-or-before V, so time travel to before a delete correctly shows the row as present. Deletes serialize through the same commit protocol - a delete conflicts with a concurrent commit that rewrote the same data file (its positions moved), caught by the same file-level conflict check.
- Compaction reconciles them (merge-on-read -> copy-on-write amortized). Delete files accumulate and slow reads (every scan applies them), so compaction periodically materializes them: rewrite data files with deleted rows physically dropped and discard the delete vectors, in one atomic commit. This is the amortization - cheap deletes now (merge-on-read), bulk physical removal later (copy-on-write during compaction you were doing anyway). The knob is how long you tolerate delete-file overhead before materializing.
DELETE user 42:
merge-on-read: commit { add deletion-vector for files containing pk=42 }
data files untouched; readers skip those rows. # cheap now
later compaction: rewrite those files without the dead rows,
drop the deletion vectors, one atomic commit. # cleanup later
Trade: read-time cost (apply deletes) vs write-time cost (rewrite). MoR defers it.
API Design & Data Schema
Table / commit API (what writers and the catalog speak)
# A commit: atomically advance the table by one version.
POST /tables/{table}/commits
{
"baseVersion": 912, # the version I read; CAS target
"operation": "append" | "compact" | "delete" | "merge" | "overwrite",
"addFiles": [ { "path": "data/part-00933.parquet", "size": 134217728,
"rowCount": 1048576, "partitionValues": {"dt":"2026-11-27"},
"stats": { "user_id": {"min":1,"max":998412,"nulls":0},
"ts": {"min": 1764201600, "max": 1764205200} } } ],
"removeFiles": [ "data/part-00817.parquet", "data/part-00820.parquet" ],
"deleteVectors":[ { "dataFile":"data/part-00901.parquet",
"path":"deletes/dv-00901.bin", "deletedRows": 3 } ]
}
-> 201 { "version": 913 } # won the race, committed
-> 409 Conflict { "currentVersion": 913 } # someone committed first; re-read, retry
# Resolve a snapshot to a concrete, pruned file list (what readers call).
GET /tables/{table}/snapshot?version=913 # or ?asOfTimestamp=...
-> { "version": 913, "schema": {...},
"checkpoint": "_log/000913000.checkpoint.parquet",
"logTail": ["_log/000913001.json", ...], # deltas since checkpoint
"files": [ ...live files with stats for pruning... ] }
GET /tables/{table}/history -> [ {version, timestamp, operation, ...} ]
POST /tables/{table}/vacuum { "retainHours": 720 } # physical cleanup
POST /tables/{table}/schema { "addColumn": {...} } # metadata-only evolve
The transaction log entry (the one schema that matters)
# One immutable JSON object per commit: _log/{version:020d}.json
{
"version": 913,
"timestamp": 1764201612345, # commit time -> TIMESTAMP AS OF
"operation": "compact",
"add": [ { "path", "size", "rowCount", "partitionValues",
"stats": { col -> { min, max, nullCount } } } ],
"remove": [ { "path", "deletionTimestamp" } ],
"metadata": { "schemaId", "partitionColumns" }, # present on schema/partition change
"schema": { ... }, # set at creation / evolution
"clientId": "writer-7", "txnId": "uuid" # idempotency for retried commits
}
Checkpoint (materialized state, read instead of replaying the log)
# _log/{version}.checkpoint.parquet - columnar, prunable, = full live state at V
path STRING data file path
size BIGINT partitionValues MAP<STRING,STRING>
rowCount BIGINT
stats_min MAP<col,VALUE> stats_max MAP<col,VALUE> stats_nulls MAP<col,BIGINT>
isDeleteVector BOOL targetDataFile STRING # for delete-file rows
addedAtVersion BIGINT
# Readers scan this (one columnar file) + fold JSON deltas after it.
Why this storage model, not a relational table. The data is immutable append-mostly analytical files on cheap object storage - a relational DB cannot hold petabytes affordably and is the wrong engine for scan-heavy analytics. But a plain file lake has no transactions. So the design is columnar files (Parquet) for data + an ordered metadata log for transactions + a small transactional catalog for the single commit-serialization point. The catalog is the only place that needs real ACID (one row: table -> current_version), and it is tiny and low-QPS (tens of commits/sec), so a single RDBMS row or a DynamoDB conditional update suffices. Everything large (data, log, checkpoints) lives on object storage and is immutable, so it is cheap, durable, and never contended. The SQL-vs-NoSQL choice is answered per-component: object storage for bulk immutable data, a small strongly-consistent catalog for the commit pointer - not one database for both.
Bottlenecks & Scaling
Where it breaks first, in order, and the fix for each:
1. Small files crushing query planning and scan. Millions of ~190 KB files mean millions of S3 GETs and HTTP round trips per query, all metadata overhead. Fix: incremental, partition-parallel, bin-packing compaction into ~128 MB files with ~16 MB row groups; selection driven by per-partition file counts in the log, so cost tracks new ingestion, not table size.
2. The commit serialization point (one ordered log per table). Every write funnels through “claim the next version”; too many conflicting commits thrash on retries. Fix: appends are conflict-free (add-only, never invalidated), so the high-rate path never retries; only compaction/delete commits serialize, and they are rare and partition-scoped. Batch each writer’s micro-batch into one commit (200 files, one version bump) to keep commit QPS at tens/sec, not thousands. Commit via conditional put / catalog CAS, which sustains that easily.
3. Hot partition / hot writer. A skewed partition (today’s date, one big region) attracts most appends and most compaction. Fix: finer partitioning or bucketing on a high-cardinality column to spread writes; dedicate compactors to hot partitions; sort/cluster on write so even a big partition prunes well. Partition-level parallelism means hot and cold partitions compact independently.
4. Log read cost grows unbounded. Resolving the current version by replaying millions of entries gets slower every day. Fix: periodic checkpoints (every ~100 commits) materialize full state into one columnar Parquet; readers read the latest checkpoint + a short JSON tail. Resolution is O(recent commits), not O(all history). Expire old log JSON past the time-travel window.
5. Two compactors (or a compaction and a delete) fighting over the same files. The real conflict case - overlapping remove sets.
Fix: the file-level conflict check at commit: a commit aborts if any file it removes/depends-on was removed by a concurrent commit since its snapshot, then re-plans over current state. Partition assignment makes this rare; the check makes it safe when it happens. Appends never hit this.
6. Delete/MERGE write amplification. Copy-on-write rewrites whole files to change a few rows; GDPR and CDC make this continuous. Fix: merge-on-read with deletion vectors / equality deletes - cheap append-only “mark deleted,” applied at scan time, then materialized by compaction in bulk later. Trades read-time cost for far lower write amplification; the knob is materialization frequency.
7. Readers pinned to old snapshots blocking cleanup, and storage blowup from retained versions. Immutable + versioned means nothing is ever deleted until told.
Fix: VACUUM physically deletes data/delete files unreferenced by any snapshot newer than a retention horizon H, with H > max query/snapshot age so no live reader is pulled out from under. This is the explicit storage-cost vs time-travel-depth trade. Orphan cleanup removes files from aborted commits (never in any log entry).
8. Catalog as a single point of failure / contention. Every commit touches the one catalog row for the table. Fix: the catalog is per-table (or per-table-partition of the keyspace), so contention is bounded by one table’s tens of commits/sec; run it on a replicated, strongly-consistent store (RDBMS with failover, DynamoDB, or a Raft-backed catalog like Nessie). It stores pointers, not data, so it stays small and fast; losing a replica fails over without data loss because the log and files are the durable truth.
9. Eventually-consistent object storage. A stale LIST or a not-yet-visible GET could corrupt reads. Fix: never LIST to find the table - the file set comes from the log, and new keys have read-after-write consistency on modern S3/GCS. The commit’s atomicity lives in the catalog CAS / conditional put, not in listing. Immutability means no overwrite-visibility races.
10. Schema evolution breaking old files. Adding/renaming a column must not require rewriting petabytes. Fix: column-ID-based schema in the log (not name-or-position): add/rename/drop/reorder are metadata-only commits; old files are read by mapping their columns to IDs, with missing columns read as defaults/null. No data rewrite; the log’s schema version governs how each snapshot interprets files.
Wrap-Up
The trade-offs that define this design:
- The table is a log, not a directory. We pay the cost of a commit protocol and a metadata log so that a pile of immutable files on dumb object storage behaves like an ACID table - atomic multi-file commits, snapshot isolation, and time travel all fall out of one versioned, append-only log. Everything else is inert bytes the log points at.
- Optimistic concurrency with a conflict-free hot path. Appends only add files and so never conflict, letting tens of writers commit per second without coordination; only compaction and deletes serialize, and only when they touch the same files. We trade occasional compaction retries for a lock-free, high-throughput ingest path.
- Immutability buys isolation for free. Data files are written before they are committed and never mutated, so a reader pins a version and reads a stable file set with no locks and no MVCC rows; the only cost is deferred physical deletion (vacuum), which is the explicit storage-vs-history-depth knob.
- Incremental compaction over stop-the-world. We rewrite only the small-file debris, partition-parallel, as atomic conflict-checked swaps, so compaction keeps pace with a firehose instead of pausing it, and cost tracks new ingestion rather than table size.
- Merge-on-read for deletes, compacted later. Cheap append-only delete markers applied at scan time, materialized in bulk by compaction, trade read-time overhead for a fraction of the write amplification copy-on-write would cost.
- One tiny place needs real ACID. Petabytes of data and the whole log live immutably on object storage; only a single small catalog pointer (
table -> version) needs a strongly-consistent store, so the serialization point is cheap, fast, and the sole thing that must never lie.
One-line summary: writers append immutable Parquet files to object storage and publish them by atomically appending to an ordered transaction log through a compare-and-swap on a tiny catalog, a background compactor rewrites small files into large row groups as conflict-checked atomic swaps that serialize against conflict-free appends, and readers pin a log version - resolved cheaply via checkpoints - for snapshot-isolated, time-travel-capable reads, trading a commit protocol and deferred vacuum for an ACID, continuously-ingested, queryable table on dumb cheap storage.
Comments