Synthesis and Self-Test

Synthesis

Immutability makes the write cheap, and compaction is the deferred bill

The SSTables and sparse indexes part's flat SSTable is only possible because nothing is ever mutated — which means an overwritten key's old version cannot be removed at write time. Every write is therefore O(1)-ish and sequential, and the cost of reclaiming that space is pushed entirely into the Compaction strategies part's background compaction. Leveled compaction's 10–30× write amplification is not a flaw in compaction; it is the invoice for the SSTables and sparse indexes part's write path. Choose size-tiered and you've simply asked to pay it in disk space (2–3× bloat) instead of I/O.

Ref counts and OldestXmin are the same mechanism, and they fail the same way

The Memtable, flush and ref-counting part's SuperVersion ref count and the VACUUM and free space part's OldestXmin both answer one question: is any reader still able to see this? Both defer all cleanup on that answer. So both have the identical pathology: a single long-lived reader stops reclamation entirely. In RocksDB it is a long scan pinning an old snapshot, forcing compaction to keep stale versions and old SSTable files alive (see Concurrency, tombstones and compaction). In PostgreSQL it is a long idle transaction pinning OldestXmin, so VACUUM runs but removes nothing and the table bloats. Different engine family, different vocabulary, same incident.

Both engines have a WAL, and it protects against two different failures

The WAL part's WAL exists because the memtable is only in RAM — the threat is data that exists nowhere on disk. A torn tail entry is harmless and simply discarded, because it was never acknowledged. The In-place writes part's WAL exists because pages are overwritten in place — the threat is data that exists on disk in a half-written, corrupt state. A torn page is not a discardable tail; it is live data that must be reconstructed, which is why B-trees additionally need pageLSN, checkpoints and idempotent ARIES redo, and LSM engines do not.

"the index stores no visibility" is one fact with three consequences

An index entry is only key → TID. From that single omission follows: (a) an index scan must always touch the heap, because the index cannot say which TID is visible to you (see MVCC and visibility); (b) a scan for a repeated key returns every candidate TID and lets heap MVCC filter (see VACUUM and free space); and (c) VACUUM must remove index entries before freeing heap slots, because an index that can't detect a stale pointer would happily lead a reader to a reused slot holding a different row (see VACUUM and free space). Index-only scans are the sole relaxation — and they work by proving visibility in advance via the visibility map, not by moving the check into the index.

The Bloom filter's 300× win is contingent on Numbers on disk's file count

The Bloom filters part says a filter turns a 300 ms miss into a few ms. The Numbers on disk part says that holds only while file count stays bounded — a filter's ~1% false-positive rate is paid per file consulted, so a miss against 1,500 un-compacted files costs ~15 real block reads and against 150 files ~1.5. So the read-path optimization of the Bloom filters part is silently underwritten by the compaction throughput of the Compaction strategies part. When "reads got slow," the subsystem at fault is usually neither the read path nor the filter.

Latches exist because structure is the one thing MVCC cannot version

MVCC (see MVCC and visibility) can show two transactions two different row versions because a row version is just bytes with stamps. It cannot show two transactions two different tree shapes — after a split there is exactly one correct structure, with both children existing, sibling pointers rewritten and the parent updated. That is why the Leaf traversal and latches part needs latch coupling and the In-place writes part needs page latches, and why the MVCC: LSM vs B-tree part's RocksDB needs neither: its structures are append-only and immutable, so "publish a new version and swap one pointer" (see Memtable, flush and ref-counting) does the entire job that latches do here. Latching is the price of in-place mutation, exactly as compaction is the price of immutability.

The inverted index rediscovers Part I, because it has no alternative

Inverting the mapping (see Full-text indexes) makes one document touch a couple of hundred scattered keys, and no in-place structure survives that at arrival rate. Lucene drew the obvious conclusion and built Part I outright: immutable segments (see SSTables and sparse indexes), an in-memory buffer that becomes one on flush (see Memtable, flush and ref-counting), deletes as tombstone bits (see Concurrency, tombstones and compaction), tiered background merges (see Compaction strategies), a translog for the data that exists only in RAM (see WAL). PostgreSQL kept its B-tree and bolted a pending list onto the side — and got a memtable anyway, complete with a read path that must consult two places and a flush that stalls one unlucky writer. The bills then arrive under translated names in both: segment count is file count (see Numbers on disk), deleted_docs is tombstone bloat, _forcemerge is a manual full compaction. Part I is not a design for key-value stores; it is what any index whose writes are scattered eventually converges on.

Self-Test

Question 1

Trace SET k=v2 through RocksDB and through PostgreSQL. What does each engine's WAL protect against, where does each one pay for the write, and why does one need page latches while the other needs only an atomic pointer swap?

Show answer

RocksDB: append to WAL, fsync, insert a new node into the memtable skip list with a fresh sequence number, ACK (see WAL). Nothing is overwritten; the old value stays. The WAL protects memtable data that exists nowhere on disk. The write is paid for later, by compaction — 10–30× write amplification under leveled (see Compaction strategies). No latch is needed because nothing mutates in place: a new node is fully built off to the side and published with one atomic pointer store (see Concurrency, tombstones and compaction, Layer A), and version changes publish a new SuperVersion and swap one pointer (see Memtable, flush and ref-counting).

PostgreSQL: read heap page 42 into the buffer pool if it isn't resident (see In-place writes Deep Dive 1), stamp the old tuple's xmax, append a new tuple with a new xmin, dirty the page; add a new B-tree entry pointing at the new TID, dirty that page; append WAL records for both; at COMMIT fsync WAL through the commit record and write pg_xact; ACK (see In-place writes). Both pages are still only in RAM. The WAL protects against a torn in-place page write — data that exists on disk in corrupt form — which is why it additionally needs pageLSN, checkpoints and idempotent redo. The write is paid for later by VACUUM, which must prove no snapshot can see the dead tuple before reclaiming it (see VACUUM and free space). Latches are required because a concurrent split cannot be versioned — after a split there is exactly one correct structure (see Leaf traversal and latches).

Question 2

A colleague reports that disk usage on a RocksDB cluster is climbing with no growth in data, and separately that a PostgreSQL table has bloated 4× overnight. Why is this the same incident, mechanically?

Show answer

Both engines defer all reclamation on the same question — "can any live reader still see this?" — and both answer it by pinning a value that a long-lived reader holds open.

In RocksDB, an in-flight read pins a SuperVersion (see Memtable, flush and ref-counting), which keeps its memtables and its Version's SSTable files alive; and it holds a snapshot sequence number in the snapshot list, which compaction consults once per job to decide the oldest version it may drop (see Concurrency, tombstones and compaction). A long scan therefore keeps whole generations of state resident and forces compaction to retain stale versions.

In PostgreSQL, a long-running (even idle) transaction keeps its xmin registered in the ProcArray, pinning OldestXmin low (see VACUUM and free space). VACUUM still runs — it simply cannot prove any row deleted after that snapshot is dead, so it removes nothing from the heap or the indexes.

Same mechanism, same fix: bound reader lifetime. The diagnostic tell in both cases is that the background job appears healthy while making no progress.

Question 3

Someone proposes raising the SSTable block size from 4 KB to 64 KB "so the filesystem has to do less logical-to-physical translation work per lookup." What is right and what is wrong about that reasoning?

Show answer

Wrong: block size has zero bearing on how bytes get located on disk. The engine only ever issues "read N bytes at logical offset X of this file"; the VFS splits it into 4 KB pages, and the filesystem translates each to a physical block via that file's extent map — machinery that is identical at any block size and entirely owned by the filesystem (see SSTables and sparse indexes). The extent map is also cached in the inode after first access, and an SSTable written as one sequential flush usually lands in contiguous extents anyway, so the block layer collapses several logical pages into one physical I/O regardless.

Right, but for different reasons: 64 KB blocks shrink the sparse index from ~200 KB to ~12 KB per 100 MB SSTable and compress better (see Numbers on disk). The real cost is a longer in-block sequential scan per lookup, which is why 4 KB suits point-lookup OLTP and 64 KB suits scan-heavy OLAP. Also worth correcting: "one block = one disk I/O" was never true — blocks are variable-size and not page-aligned, so a read typically triggers 1–2 page fetches, and an oversized value can produce a block far above target (see SSTables and sparse indexes).

Question 4

Why must VACUUM remove index entries before freeing heap slots — and why does an LSM engine need no analogous ordering rule?

Show answer

Because an index entry is only key → TID and carries no visibility information whatsoever (see Heap and index, In-place writes Deep Dive 3). It cannot tell a live pointer from a stale one; it simply trusts that its TID names a real, current row. Free the heap slot first, let the FSM hand it to an unrelated new row, and a concurrent reader following the still-present index entry lands on that slot and silently reads the wrong row — with nothing in the index able to detect the mismatch. So the pointer must die before the thing it points at could mean something else (see VACUUM and free space).

An LSM engine has no equivalent problem because nothing is ever reused in place. A deleted key is a new tombstone entry at a higher sequence number (see Concurrency, tombstones and compaction), files are immutable, and space is reclaimed only by writing an entirely new merged file and then dropping the old ones once no SuperVersion references them (see Memtable, flush and ref-counting). There is no slot that can be recycled underneath a reader, so there is no ordering constraint to get wrong.

Question 5

PostgreSQL's visibility check needs three values (xmin, xmax, xip[]); RocksDB's needs one (seq ≤ snapshot). Is RocksDB's MVCC simply weaker, or is something structurally different?

Show answer

Structurally different. xip[] exists to describe one specific gap: PostgreSQL assigns an XID when a transaction first writes, but that transaction may commit much later, in any order relative to other in-flight transactions. So an XID inside the xmin–xmax range is ambiguous — it might be committed or still running — and xip[] is the list that disambiguates (see MVCC and visibility).

RocksDB has no such gap: sequence numbers are handed out only at the moment a write is fully applied to the memtable, through a serialized write path. The instant a seq exists, it is already committed and visible. There is no state where seq=150 exists uncommitted while seq=160 is committed — so seq ≤ snapshot is a complete check, not an approximation (see MVCC: LSM vs B-tree).

What RocksDB genuinely doesn't provide is full ACID transaction isolation — there is no notion of a transaction that takes an identifier, does work, and then aborts. It gives consistent point-in-time reads. That is the real difference; the number of fields is a symptom, not the cause.

Question 6

A key-not-found lookup that used to take <1 ms now takes 60 ms. Bloom filters are enabled and configured at 10 bits/key. Where is the time going, and which subsystem is actually at fault?

Show answer

File count. A filter's ~1% false-positive rate is paid per SSTable consulted, so if compaction has fallen behind and the table is sitting at ~1,500 files, a miss triggers ~15 "probably present" answers — each a real sparse-index probe plus a block read, ~4–5 ms apiece on spinning disk (see Numbers on disk). That is the 60 ms. Compact down to ~150 files and the same lookup drops to ~1.5 spurious reads, and leveled compaction's per-level key-range check skips most files before a filter even runs — back to <5 ms. (With tiny records the filters themselves can also outgrow RAM — ~12 MB per SSTable at 10-byte records — which produces the same symptom by a second route.)

The subsystem at fault is compaction throughput (see Compaction strategies), not the read path or the filter sizing. File count is the output of compaction keeping up, and it is also what determines whether the Bloom filters part's mechanism works at all. The corollary worth internalizing: in an LSM engine, "reads got slow" is very often a background-write-work problem — and if writes have also started stalling (see Memtable, flush and ref-counting backpressure), that's confirmation rather than a second, separate incident.

Question 7

An Elasticsearch cluster's p99 search latency has tripled; deleted_docs is 22% of the index and segment count per shard is in the hundreds. A colleague proposes raising the refresh interval from 1 s to 30 s "to reduce indexing overhead." Separately, the same team's PostgreSQL LIKE '%…%' queries have become intermittently slow since a GIN trigram index was added. What single mechanism explains all three, and is the refresh-interval change the right fix?

Show answer

One mechanism: an inverted index is maintained as an LSM tree (see Full-text indexes), so every symptom here is a Part I symptom under a translated name.

A search queries every segment, so latency scales with segment count exactly as the 1,500-SSTable lookup in Q6 did — segments are SSTables (see SSTables and sparse indexes), and hundreds of them is the same incident as hundreds of un-compacted files (see Numbers on disk). deleted_docs at 22% is not a separate problem either: a Lucene delete only clears a liveDocs bit, and the space comes back only when a merge rewrites the segment — the Concurrency, tombstones and compaction part's tombstone bloat, waiting on the Compaction strategies part's background job.

The refresh-interval change is correct but partial, and it is not the lever. Fewer, larger segments do reduce merge pressure and segment count going forward — the same trade as sizing a memtable in the Memtable, flush and ref-counting part — but it is bought with 30 s of visibility lag, and it does nothing about the hundreds of segments already on disk. The actual fault is merge throughput, precisely as Q6's fault was compaction throughput; the fix is to let merging catch up (and to stop treating _forcemerge as free — it is a manual full compaction, with a full rewrite's I/O).

The PostgreSQL case is the same problem arriving from the other side. GIN's pending list is a memtable: unsorted, appended to, and scanned linearly by every query on top of the tree search. And its flush is a foreground stall charged to whichever backend's INSERT happens to cross gin_pending_list_limit — the Memtable, flush and ref-counting part's write stall aimed at one unlucky transaction instead of applied as backpressure to all of them. Intermittent, unexplained-by-the-plan latency is the signature.