Skip to content

Merkle Trees, Read Repair, Anti-Entropy & Tombstones ​

"To detect the inconsistencies between replicas faster and to minimize the amount of transferred data, Dynamo uses Merkle trees." — DeCandia et al., Dynamo: Amazon's Highly Available Key-value Store, SOSP 2007, section 4.7

Summary: Replicas that accept writes independently drift apart; a store converges them on three paths: hints on the write path, read repair on the read path, and Merkle-tree anti-entropy repair in the background, and it can only do that safely for deletes if a delete is itself data (a tombstone) that lives long enough to reach every replica. Focus: The Merkle (hash) tree from Merkle 1979 (leaves, inner nodes, root hash, branching factor, depth, audit path); inclusion and consistency proofs (RFC 6962 / RFC 9162 Certificate Transparency); content addressing in Git; anti-entropy from Demers et al. 1987 and Dynamo section 4.7; Cassandra full vs incremental repair, repaired and unrepaired SSTables, anticompaction, nodetool repair options, subrange repair, Reaper and Auto Repair; Riak active anti-entropy and ScyllaDB row-level repair; read repair with digest requests, digest mismatch, blocking vs NONE, and the removal of read_repair_chance in Cassandra 4.0; hinted handoff and max_hint_window; tombstones (delete markers, death certificates), resurrection and zombie data, gc_grace_seconds, tombstone thresholds and TombstoneOverwhelmingException, range and TTL tombstones, compaction that drops them; Kafka compaction tombstones and delete.retention.ms; Redis Streams XDEL; soft deletes vs tombstones in SQL and Laravel (SoftDeletes, Prunable, model:prune); client sync (CouchDB replication, Merkle sync endpoints, rsync rolling checksums); repair and tombstone observability; with a Go Merkle library and replica simulator, SQL and Laravel 13 code, and a lab. Learning goal: Explain why a Merkle tree makes the cost of comparing two replicas proportional to the differences rather than the data, verify an inclusion proof by hand, pick the right convergence mechanism for each kind of drift, and design deletes (tombstone, grace period, repair cadence, pruning) so that deleted data never comes back, in Cassandra, Kafka, PostgreSQL and an offline-first Laravel API.

This chapter belongs to the Distributed Systems Primitives group and owns the repair and delete machinery that leaderless and eventually consistent systems run underneath their consistency promises. The hash functions themselves (SHA-2, BLAKE3, CRC) are taught in Checksums & Hashing; the CAP choice that makes divergence possible in CAP & PACELC; quorum topologies and conflict resolution in Replication Topologies; the formal models in Consistency Models; how membership and failure detection spread in Gossip Protocols; concurrent versions in Vector Clocks; mergeable values in CRDTs; LSM storage and compaction internals in Storage Engines; Cassandra operations in depth in Cassandra & ScyllaDB in Depth and Wide-Column & Key-Value at Scale; engine-level eventual consistency in Eventual Consistency in Database Systems; content-addressable blob storage in Object Storage; Kafka log compaction as a broker feature in Kafka in Depth; erasure in immutable logs in Messaging Security.

Page map ​

If you are looking forGo to
The whole page in three tablesEverything in one minute
Why replicas drift and why deletes are the hard partWhy it exists
Merkle 1979, Demers 1987, rsync, Dynamo 2007, RFC 6962Where it comes from
What a hash tree is and how two trees are comparedMerkle tree, Shape: branching factor and depth
Proving one record is in a log, proving a log only grewInclusion proof, Consistency proof
Git objects, certificate transparency, blockchainsContent addressing, Certificate Transparency
Background repair between replicasAnti-entropy, Repair in products
Full vs incremental, repaired SSTables, anticompactionFull and incremental repair
nodetool repair, -pr, subranges, Reaper, Auto RepairRunning repair
Digest requests, digest mismatch, blocking read repairRead repair, read_repair_chance
Hints and the hint windowHinted handoff
Delete markers, zombies, gc_grace_secondsTombstones, Resurrection
Tombstone warnings, failures, range and TTL tombstonesTombstone overhead, Kinds of tombstones
Kafka null values, delete.retention.ms, Redis XDELTombstones in logs
deleted_at, SoftDeletes, PrunableSoft delete vs tombstone
Offline clients, CouchDB, rsyncClient sync protocols
What to graph and alert onObservability
Formulas, knobs, error messagesMechanics
CodeGo, Laravel
Incidents and their fixesSolving the classic problems
Which mechanism and which delete strategy whenChoosing
From one process to many regionsIn architecture
Run it yourselfLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The three convergence paths (Cassandra names, Dynamo origin).

MechanismRuns onFixesDoes not fixMain knob
Hinted handoffWrite path: the coordinator keeps the write for a down replica and replays it laterShort outages (restarts, maintenance)Outages longer than the hint window; lost hint files; data that was never written to the coordinatormax_hint_window (default 3h), hinted_handoff_enabled
Read repairRead path: digest mismatch among the replicas a read contactedHot keys that are read at a consistency level above ONEKeys nobody reads; replicas the read did not contactTable option read_repair = BLOCKING (default) or NONE
Anti-entropy repairBackground: Merkle trees per token range, stream only the differencesEverything, including cold data and long outagesNothing, if it runs often enough; it is the only guaranteenodetool repair (incremental default, --full), Reaper, Auto Repair

Deletes in replicated and log-structured systems.

ProductWhat a delete writesHow long the marker livesWhat removes itWhat goes wrong
Cassandra, ScyllaDBA timestamped tombstone (cell, row, range or partition)gc_grace_seconds per table, default 864000 (10 days)Compaction, once the grace period passed and all older data is in the same compactionReplica not repaired within the grace period: the row is resurrected (zombie)
Kafka (compacted topic)A record with a key and a null valuedelete.retention.ms, default 86400000 (1 day)The log cleanerA consumer that lags more than delete.retention.ms misses the delete
CouchDBA new revision with _deleted: trueUntil purgedPOST /{db}/_purgeA purged id is no longer replicated as deleted
Redis StreamsXDEL marks the entry deleted inside its macro nodeUntil every entry in the node is deletedMemory reclaimed when the whole node is emptyNo replicated delete marker exists for consumers; a consumer group simply does not see the entry
PostgreSQL / MySQL with soft deleteUPDATE ... SET deleted_at = now()Your retention policyA scheduled DELETE in batchesForgetting WHERE deleted_at IS NULL; pruning before every consumer has synced
Laravel EloquentSoftDeletes: delete() sets deleted_atYour prunable() queryphp artisan model:prune (force-deletes soft-deleted models that match)Pruning shorter than the longest offline client

Merkle trees outside databases.

WhereLeavesWhat the root (or a hash) buysProof used
Dynamo, Cassandra, Riak repairHashes of the data in a key or token rangeTwo replicas compare one hash and descend only into differing rangesTree diff
Certificate Transparency (RFC 6962)`SHA-256(0x00entry)` per logged certificate
GitBlob objects (file contents), trees (directories), commitsA commit id names the whole snapshotContent address: same content, same id
Bitcoin-style blockchainsTransaction hashesThe block header commits to every transactionInclusion path (simplified payment verification)
rsyncPer-block weak rolling checksum + strong checksumOnly unmatched blocks are sentNot a tree: a flat list of block checksums
CouchDB replicationNone: a changes feed and checkpoints_revs_diff asks which revisions the target lacksNot a tree: sequence checkpoints
Three ways replicas converge: write path, read path, backgroundcoordinatorwrite x, RF=3replica n3 downstore hint locallyn3 returnsreplay hintdown past hint windowno hint: needs repairfull read + digestsCL replicasdigest mismatchfetch full datanewest timestamp winsmerge cellsblocking writeto stale, then replybuild Merkle treesone per token rangecompare treeswith each replicastream rangesthat differanticompactionrepaired / unrepairedWrite pathhinted handoffreach: best effort, hoursRead pathread repairreach: only keys that are readBackgroundanti-entropy repairreach: everything, incl. cold dataCassandra: hints and read repair are best effort; only full or incremental repair guarantees convergence.

The picture is the whole page in three lanes. Hints are cheap and fast but bounded by the hint window; read repair is free but only touches what is read; Merkle-tree repair is expensive but is the only path that guarantees every replica eventually holds every write and every delete. Tombstones are what make the delete case work on all three paths.

Why it exists ​

A leaderless store accepts a write when W of N replicas acknowledge it. The others may be restarting, overloaded or partitioned, so some replicas miss some writes. Cassandra's own documentation says it plainly: "Hints attempt to inform a node of missed writes, but are a best effort, and aren't guaranteed to inform a node of 100% of the writes it missed. These inconsistencies can eventually result in data loss as nodes are replaced or tombstones expire." Something has to find those differences and fix them, and it has to do so without copying the whole dataset between every pair of replicas every night.

Deletes are the hard part. A replica that missed an update holds an older value; timestamps say which is newer. A replica that missed a delete holds a value, and the others hold nothing. "Nothing" has no timestamp, so the repair process sees one replica with data and two without, and copies the data back. Demers et al. described this in 1987: "the propagation mechanism will spread old copies of the item from elsewhere in the database back to the site where we have deleted it." The fix is to make a delete into data (a death certificate, a tombstone) and keep it until every replica has seen it.

Cheap convergenceGuaranteed convergence
Hints and read repair onlyScheduled anti-entropy repair
No background I/OReads the data on every replica to build trees, streams differences
Fixes what was written recently or read recentlyFixes everything, including cold data
Deleted data can come back after a long outageDeletes stay deleted if repair runs within the grace period
Good for caches and data you can rebuildRequired for anything you delete and must not see again

The everyday picture used through this page: three branch offices keep copies of the same member register. Every evening each office writes the total of every page on a summary card, and every page total is also summed into one number for the whole book. Comparing two books starts with that one number; if it matches, nobody opens the books. If it differs, they compare the section totals, then the page totals, and only then the lines on the one page that differs. When a member leaves, the office does not tear out the line: it writes "resigned on 3 May" in red, because a torn-out line looks exactly like a line the other offices never had, and they would helpfully copy it back. After a month, when every office has surely seen the red line, the line and the note can both be removed.

Three common misunderstandings, up front ​

  1. "Quorum reads and writes make repair unnecessary." Quorums make a single read likely to see the latest acknowledged write. They do not copy that write to the replicas that missed it; a later failure of the replicas that have it, or a delete that one replica missed, still loses or resurrects data. Cassandra: hints and read repair "are best effort and not an alternative to performing full repair."
  2. "A Merkle tree is a security feature." In repair it is a bandwidth and disk-read optimisation: Dynamo says Merkle trees "minimize the amount of data that needs to be transferred for synchronization and reduce the number of disk reads performed during the anti-entropy process." The security use (tamper-evident logs, inclusion proofs) is a different application of the same structure.
  3. "Deleting a row deletes it." In Cassandra, ScyllaDB, Kafka compaction, CouchDB and every LSM engine, a delete is a write. It costs space, slows reads that scan over it, and must be kept long enough, then removed by compaction. "Cassandra treats a deletion as an insertion, and inserts a time-stamped deletion marker called a tombstone."

Where it comes from ​

text
     Year   Who / what                                   What it added
1    1979   Ralph Merkle, "A Certified Digital           "Tree authentication": H(i,j,Y) built by divide and conquer;
            Signature" (published Crypto '89)            root R; authentication path of log2 n hashes
2    1987   Demers et al., "Epidemic Algorithms for      Anti-entropy and rumor mongering for the Xerox Clearinghouse;
            Replicated Database Maintenance" (PODC)      "death certificates" so deletes are not resurrected
3    1990s  Tridgell & Mackerras, "The rsync             Weak rolling checksum + strong checksum per block;
            algorithm" (tech report)                     send only the blocks the other side lacks
4    2007   DeCandia et al., Dynamo (SOSP)               Sloppy quorum, hinted handoff (4.6), Merkle-tree anti-entropy
                                                         per key range (4.7), read repair
5    1.3    Riak KV 1.3                                  Active anti-entropy: persistent on-disk hash trees, updated
                                                         on every write, rebuilt weekly
6    2013   RFC 6962, Certificate Transparency           MTH with 0x00/0x01 domain separation, audit paths,
            (Experimental, June)                         consistency proofs
7    4.0    Apache Cassandra 4.0                         read_repair_chance removed; table option read_repair
                                                         (BLOCKING / NONE); incremental repair reworked
8    2021   RFC 9162, CT 2.0 (December)                  Obsoletes RFC 6962; exact verification algorithms
9    5.0.8  Cassandra Auto Repair (CEP-37, in 6.0,       Repair scheduler inside Cassandra itself
            backported to 5.0.8)

Merkle (1979). The problem was signing many messages with one-time signatures without storing every public value. His answer: hash the values pairwise up to one root, publish the root, and ship each value with the hashes needed to recompute the root. "The method is called tree authentication because the computation of H(1,n,Y) forms a binary tree of recursive calls." He also noticed the half of the hashes you do not need to send: "to authenticate Y5 only required that we have previously authenticated H(1,8,Y), and that we transmit Y5, H(6,6,Y), H(7,8,Y), and H(1,4,Y)". That list is what RFC 6962 later called the audit path.

Demers et al. (1987). Working on Xerox's Clearinghouse name service, they compared direct mail, anti-entropy and rumor mongering. Anti-entropy is the simplest: "every site regularly chooses another site at random and by exchanging database contents with it resolves any differences between the two." The same paper names the delete problem and the tombstone: "we replace deleted items with death certificates, which carry timestamps and spread like ordinary data," and states the trade-off that gc_grace_seconds still embodies: "increasing the time threshold reduces the risk but increases the amount of space consumed by death certificates." Gossip-based dissemination itself is taught in Gossip Protocols.

rsync. A contrast, not a tree: the receiver sends weak and strong checksums of fixed-size blocks of its file, and the sender slides a rolling checksum over its own file to find matches at any offset. "The algorithm identifies parts of the source file which are identical to some part of the destination file, and only sends those parts which cannot be matched in this way."

Dynamo (2007). Put the pieces together for a production store: sloppy quorums with hinted handoff for transient failures, Merkle trees per key range for "permanent failures", and read repair. It also recorded the operational cost: "when a node joins/leaves the system, the key ranges handled by many nodes change and the Merkle trees for the new ranges need to be recalculated, which is a non-trivial operation to perform on a production system."

Cassandra, Riak, ScyllaDB. Cassandra inherited Dynamo's repair and added sub-range and incremental repair; Riak 1.3 made it continuous with persistent trees; ScyllaDB replaced tree exchange with row-level checksums and set reconciliation. Cassandra 4.0 removed probabilistic background read repair, and Cassandra 6.0 (backported to 5.0.8) ships an in-process repair scheduler.

Certificate Transparency (2013, 2021). Applied Merkle trees to public, append-only logs of TLS certificates, where the root is signed and anyone can demand proofs. RFC 9162 obsoleted RFC 6962 and spelled out the verification algorithms that the Go code on this page implements.

The concept catalogue ​

Each block follows the same order: plain words, the usual wrong belief, a definition, a timeline or request flow, real scenarios, what products do, and the fix.

Merkle tree (hash tree) Must-know ​

In plain words: hash each piece of data; then hash pairs (or groups) of those hashes; keep going until one hash is left. That top hash, the root hash, changes if any piece changes, so two machines can learn "we are identical" by comparing 32 bytes, and if not, find the different piece by comparing a few more hashes on the way down.

Common misunderstanding: "To compare two replicas with a Merkle tree you must send the whole tree." You send one level at a time and only below nodes that differ. Dynamo: "each branch of the tree can be checked independently without requiring nodes to download the entire tree or the entire data set."

Definition: a tree in which every leaf holds the hash of a data block and every inner node holds the hash of its children. Dynamo: "A Merkle tree is a hash tree where leaves are hashes of the values of individual keys. Parent nodes higher in the tree are hashes of their respective children." RFC 6962 fixes one concrete form: MTH({d(0)}) = SHA-256(0x00 || d(0)) for a leaf and MTH(D[n]) = SHA-256(0x01 || MTH(D[0:k]) || MTH(D[k:n])) for n > 1, with k the largest power of two smaller than n. The two prefixes are domain separation: "This domain separation is required to give second preimage resistance."

Anti-entropy: compare roots, descend only where hashes differReplica ArootH(0-3)H(4-7)0-12-34-56-7R0R1R2R3R4R5R6R7Replica B (with R5 inclusion proof)rootH(0-3)H(4-7)0-12-34-56-7R0R1R2R3R4R5R6R7hash differs: ask for childrenhash equal: skip subtreeaudit path for R5: R4, H(6-7), H(0-3)Cost: 1 root + 2 + 2 + 2 = 7 hash comparisons for 8 ranges; with 2^20 ranges and one difference: 1 + 2 x 20 = 41.Only range R5 is streamed. Identical replicas exchange one root hash and stop.
text
     Replica A                               Replica B                       (8 token ranges)
1    send root(A)                    ->      compare with root(B): differ
2    send H(0-3), H(4-7)             ->      H(0-3) equal: skip 4 ranges; H(4-7) differs
3    send H(4-5), H(6-7)             ->      H(6-7) equal; H(4-5) differs
4    send H(R4), H(R5)               ->      R5 differs
5    stream the rows of range R5     <->     both sides merge by timestamp; 7 ranges untouched

Real scenario: a Cassandra node that was down for six hours comes back; anti-entropy between replicas of a 200 GB table finds the few ranges that changed and streams those; a backup verifier compares the root of today's snapshot with yesterday's to prove nothing changed in cold partitions; a mobile app compares one root with the server before downloading anything; a Certificate Transparency monitor checks that a certificate it cares about is in a log without downloading the log.

ProductTree shapeLeavesBuilt when
Dynamo (paper)One tree per key range (virtual node)Hashes of the values of keysMaintained per node; recalculated when ranges move
Apache CassandraOne tree per token range per repair session; resolution bounded by repair_session_spaceHashes of partitions in a sub-rangeDuring repair (validation compaction), then discarded
Riak KV (AAE)Persistent on-disk hash treesObject hashesUpdated in real time on writes; rebuilt weekly by default
ScyllaDBNo tree exchange: row-level checksums with set reconciliationRowsDuring repair
RFC 6962 / RFC 9162 logsLeft-filled binary tree over an append-only list`SHA-256(0x00
GitA tree object per directory (not binary)Blob ids (content hashes)On commit

Fix / how to use it: for replica comparison, build the tree over fixed key or token ranges so both sides have the same shape; for proofs, use the RFC 6962 layout with the 0x00/0x01 prefixes. The merkle and antientropy Go packages in Go do one each.

Shape: leaves, branching factor, depth and resolution Important ​

In plain words: a leaf usually covers a range of keys, not one key. More leaves means you can point at a smaller range that differs (less data streamed), but the tree costs more memory and more hashes to exchange. A wider tree (more children per node) has fewer levels, so fewer round trips, but each step sends more hashes.

Common misunderstanding: "One leaf per key is the most precise, so it is best." With a billion keys that is a billion hashes in memory per range per repair. Cassandra limits the memory instead: repair_session_space defaults to "1/16th of the available heap", and "smaller trees have less resolution, which can lead to over-streaming data."

Definition: for a complete tree with branching factor b and depth d there are b^d leaves. Comparing two trees that differ in k leaves costs at most d round trips and about 1 + k * b * d hash comparisons; identical trees cost one comparison. Streaming cost is the data in the k divergent leaves, so it depends on keys per leaf: with n keys and L leaves, one changed key streams about n / L keys (over-streaming).

text
     One divergent key among 100000 (measured by the Go lab, cmd/aesim)
1    fanout 2,     depth 4   ->     16 buckets:  5 rounds,     9 hashes, 6110 keys streamed
2    fanout 2,     depth 16  ->  65536 buckets: 17 rounds,    33 hashes,    2 keys streamed
3    fanout 16,    depth 4   ->  65536 buckets:  5 rounds,    65 hashes,    2 keys streamed
4    fanout 256,   depth 2   ->  65536 buckets:  3 rounds,   513 hashes,    2 keys streamed
5    fanout 65536, depth 1   ->  65536 buckets:  2 rounds, 65537 hashes,    2 keys streamed (a flat list)

Real scenario: a Cassandra cluster with large partitions sees repairs that stream gigabytes for a handful of changed rows (low resolution: raise repair_session_space or repair smaller subranges); a mobile sync endpoint chooses 256 buckets so that one round trip of 8 KB of hashes finds the changed buckets; a cross-region sync over a 150 ms link prefers a wide tree to keep the number of round trips low.

KnobProductEffect
repair_session_spaceCassandra cassandra.yamlMemory for Merkle trees per table and range; more memory, higher resolution, less over-streaming
concurrent_merkle_tree_requestsCassandraLimits simultaneous tree builds; default 0 (no limit) "can produce OOM"
-st / -et (subrange repair)nodetool repairFewer keys per tree, so higher resolution for the same memory
Number of bucketsYour sync APIOne level of 256 buckets is 8 KB of SHA-256 hashes per comparison

Fix / how to use it: choose leaves by the amount of data you are willing to stream per difference, then choose the fan-out by your round-trip latency. For a server-to-phone sync, two levels of 256 are usually enough.

Inclusion proof (audit path, audit proof) Important ​

In plain words: to convince someone who already trusts the root that one item is in the tree, send the item and the sibling hash at each level on the way up. They recompute the root; if it matches, the item is in the tree. With a million items that is 20 hashes.

Common misunderstanding: "The proof must contain the other items." It contains only ceil(log2 n) hashes; the verifier never sees the other items. The other mistake is trusting a proof without a trusted root: the proof only ties the item to the root you compare against.

Definition: RFC 6962: "A Merkle audit path for a leaf in a Merkle Hash Tree is the shortest list of additional nodes in the Merkle Tree required to compute the Merkle Tree Hash for that tree. ... If the root computed from the audit path matches the true root, then the audit path is proof that the leaf exists in the tree." RFC 9162 section 2.1.3.2 gives the verification loop over leaf_index and tree_size; VerifyInclusion in the merkle package is a line-by-line port. Merkle 1979 called it the "authentication path".

text
     Verify leaf 5 of 8 with audit path [h4, h(6-7), h(0-3)]
1    r = leaf hash of d5
2    5 is odd       -> r = H(0x01 || h4 || r)          = h(4-5)
3    2 is even      -> r = H(0x01 || r || h(6-7))      = h(4-7)
4    1 is odd       -> r = H(0x01 || h(0-3) || r)      = root
5    compare r with the signed root: equal -> leaf 5 is in the tree

Real scenario: a CT log hands a browser a signed certificate timestamp and later an inclusion proof; a ledger service gives auditors a proof that one transaction is in the day's root, which was published; a light blockchain client checks a payment against a block header; a document service proves a contract version existed at a time without revealing other contracts.

Fix / how to use it: tree.InclusionProof(i, size) and merkle.VerifyInclusion(merkle.LeafHash(data), i, size, proof, root). Always hash with the leaf prefix: a verifier that accepts an inner node as a leaf is open to the second preimage attack the prefixes exist to stop.

Consistency proof Good to know ​

In plain words: a log published root R1 when it had m entries and root R2 now that it has n. A consistency proof is a handful of hashes that show the first m entries are unchanged, so the log only appended.

Common misunderstanding: "If every inclusion proof checks out, the log is honest." A log can show different histories to different people (a split view). Consistency proofs between every pair of tree heads you have seen, plus gossip of tree heads between monitors, close that gap.

Definition: RFC 6962 2.1.2: "Merkle consistency proofs prove the append-only property of the tree." The proof is SUBPROOF(m, D[n], true), and "the number of nodes in the resulting proof is bounded above by ceil(log2(n)) + 1." RFC 9162 2.1.4.2 gives the verification loop.

text
     Monitor                                         Log
1    stored: (size 600000, root R1)
2    GET consistency proof 600000 -> 1000000   ->
3                                              <-    15 hashes
4    recompute R1 and R2 from the same hashes
5    both match -> the first 600000 entries were not rewritten

Real scenario: a CT monitor polls tree heads every few minutes; a tamper-evident audit log for an admin console publishes a daily root and must show auditors that last week's entries were not edited; a transparency log for software releases (Go's checksum database uses the same tree construction) lets clients detect a release that was swapped.

Fix / how to use it: keep every tree head you have verified, and on each new one call VerifyConsistency(oldSize, newSize, oldRoot, newRoot, proof). The test TestRewrittenHistoryFailsConsistency shows a log that edited entry 2 failing the check.

Content addressing and Git objects Good to know ​

In plain words: name each piece of data by the hash of its content. The same content always has the same name, a different name means different content, and a directory that lists the names of its children is itself named by a hash: a Merkle tree.

Common misunderstanding: "Git stores diffs." The object model stores whole contents addressed by hash; packfiles compress later. "Git is a content-addressable filesystem. ... at the core of Git is a simple key-value data store."

Definition: Git stores blobs (file contents) and tree objects; "A single tree object contains one or more entries, each of which is the SHA-1 hash of a blob or subtree with its associated mode, type, and filename." A commit points at a root tree, so a commit id commits to every byte of the snapshot. Two repositories that share a commit id share the whole tree beneath it, which is why fetch only transfers objects the other side lacks. The hashing itself is covered in Checksums & Hashing; content-addressable blob stores in Object Storage.

text
     git commit
1    blob   ce0136...  <- "hello\n"                      (file contents; id = SHA-1 of header + content)
2    tree   T1         <- 100644 blob ce0136... README    (directory listing names children by hash)
3    commit C1         <- tree T1, parent C0, author ...
4    edit README -> new blob id -> new tree id -> new commit id; unchanged subtrees keep their ids

Real scenario: deduplicating uploads in an object store by SHA-256; a build cache keyed by the hash of inputs; container image layers addressed by digest; IPFS-style content ids; Git fetch negotiating which objects to send.

Fix / how to use it: when you need "has this changed?" for a hierarchy, hash children and store the child hashes in the parent. When you need "is this exactly that content?", address by a cryptographic hash (SHA-256), not by CRC.

Certificate Transparency (RFC 6962) and blockchains Good to know ​

In plain words: CT logs are public append-only lists of TLS certificates. The log signs its current root (the Signed Tree Head), and anyone can ask for an inclusion proof for a certificate or a consistency proof between two signed roots. Blockchains put a Merkle root of a block's transactions in the block header for the same reason.

Common misunderstanding: "CT and Cassandra use Merkle trees the same way." CT uses them for proofs to untrusting third parties over an append-only list. Cassandra uses them between trusting replicas to find differences in a mutable dataset; the trees are thrown away after each repair and never signed.

Definition: RFC 6962: "Logs use a binary Merkle Hash Tree for efficient auditing." The certificate-transparency.dev overview: "When the log server signs the root Merkle tree it creates a Signed Tree Head (STH)." RFC 9162 (CT 2.0) obsoletes RFC 6962.

text
     CA                    CT log                     Browser                 Monitor
1    submit precert  ->    add leaf, return SCT
2                          later: new STH (size n, root R, signature)
3                                                     cert + SCT ->  check SCT signature
4                                                                            GET inclusion proof, GET consistency(R_old, R)
5                                                                            alarm if a certificate for its domain appears

Real scenario: detecting a mis-issued certificate for your domain; auditing a vendor's software releases through a transparency log; anchoring an internal audit trail by publishing daily roots.

UseTree updatedWho trusts whomProofs
Cassandra / Dynamo repairRebuilt per repairReplicas trust each otherNone, only diff
CT logAppend-onlyNobody trusts the logInclusion + consistency, signed root
Blockchain blockPer blockConsensus on headersInclusion path to the header
GitPer commitSigned tags or trust in the remoteContent ids

Fix / how to use it: if you are building an audit log, the RFC 6962 tree with published (or signed) roots is a better primitive than a hash chain: inclusion proofs are logarithmic, and consistency proofs show append-only growth.

Anti-entropy Must-know ​

In plain words: a background job that makes two replicas compare everything they hold and copy over whatever one has and the other lacks, regardless of whether anyone read or wrote it recently. The Merkle tree only makes the comparison cheap.

Common misunderstanding: "Anti-entropy runs automatically in every Dynamo-style database." In Riak KV, AAE "is enabled by default"; in Apache Cassandra, "since repair can result in a lot of disk and network io, it's not run automatically by Cassandra. It is run by the operator via nodetool" (or by Reaper, or by the Auto Repair scheduler in 6.0 and 5.0.8 if you enable it). A Cassandra cluster with nobody running repair has no anti-entropy at all.

Definition: Demers et al.: "every site regularly chooses another site at random and by exchanging database contents with it resolves any differences between the two. Anti-entropy is extremely reliable but requires examining the contents of the database and so cannot be used too frequently." Dynamo 4.7 makes it range-based: "Each node maintains a separate Merkle tree for each key range ... two nodes exchange the root of the Merkle tree corresponding to the key ranges that they host in common." The repaired values are merged by the store's normal conflict rule (Cassandra: per-cell last-write-wins by timestamp; Dynamo/Riak: vector clocks and siblings; see Vector Clocks).

text
     n1 (owns range R)                      n2 (replica of R)                n3 (replica of R)
1    repair session starts for R
2    request tree for R          ->         read R, build tree T2            read R, build tree T3
3    build T1                    <-         send T2                    <-    send T3
4    compare T1/T2, T1/T3, T2/T3: ranges R.17 and R.230 differ between n1 and n3
5    stream R.17, R.230 between n1 and n3 (both directions); n2 untouched
6    session done; trees discarded (Cassandra) or kept and updated (Riak AAE)

Real scenario: a node was down for a day, longer than the hint window; a disk was replaced and a node rebuilt from a stale backup; a replication factor was increased (Cassandra warns "When increasing replication factor you need to run a full (-full) repair to distribute the data"); a datacenter was cut off for hours; cold data that nobody reads must still have every delete propagated before gc_grace_seconds runs out.

Fix / how to use it: schedule it. Cassandra's documentation gives a starting point: "running an incremental repair every 1-3 days, and a full repair every 1-3 weeks is probably reasonable", and the hard limit: "repair should be run often enough that the gc grace period never expires on unrepaired data."

Merkle-tree repair in Dynamo, Cassandra, Riak and ScyllaDB Must-know ​

In plain words: every leaderless store has some version of the Dynamo scheme, but they differ in whether trees are persistent, how often repair runs, and whether you have to start it.

Common misunderstanding: "Amazon DynamoDB exposes repair like Cassandra." The Dynamo paper describes Amazon's internal store; the DynamoDB service does not document its internal replica synchronization or give you a repair command. What you get is the consistency choice per read (ConsistentRead), discussed in CAP & PACELC. Treat anything about DynamoDB internals as inference.

Definition: the products below compare replicas by hashes over ranges and stream only the differing data; the table is the operational difference.

text
     Cassandra full repair on one node, keyspace shop, table carts
1    nodetool repair --full shop carts
2    [..] Starting repair command #1 ..., repairing keyspace shop with repair options (parallelism: parallel,
         primary range: false, incremental: false, ...)
3    for each token range of this node: replicas build Merkle trees, compare, stream mismatches
4    [..] Repair session ... for range [(-8792657144775336505,-8786320730900698730], ...] finished
5    [..] Repair completed successfully

Real scenario: an operator team runs Reaper against several Cassandra clusters with a weekly full and daily incremental schedule; a Riak cluster relies on AAE plus read repair and never schedules anything; a ScyllaDB cluster uses ScyllaDB Manager or automatic repair on tablets.

ProductTreesWho starts repairIncremental?Notes
Dynamo (paper)Per key range, maintained per nodeThe systemn/aTrees recalculated when membership changes ranges
Apache CassandraBuilt per repair session, discardedOperator: nodetool repair, Reaper, or Auto Repair (6.0; 5.0.8 behind -Dcassandra.autorepair.enable=true)Yes, the default typeSub-range repair raises tree resolution
Riak KVPersistent, on-disk, updated on every writeThe system (AAE on by default)ContinuousTrees "periodically" regenerated, default one week, to catch silent corruption
ScyllaDBRow-level checksums and set reconciliation, not tree exchangenodetool repair, ScyllaDB Manager, or automatic repairYes, on tabletsDocs: run repair more often than gc_grace_seconds if you delete frequently
Amazon DynamoDBNot documentedThe servicen/aInference only

Fix / how to use it: in Cassandra, decide who owns repair (one scheduler per cluster, never two), alert when any table's last successful repair is older than gc_grace_seconds minus a margin, and keep incremental and full repairs on separate cadences.

Full and incremental repair, repaired SSTables and anticompaction Must-know ​

In plain words: a full repair compares all the data in a range. An incremental repair compares only data written since the last incremental repair, then labels it "repaired" so the next run can skip it. That is much cheaper, but anything labelled repaired is never checked again by incremental runs.

Common misunderstanding: "Incremental repair replaces full repair." Cassandra: "once an incremental repair marks data as repaired, it won't try to repair it again. This is fine for syncing up missed writes, but it doesn't protect against things like disk corruption, data loss by operator error, or bugs in Cassandra. For this reason, full repairs should still be run occasionally."

Definition: Cassandra keeps repaired and unrepaired data in separate SSTables: "With anticompaction repaired data is split out into repaired and unrepaired SSTables. To avoid mixing up the data again separate compaction strategy instances are run on the two sets of data." Anticompaction itself: "After repair, the ranges that were actually repaired are split out of the SSTables that existed when repair started." Incremental is the default: nodetool repair; full is nodetool repair --full.

Incremental repair keeps two worlds apart; full repair re-checks bothUnrepaired SSTablesnew writes, flushess1s2s3r1r2r3own compaction instancetombstones kept here whenonly_purge_repaired_tombstonesRepaired SSTablesmarked as repairedown compaction instancenever re-checked byincremental repairincremental repairMerkle trees over unrepaired onlyanticompactionsplit repaired ranges outfull repair (nodetool repair --full): Merkle trees over repaired + unrepairedcatches disk corruption, operator error and bugs; --validate checks repaired data, --preview estimates streaming
text
     Day   Command                      Trees over                    Then
1    1     nodetool repair             unrepaired SSTables            anticompaction: repaired set grows
2    2     nodetool repair             new unrepaired data only       cheap: yesterday's data is skipped
3    7     nodetool repair --full      repaired + unrepaired          catches a bit flip in a repaired SSTable
4    8     (incremental stopped)       -                              old repaired data blocks tombstone purge
                                                                      in newer unrepaired SSTables

Real scenario: a large time-series cluster cuts repair time by an order of magnitude with incremental repair; a team that ran one incremental repair during a test and never again finds tombstones that will not drop, because "if you only run incremental repair once and then never again, you might have very old data in the repaired SSTables that block compaction from dropping tombstones in the unrepaired (probably newer) SSTables"; an operator uses nodetool repair --validate after a suspicious disk event.

OptionWhat it does
nodetool repairIncremental repair of all ranges this node replicates
--full / -fullFull repair
-pr, --partitioner-rangeOnly the node's primary ranges; run on every node to cover the ring once
-st, -etSubrange repair between two tokens
-prv, --preview"builds the merkle trees, and prints the expected streaming activity, but does not actually do any streaming"
-vd, --validateChecks repaired data is in sync; out of sync means run a full repair
-dc, -local, -dcparLimit to datacenters or repair them in parallel
-seqSequential repair (one replica at a time)
-jJob threads, "default: 1, max: 4"
--pullOne-way repair: stream only from the remote node to this node

Fix / how to use it: incremental every one to three days, full every one to three weeks, both finishing well inside gc_grace_seconds. If you stop running incremental repair, run a full repair afterwards and consider nodetool repair --full as the only mode.

Running repair: -pr, subranges, Reaper, Auto Repair Important ​

In plain words: nodetool repair repairs the ranges of the node you run it on, not the cluster. Run it naively on every node and each range is repaired once per replica. Tools exist to split the ring into small pieces, run them a few at a time, and remember what is done.

Common misunderstanding: "One nodetool repair repairs the cluster." Cassandra: "The repair command repairs token ranges only on the node being repaired; it does not repair the whole cluster." And "By default, repair operates on all token ranges replicated by the node on which repair is run, causing duplicate work when running it on every node. Avoid duplicate work by using the -pr flag".

Definition: a full cluster repair is nodetool repair -pr "on each node in each datacenter in the cluster." Reaper "is a centralized, stateful, and highly configurable tool for running Apache Cassandra repairs for multi-site clusters" that schedules repairs "at keyspace, table, or even token range level" and "prevents overlapping repairs". Cassandra Auto Repair "is a fully automated scheduler that provides repair orchestration within Apache Cassandra", keeps history in system_distributed.auto_repair_history, and "splits token ranges into subranges, with necessary retries to handle transient failures."

text
     Reaper, weekly schedule for keyspace shop (expected behaviour)
1    split the ring into segments (subranges)
2    run segment 1 on its replicas; at most one segment per node at a time
3    segment fails -> retry later; progress kept in Reaper's backend
4    all segments done -> record completion; next run in 7 days
5    alert if the run does not finish inside gc_grace_seconds

Real scenario: a 60-node cluster where a single full repair of one node took a day; moving to subrange repair keeps each session small enough to retry; a cluster upgraded to 5.0.8 enables Auto Repair and retires cron jobs; a team running both Reaper and cron finds overlapping repairs doubling disk I/O.

Fix / how to use it: one scheduler, subrange segments, -pr if you script it yourself, and a monitored deadline equal to gc_grace_seconds minus slack (Cassandra's own example: "With a default gc grace period of 10 days, repairing every node in your cluster at least once every 7 days will prevent this").

Read repair: digest requests, digest mismatch, blocking Must-know ​

In plain words: when a read asks several replicas, the coordinator gets the full data from one and just a hash (digest) from the others. If the hashes agree, done. If not, it fetches full data, picks the newest version, writes it to the replicas that were behind, and only then answers.

Common misunderstanding: "Read repair fixes all replicas of the key." It repairs only replicas involved in that read: "If read repair is performed it is made only on the replicas that are not up-to-date and that are involved in the read request." At ONE and LOCAL_ONE there are no digest requests and no read repair at all.

Definition: Cassandra: "A digest read request is not a full read and only returns the hash value of the data." On a mismatch, the coordinator sends full reads, reconciles by timestamp, and with read_repair = 'BLOCKING' (the default) "the read will block on writes sent to other replicas until the CL is reached by the writes." That gives "monotonic quorum reads": "in 2 successive quorum reads, it's guaranteed the 2nd one won't get something older than the 1st one". NONE reconciles for the response but writes nothing back, which keeps partition-level write atomicity instead. Riak calls read repair "a passive anti-entropy mechanism"; Dynamo: "This process is called read repair because it repairs replicas that have missed a recent update at an opportunistic time and relieves the anti-entropy protocol from having to do it."

text
     Client       Coordinator                    R1 (fresh)           R2 (stale)       CL = QUORUM, RF = 3
1    SELECT ->    full read to R1          ->    data v2 (ts 20)
2                 digest read to R2        ->                         digest(v1)
3                 digest(v2) != digest(v1): digest mismatch
4                 full read to R2          ->                         data v1 (ts 10)
5                 newest = v2; write v2    ->                         applied, ack
6    <- v2        (BLOCKING: reply only after the repair write reached CL)

Real scenario: a user profile read at LOCAL_QUORUM silently fixes the replica that missed the last update; a read-heavy table converges hot keys within minutes of an outage while cold keys stay divergent until repair; a table written in multi-row batches but read one row at a time sets read_repair = 'NONE' because "read repair can break write atomicity when data is read at a more granular level than it is written."

Consistency level (Cassandra)Digest requestsRead repair
ONE, LOCAL_ONENoneNot performed
TWO, THREEYesPerformed on mismatch
QUORUM, LOCAL_QUORUMYesPerformed on mismatch
ALLYesPerformed on mismatch

Fix / how to use it: keep BLOCKING unless you have the batch-atomicity case; do not rely on read repair for cold data; read at QUORUM/LOCAL_QUORUM where you want both repair and monotonic reads.

read_repair_chance and its removal Important ​

In plain words: older Cassandra versions could also repair a random fraction of reads in the background, even at ONE, by asking all replicas. It cost extra reads and gave no guarantee, so it was removed.

Common misunderstanding: "Setting read_repair_chance = 1.0 is a cheap substitute for repair." It never reached cold data, added load to every read it chose, and in Cassandra 4.0 the option no longer exists: "Background repair has been removed. dclocal_read_repair_chance and read_repair_chance table options have been removed and are now rejected." (CASSANDRA-13910).

Definition: in 3.x, read_repair_chance (all datacenters) and dclocal_read_repair_chance (local) set the probability of a background, non-blocking read repair; 4.0 replaced them with the read_repair table option (BLOCKING / NONE).

text
     Upgrade from Cassandra 3.11 to 4.x
1    schema has WITH dclocal_read_repair_chance = 0.1
2    after upgrade, CREATE/ALTER with that option is rejected
3    remove the option from schema migration scripts; set read_repair if needed
4    replace any "background repair" assumption with scheduled repair

Real scenario: an infrastructure-as-code repository fails after a Cassandra 4.0 upgrade because its table definitions still set read_repair_chance; a capacity plan that counted on background read repair to fix cold data has to add Reaper.

Fix / how to use it: delete the options from schema scripts; use read_repair only to choose BLOCKING or NONE.

Hinted handoff and the hint window Must-know ​

In plain words: when a replica is down, the coordinator keeps the write in a local "hint" file and delivers it when the replica returns. It only does this for a few hours; after that it stops, and the replica must be fixed by repair.

Common misunderstanding: "With hints enabled, a node that comes back is consistent." Only if it was down less than max_hint_window, the hint files survived on the coordinators, and delivery finished. Cassandra: "Hints are best effort, however, and do not guarantee eventual consistency like anti-entropy repair does." A delete missed during an outage longer than the window is exactly the case that resurrects data.

Definition: Dynamo 4.6: a write for down node A goes to D with "a hint in its metadata that suggests which node was the intended recipient", and "Upon detecting that A has recovered, D will attempt to deliver the replica to A" (a sloppy quorum). Cassandra stores hints on the coordinator's disk, generated for a dead host for at most max_hint_window (default 3h): "After it has been dead this long, new hints for it will not be created until it has been seen alive and gone down again." Hints are also written for writes that time out (write_request_timeout, default 2000ms). "Since hints contain the original unmodified mutation timestamp, hint application is idempotent and cannot overwrite a future mutation."

text
     t     Coordinator                          replica_2                         (CL = LOCAL_QUORUM, RF = 3)
1    t0    write to replica_1, 2, 3             restarting
2    t1    2 acks -> success to client
3    t2    write timeout (2s): store hint for replica_2 on local disk
4    t3                                         back up, gossips "alive"
5    t4    replay hints                   ->    applies the missed mutation
     ---- if replica_2 is down longer than max_hint_window (3h) ----
6          no new hints; replica_2 stays out of sync until read repair or anti-entropy repair

Real scenario: a rolling restart of a cluster: hints cover every node's few minutes of downtime; a node with a failed disk is out for two days: hints stop after three hours and repair must run; hints pile up on coordinators during a long outage and fill disks (max_hints_size_per_host caps them).

Setting (Cassandra)DefaultMeaning
hinted_handoff_enabledtrueGenerate hints at all
max_hint_window3hStop creating hints for a host down longer than this
hinted_handoff_throttle1024KiBPer delivery thread, scaled down by cluster size
max_hints_delivery_threads2Raise for multi-datacenter clusters
max_hints_file_size128MiBSize of one hints file
max_hints_size_per_host0MiB (no limit)Stop hinting a host once its hint files reach this size
hinted_handoff_disabled_datacentersunsetDatacenters that do not hint
auto_hints_cleanup_enabledfalseRemove expired and orphaned hint files

Fix / how to use it: treat hints as latency reduction for short outages. Any outage longer than max_hint_window triggers a repair of that node (nodetool repair on it, or let the scheduler pick it up); nodetool statushandoff, getmaxhintwindow and setmaxhintwindow inspect and adjust at runtime.

Tombstones (delete markers) Must-know ​

In plain words: instead of removing a value, write a small record that says "deleted at time T". It replicates, gets repaired and wins over older values exactly like a normal write. Later, when every replica must have seen it, compaction throws away both the marker and the data it covers.

Common misunderstanding: "A tombstone is only a Cassandra quirk." It is the general answer for any system where replicas or log segments merge later: Demers' death certificates, Cassandra and ScyllaDB tombstones, Kafka null-value records, CouchDB _deleted revisions, LSM engines (RocksDB, LevelDB) delete markers in SSTables, and soft-delete columns in SQL tables that other systems sync from. The storage-engine side is in Storage Engines.

Definition: Cassandra: "Cassandra treats a deletion as an insertion, and inserts a time-stamped deletion marker called a tombstone. The tombstones go through Cassandra's write path, and are written to SSTables on one or more nodes. The key feature difference of a tombstone is that it has a built-in expiration date/time." "Once an object is marked as a tombstone, queries will ignore all values that are time-stamped previous to the tombstone insertion."

text
     Writer            n1                     n2                     n3 (down)
1    INSERT x  ->      x@10                   x@10                   x@10
2    DELETE x  ->      x@10, T@20             x@10, T@20             (missed)
3    read QUORUM n1+n2: T@20 newer than x@10 -> "no row"
4    n3 back, repair: n3 receives T@20 -> x@10 shadowed everywhere
5    after gc_grace_seconds and a compaction that includes x@10 and T@20: both removed

Real scenario: removing a user's session rows; deleting a cart after checkout; GDPR erasure in a wide-column store (the data is not gone until the tombstone is compacted with it); a "queue" table in Cassandra whose consumers delete processed rows and soon read through millions of tombstones.

EngineDelete writesPurged byPurge condition
CassandraTombstone (cell, row, range, partition), or TTL expiryCompactionOlder than gc_grace_seconds and every SSTable with older data for that partition in the same compaction; optionally only repaired data (only_purge_repaired_tombstones)
ScyllaDBTombstoneCompactiongc_grace_seconds; ScyllaDB's repair docs: repair more often than it if you delete frequently
RocksDB / LevelDB (LSM)Delete marker in the memtable and SSTables (see Storage Engines)CompactionNo older version of the key left below it
Kafka compacted topicRecord with key and null valueLog cleanerAfter delete.retention.ms
CouchDBNew revision _deleted: true_purgeExplicit request
PostgreSQL soft deletedeleted_at setYour scheduled DELETEYour retention policy

Fix / how to use it: model deletes as writes wherever replicas, caches or clients merge state later, and give every marker a deliberate lifetime that is longer than the longest time any replica or consumer may be out of touch.

Resurrection, zombie data and gc_grace_seconds Must-know ​

In plain words: if a tombstone is removed before every replica has received it, the replica that never saw the delete still has the old value, and the next repair or read copies it back. The deleted data is alive again: a zombie.

Common misunderstanding: "gc_grace_seconds is a performance knob; lower it to get rid of tombstones faster." It is a correctness contract: it is the maximum time you allow between a delete and the moment every replica has it. "If a node remains down or disconnected for longer than gc_grace_seconds, its deleted data will be repaired back to the other nodes and reappear in the cluster."

Definition: Cassandra: "If the tombstoned object has already been deleted from the rest of the cluster before that node recovers, Cassandra treats the object on the recovered node as new data, and propagates it to the rest of the cluster. This kind of deleted but persistent object is called a zombie." "To prevent the reappearance of zombies, Cassandra gives each tombstone a grace period. The grace period for a tombstone is set with the table property WITH gc_grace_seconds. Its default value is 864000 seconds (ten days)". The rule that follows: complete a repair of every replica within gc_grace_seconds. cassandra.yaml (5.0) has an optional startup check, check_data_resurrection, "to fail startup if the node is down for longer than gc_grace_seconds".

Why deletes need tombstones, and why tombstones need repair within gc_grace_seconds1. write x (RF=3)2. DELETE x, n3 down3. later4. n3 back, repairxxx--x--xxxxn1n2n3zombie: x is backxxxx+Tx+Txx+Tx+Txx+Tx+Tx+Tn1n2n3stays deletedxxxx+Tx+Tx--xxxxn1n2n3zombie: x is backHard deleteTombstone, repairedwithin gc_graceTombstone purgedcompacted after gc_gracex+T = row plus a newer tombstone (the tombstone wins). Dashed = replica down. Cassandra defaultgc_grace_seconds = 864000 (10 days); repair every node within that window.
text
     Day   n1, n2                                 n3                         gc_grace_seconds = 1 day
1    0     x                                      x
2    0     (n3 goes down)                         down
3    0.2   DELETE x -> T                          misses it; down > max_hint_window, no hint
4    1.2   compaction: T older than grace -> x and T purged
5    2.2   n3 back: still has x
6    2.2   repair: n1, n2 have nothing, n3 has x -> x streamed back: zombie

Real scenario: a shopping cart emptied at checkout reappears a week later after a node was rebuilt from an old snapshot; a revoked permission row comes back; "unsubscribed" users start receiving email again; a team lowered gc_grace_seconds to 1 hour on a table to fix tombstone warnings and then a 2-hour node outage resurrected data.

Fix / how to use it: keep gc_grace_seconds larger than your repair cycle plus slack; repair any node that was down longer than max_hint_window; never bring back a node that was out longer than gc_grace_seconds without wiping and rebuilding it (or enable check_data_resurrection); on tables with only TTL'd, never-deleted, never-updated data, a lower grace is safe because every replica expires the data independently.

Tombstone overhead, warnings and failures Important ​

In plain words: a read has to skip over every tombstone between the rows it wants, and it must carry those tombstones back to the coordinator so other replicas learn about the deletes. A partition with a hundred thousand tombstones makes a simple SELECT slow, uses heap, and eventually fails.

Common misunderstanding: "If I delete rows, reads get faster." Until compaction removes the tombstones, the opposite happens: the rows are still there plus markers. Cassandra's yaml comment links "cassandra-anti-patterns-queues-and-queue-like-datasets" for exactly this reason.

Definition: "When executing a scan, within or across a partition, we need to keep the tombstones seen in memory so we can return them to the coordinator, which will use them to make sure other replicas also know about the deleted rows. With workloads that generate a lot of tombstones, this can cause performance problems and even exhaust the server heap." tombstone_warn_threshold (default 1000) logs a warning; tombstone_failure_threshold (default 100000) aborts the query with TombstoneOverwhelmingException. Guardrails partition_tombstones_warn_threshold / partition_tombstones_fail_threshold (default -1, disabled) check partitions when SSTables are written.

text
     Queue-like table: messages(queue_id, msg_id) consumed and deleted
1    producer inserts 200000 messages into partition q1
2    consumers delete each message after processing -> 200000 row tombstones in q1
3    SELECT * FROM messages WHERE queue_id = 'q1' LIMIT 10
4    replica scans tombstones before finding 10 live rows
5    > 1000:   WARN  Read 10 live rows and 1500 tombstone cells for query ...; token ... (see tombstone_warn_threshold)
6    > 100000: Scanned over 100001 tombstones during query '...' (last scanned row token was ... and partion key was (...)); query aborted

Real scenario: a job queue or "inbox" modelled as a Cassandra partition; a time-ordered partition where old rows are deleted from the front, so every read of the newest rows starts with a wall of tombstones; collection columns (sets, maps) overwritten wholesale, which writes a tombstone for the previous collection each time.

Fix / how to use it: do not model queues in Cassandra (use a broker, see Messaging Fundamentals); use time buckets in the partition key and drop whole buckets (one partition tombstone, or TTL with Time Window Compaction Strategy); read with a clustering range that starts after the deleted region; watch TombstoneScannedHistogram; do not raise the failure threshold as a fix.

Kinds of tombstones: cell, row, range, partition, TTL Important ​

In plain words: the size of the marker depends on what you deleted. One column value, one row, a slice of rows in a partition, a whole partition, or data that simply expired (TTL) each leave a different kind of marker; one marker can hide millions of rows or one marker per row can bury a partition.

Common misunderstanding: "TTL avoids tombstones." Expired data is converted into tombstones: "After this amount of time has ended, Cassandra marks the object with a tombstone, and handles it like other tombstoned objects." TTL avoids the delete round trip, not the marker.

Definition: Cassandra CQL: "A range of rows may be deleted using an inequality operator (such as >= )", which writes one range tombstone covering the slice; DELETE FROM t WHERE pk = ? writes one partition tombstone; deleting a column writes a cell tombstone. Removal happens in compaction: "a tombstone can live in one SSTable and the data it marks for deletion in another, so a compaction must also remove both SSTables." An SSTable that holds only expired data can be dropped whole ("Fully expired SSTables"), and sstableexpiredblockers lists what blocks that.

text
     Statement                                                     Marker written
1    DELETE email FROM users WHERE id = 7                           cell tombstone
2    DELETE FROM events WHERE day = '2026-11-01' AND ts = t1        row tombstone
3    DELETE FROM events WHERE day = '2026-11-01' AND ts < t2        range tombstone (one marker for a slice)
4    DELETE FROM events WHERE day = '2026-11-01'                    partition tombstone
5    INSERT ... USING TTL 86400                                     cell expires after a day -> treated as a tombstone

Real scenario: an event store keyed by day drops whole days with one partition tombstone; a retention job deletes "older than 30 days" inside each device's partition with one range tombstone instead of a million row tombstones; session data written with TTL and compacted with Time Window Compaction Strategy drops whole SSTables when they expire.

Compaction option (Cassandra)DefaultUse
tombstone_threshold0.2Single-SSTable compaction when this fraction is tombstones
tombstone_compaction_interval86400sMinimum time between such attempts per SSTable
unchecked_tombstone_compactionfalseSkip the overlap pre-checks; still drops only safe tombstones
only_purge_repaired_tombstonesfalseDrop tombstones only from repaired data

Fix / how to use it: delete at the coarsest level your model allows (partition, then range, then row); use TTL plus TWCS for data that expires by age; never mix TTL and non-TTL data in the same partition if you want SSTables to expire whole ("Cassandra will have a hard time dropping the tombstones").

Tombstones in logs: Kafka compaction, delete.retention.ms, Redis Streams Important ​

In plain words: a compacted Kafka topic keeps the last value per key. To delete a key you write the key with an empty (null) value. Consumers that read the topic from the start see the delete marker, as long as they finish before the cleaner removes it.

Common misunderstanding: "Writing a null value deletes the key immediately for everyone." The marker removes older values during compaction, and is itself removed after delete.retention.ms. A consumer that rebuilds state from offset 0 and is slower than that misses the delete and keeps the key forever. That is the Cassandra zombie in a log.

Definition: Kafka design: "A message with a key and a null payload will be treated as a delete from the log. Such a record is sometimes referred to as a tombstone." "all delete markers for deleted records will be seen, provided the consumer reaches the head of the log in a time period less than the topic's delete.retention.ms setting (the default is 24 hours)." delete.retention.ms (topic) / log.cleaner.delete.retention.ms (broker default) is 86400000. min.compaction.lag.ms keeps recent records uncompacted for at least that long. Redis Streams has no replicated delete marker for consumers: XDEL removes an entry from the stream, and internally "the entry is not really evicted, it just gets marked as deleted" until its whole macro node is empty.

text
     Producer                         Compacted topic users (cleanup.policy=compact)      Slow consumer
1    key=u7 value={...}         ->    offset 10: u7 -> {...}
2    key=u7 value=null          ->    offset 11: u7 -> null (tombstone)
3                                     cleaner: drops offset 10
4                                     24h later (delete.retention.ms): drops offset 11
5                                                                                         restarts from offset 0 after 30h
6                                                                                         never sees u7 at all: fine
     ---- but if the consumer read offset 10 before step 3 and reached offset 11 after step 4: it keeps u7 forever

Real scenario: a user-profile changelog topic used to rebuild caches; a CDC pipeline that turns row deletes into tombstones on a compacted topic (see Change Data Capture); a KTable-style materialised view; an event-sourced read model (see Event Sourcing & CQRS).

Fix / how to use it: set delete.retention.ms longer than the longest full replay any consumer does; alert on consumer lag approaching it; in Go with franz-go a tombstone is a record with Value: nil; never use null values for anything except deletes on compacted topics.

Soft delete vs tombstone (SQL, SoftDeletes, Prunable) Must-know ​

In plain words: a soft delete keeps the row and sets deleted_at. Inside one SQL database that is a UX feature (undo, trash, audit). As soon as other systems copy that table (mobile clients, search indexes, caches, a data warehouse), the soft-deleted row is also the tombstone that tells them to delete their copy, and pruning it is garbage collection with the same grace-period rule.

Common misunderstanding: "Soft delete is for undo; sync can use updated_at > ?." A hard-deleted row never appears in any "changed since" query, so every downstream copy keeps it. And "prune soft-deleted rows after 7 days" silently becomes a resurrection bug for a phone that was offline for 8.

Definition: Laravel: "When models are soft deleted, they are not actually removed from your database. Instead, a deleted_at attribute is set on the model". Queries exclude them automatically; withTrashed() and onlyTrashed() include them; restore() undoes; forceDelete() removes for good. Pruning: add Prunable or MassPrunable, return the expired rows from prunable(), and schedule model:prune; "Soft deleting models will be permanently deleted (forceDelete) if they match the prunable query." MassPrunable deletes with one query, so "the pruning method will not be invoked, nor will the deleting and deleted model events be dispatched."

text
     Server (Laravel)                            Phone (offline 3 days)
1    doc 9 exists                                doc 9 cached
2    DELETE /docs/9 -> deleted_at = now()        (offline)
3    sync diff for other clients includes {id: 9, deleted: true}
4    day 30: model:prune force-deletes doc 9 (grace = 30 days)
5                                                day 3: online, last_synced_at 3 days ago < 30 days
6                                                bucket of doc 9 differs -> receives {id: 9, deleted: true} -> drops it
     ---- a phone offline 40 days gets 409 resync_required instead of a silent zombie

Real scenario: offline-first mobile notes; a search index fed by "changed since" polling; a data warehouse ingesting nightly deltas; a multi-tenant SaaS with a recycle bin; right-to-erasure requests that must eventually remove the row for real.

ApproachDelete visible to sync clients?StorageUndoErasure
Hard DELETENoFreed nowNoImmediate in the primary, not in copies
Soft delete, never prunedYesGrows foreverYesNever, unless you strip columns
Soft delete + pruning after a grace periodYes, within the grace periodBoundedWithin graceAfter grace, plus copies resync
Separate tombstone table (id, deleted_at) + hard delete of the rowYes, within the tombstone retentionSmallNoPayload removed immediately; id kept until prune
Event log of deletes (outbox / CDC)Yes, for consumers within retentionLog retentionNoDepends on the log (compaction)

Fix / how to use it: in SQL, a partial index on live rows and batched pruning; in Laravel, SoftDeletes plus Prunable with a grace period longer than the longest supported offline time, and a sync API that includes trashed rows and refuses clients older than the grace period. Both are in Solving the classic problems and Laravel.

Client sync protocols: CouchDB replication, Merkle sync, rsync Important ​

In plain words: there are three families of "bring the other side up to date": follow a log of changes from a checkpoint (CouchDB), compare hashes of buckets and fetch differing buckets (Merkle sync), or compare checksums of blocks of a file and send only unmatched blocks (rsync).

Common misunderstanding: "CouchDB replication uses Merkle trees." The protocol is a changes feed plus checkpoints: the replicator reads GET /{db}/_changes?since=..., asks the target POST /{db}/_revs_diff which revisions it lacks, and records checkpoints in a replication log. Deletes travel as revisions with "deleted": true; "Normal deletion of a document within CouchDB does not remove the document from the database, instead, the document is marked as _deleted=true (and a new revision is created). This is to ensure that deleted documents can be replicated to other databases as having been deleted."

Definition: a changes feed is cheap when the client was recently online and the server keeps history; a Merkle comparison is cheap when the client may be arbitrarily stale or the server does not keep a log, and its cost depends on the number of differences; rsync's "weak rolling checksum" can be computed "for blocks of length S at all possible offsets within a file in a "rolling" fashion, with very little computation at each point", so it finds moved data inside a single file.

text
     CouchDB replication (changes feed)                 Merkle sync endpoint (this page's Laravel code)
1    GET target/_local/<replication id> -> checkpoint     GET /sync/root -> root R
2    GET source/_changes?since=seq                       client root == R ? done
3    POST target/_revs_diff {id: [revs]}                 POST /sync/diff {256 bucket hashes, last_synced_at}
4    fetch missing revisions, write to target            server returns rows of divergent buckets (incl. deleted)
5    PUT checkpoint                                      client applies, recomputes its buckets

Real scenario: PouchDB in a browser syncing with CouchDB; a field-service app syncing work orders over a bad mobile link; Dropbox-style block sync for large files (inference: block hashing for deduplication is the common pattern; we did not read Dropbox's own description); rsync -a of a directory tree between servers.

ProtocolFinds differences byCost when in syncCost after long offlineDeletes
CouchDB replicationChanges feed since a checkpointOne empty changes requestAll changes since the checkpoint_deleted revisions; _purge removes them
Merkle sync (buckets)Root, then bucket hashesOne root hashHashes plus rows of divergent bucketsTombstones must be in the hashed rows
rsyncBlock checksums + rolling checksumChecksums of every blockUnmatched blocksFiles: --delete on the receiver
"updated_at > since" pollingTimestamp columnOne queryAll rows changed sinceInvisible unless soft-deleted

Fix / how to use it: if you have a durable change log with long retention, a changes feed is simplest. If clients can be stale for weeks and you cannot keep a log forever, use Merkle buckets, include tombstones in the hash, and define the grace period after which a client must resync.

Observability: repair lag, tombstone counts, hints Important ​

In plain words: the failure in this chapter is silent until a deleted row comes back. The only defence is a graph of "how long since each table was last fully repaired" next to gc_grace_seconds, plus counters for tombstones read and hints stuck.

Common misunderstanding: "If nodetool repair exited 0 last week, we are fine." A repair on one node does not cover the cluster; a scheduler can skip tables; incremental repair can leave the repaired set unchecked for months. Measure per table, per range.

Definition: Cassandra table metrics include PercentRepaired, BytesRepaired, BytesUnrepaired, BytesPendingRepair, TombstoneScannedHistogram, TombstoneWarnings and TombstoneFailures; repair timers include ValidationTime ("Time spent doing validation compaction during repair"), SyncTime and RepairTime; hints have Hints_created-<PeerIP> and the HintsService meters HintsSucceeded, HintsFailed, HintsTimedOut. Read repair exposes diagnostic events (contacted endpoints, digest responses, affected partition keys).

text
     Alert rules (expected configuration)
1    time_since_last_full_repair(table) > gc_grace_seconds - 3 days        -> page
2    PercentRepaired(table) < 80 for 2 days (incremental users)            -> ticket
3    rate(TombstoneWarnings) > 0 for 15 min                                -> ticket: data model
4    HintsTimedOut or hints on disk growing for 1 hour                     -> check the target node
5    node down > max_hint_window                                           -> schedule repair of that node

Real scenario: a dashboard per keyspace shows repair age in days with a red line at gc_grace_seconds; a tombstone histogram identifies the one table modelled as a queue; a hint backlog shows a node that is up but not accepting writes.

Fix / how to use it: export these metrics (JMX exporter or the Cassandra virtual tables), keep repair history in Reaper or system_distributed.auto_repair_history, and put the grace period on the same chart as repair age.

Mechanics ​

Proof sizes and diff arithmetic ​

QuantityFormulaExample
Inclusion proof length (binary, RFC 6962)at most ceil(log2 n) hashesn = 1,000,000: 20 hashes, 640 bytes with SHA-256
Consistency proof lengthat most ceil(log2 n) + 1600,000 to 1,000,000: 15 hashes (lab)
Diff of identical trees1 comparisonAny size
Diff with k divergent leaves, fan-out b, depth dat most 1 + k * b * d comparisons, d + 1 roundsk = 1, b = 16, d = 4: 65 hashes, 5 rounds
Data streamed per divergent leafabout n / b^d keys100,000 keys, 16 leaves: about 6,000 keys for one change
Full-dataset comparison without a treen keys (or hashes) both ways100,000 keys: 200,000 entries sent (the Before code)
Tree memoryb^d leaf hashes (+ inner nodes, about 1/(b-1) more)65,536 leaves x 32 bytes = 2 MiB

The asymmetry that matters: building the tree always reads all the data in the range (Cassandra times this as validation compaction), but the network cost is proportional to the differences. That is why repair is disk-heavy and why Riak keeps trees persistent and updated on write.

The knobs, product by product ​

ProductKnobDefaultWhat it controls
Cassandra tablegc_grace_seconds864000How long tombstones are kept before compaction may drop them
Cassandra tableread_repairBLOCKINGNONE reconciles reads without writing back
Cassandra tabledefault_time_to_live0TTL for rows without an explicit USING TTL
Cassandra yamlmax_hint_window3hHints generated per down host
Cassandra yamltombstone_warn_threshold / tombstone_failure_threshold1000 / 100000Per-query tombstone scan limits
Cassandra yamlrepair_session_space1/16 of heapMerkle tree memory, so resolution
Cassandra yamlconcurrent_merkle_tree_requests0 (no limit)Simultaneous tree builds per repair command
Cassandra compactiononly_purge_repaired_tombstonesfalseDrop tombstones only from repaired data
Cassandra startup checkcheck_data_resurrectiondisabledRefuse to start after being down longer than gc_grace_seconds
Kafka topiccleanup.policy=compact, delete.retention.ms86400000How long tombstones stay in a compacted topic
Kafka topicmin.compaction.lag.ms / max.compaction.lag.ms0 / 9223372036854775807 (Long.MAX)Window before a record may be compacted
Riak KVAAEenabledBackground tree exchange; trees rebuilt weekly
Laravelprunable() + model:prune schedulenoneWhich soft-deleted rows are force-deleted, and when

Error messages and log lines you will actually see ​

MessageSourceMeaningAction
Scanned over %d tombstones during query '%s' (last scanned row token was %s and partion key was (%s)); query abortedCassandra TombstoneOverwhelmingExceptiontombstone_failure_threshold exceededFix the data model; compact; never raise the threshold as the fix
Read %d live rows and %d tombstone cells for query %1.512s; token %s (see tombstone_warn_threshold)Cassandra ReadCommand warningAbove tombstone_warn_thresholdFind the table with TombstoneScannedHistogram
When increasing replication factor you need to run a full (-full) repair to distribute the data.cqlsh warning on ALTER KEYSPACENew replicas are emptynodetool repair -full on the keyspace
Repair completed successfully / Repair command #1 finished in 1 secondnodetool repairThis node's ranges are repairedRecord per table; repeat on every node (-pr)
Table option read_repair_chance rejectedCassandra 4.0+ schemaOption removed (CASSANDRA-13910)Remove it from migrations
409 {"resync_required": true}This page's Laravel sync APIClient older than the tombstone grace periodWipe and download a fresh copy

Go ​

The module academy/merkle-trees-anti-entropy uses only the standard library. merkle is the RFC 6962 tree with inclusion and consistency proofs and a tree diff, antientropy is the fixed-shape range tree replicas compare, kvsim is a three-replica leaderless store with hints, read repair, Merkle repair and two delete modes, and cmd/aesim prints the lab output.

Before ​

Replica sync as it is usually written first: ship every key to compare, delete by removing the row. The tests document both failures: 20,000 entries sent for two identical 10,000-key replicas, and a deleted cart that the sync copies back.

go
// Package before is the replica sync most teams write first: compare by
// shipping every key, delete by removing the local row. Both are correct on
// a single machine and both break between replicas.
package before

// Store is one replica: key -> value, no timestamps, no delete markers.
type Store map[string]string

// FullSync merges two replicas by sending every entry in both directions.
// It returns the number of entries that crossed the network, which is the
// size of the dataset even when the replicas are already identical.
func FullSync(a, b Store) (sent int) {
	for k, v := range a {
		if _, ok := b[k]; !ok {
			b[k] = v
		}
		sent++
	}
	for k, v := range b {
		if _, ok := a[k]; !ok {
			a[k] = v
		}
		sent++
	}
	return sent
}

// Delete removes the row locally. A replica that missed this call still has
// the row, and FullSync cannot tell "deleted here" from "never written here".
func Delete(s Store, key string) { delete(s, key) }
go
package before

import (
	"fmt"
	"testing"
)

func TestFullSyncCostsTheWholeDataset(t *testing.T) {
	a, b := Store{}, Store{}
	for i := 0; i < 10000; i++ {
		k := fmt.Sprintf("user:%d", i)
		a[k], b[k] = "v1", "v1"
	}
	if sent := FullSync(a, b); sent != 20000 {
		t.Fatalf("sent %d entries for two identical replicas", sent)
	}
}

func TestHardDeleteComesBack(t *testing.T) {
	a, b := Store{"cart:42": "3 items"}, Store{"cart:42": "3 items"}
	Delete(a, "cart:42") // b was unreachable and missed the delete
	FullSync(a, b)
	if _, ok := a["cart:42"]; !ok {
		t.Fatal("expected the deleted row to be resurrected (this is the bug)")
	}
}

After ​

An RFC 6962 Merkle tree. Leaf and node hashing with the 0x00/0x01 prefixes, roots of any prefix of the log (RootAt), audit paths, consistency proofs, the RFC 9162 verification algorithms, and Diff, which descends only into subtrees whose hashes differ:

go
// Package merkle implements the Merkle Tree Hash of RFC 6962 / RFC 9162:
// leaves are hashed as SHA-256(0x00 || data), inner nodes as
// SHA-256(0x01 || left || right), and an n-leaf list is split at the largest
// power of two smaller than n. It provides inclusion (audit) proofs,
// consistency proofs between two tree sizes, and a structural diff that
// descends only into subtrees whose hashes differ.
//
// A Tree is not safe for concurrent use: subtree hashes are memoised.
package merkle

import (
	"bytes"
	"crypto/sha256"
	"errors"
)

// Domain-separation prefixes from RFC 6962 section 2.1. Without them a leaf
// could be passed off as an inner node (second preimage attack).
const (
	leafPrefix byte = 0x00
	nodePrefix byte = 0x01
)

var (
	// ErrIndex is returned for a leaf index or tree size outside the tree.
	ErrIndex = errors.New("merkle: index out of range")
	// ErrShape is returned by Diff when the trees have different sizes.
	ErrShape = errors.New("merkle: trees have different sizes")
)

// LeafHash returns SHA-256(0x00 || data).
func LeafHash(data []byte) []byte {
	h := sha256.New()
	h.Write([]byte{leafPrefix})
	h.Write(data)
	return h.Sum(nil)
}

// NodeHash returns SHA-256(0x01 || left || right).
func NodeHash(left, right []byte) []byte {
	h := sha256.New()
	h.Write([]byte{nodePrefix})
	h.Write(left)
	h.Write(right)
	return h.Sum(nil)
}

// Tree is an append-only list of leaf hashes plus a memo of subtree hashes.
type Tree struct {
	leaves [][]byte
	memo   map[[2]int][]byte
}

// New hashes every data item into a leaf.
func New(data [][]byte) *Tree {
	t := &Tree{memo: map[[2]int][]byte{}}
	for _, d := range data {
		t.Append(d)
	}
	return t
}

// Append adds one data item as the next leaf. Earlier subtree hashes stay
// valid because a subtree never changes once all its leaves exist.
func (t *Tree) Append(data []byte) {
	t.leaves = append(t.leaves, LeafHash(data))
}

// Size is the number of leaves.
func (t *Tree) Size() int { return len(t.leaves) }

// Root is the Merkle Tree Hash of all leaves (the root hash).
func (t *Tree) Root() []byte { return t.mth(0, len(t.leaves)) }

// RootAt is the root hash of the first size leaves, as a log would have
// published it when it had size entries.
func (t *Tree) RootAt(size int) ([]byte, error) {
	if size < 0 || size > len(t.leaves) {
		return nil, ErrIndex
	}
	return t.mth(0, size), nil
}

// split returns the largest power of two strictly smaller than n (n > 1).
func split(n int) int {
	k := 1
	for k<<1 < n {
		k <<= 1
	}
	return k
}

// mth is MTH(D[lo:hi]).
func (t *Tree) mth(lo, hi int) []byte {
	switch hi - lo {
	case 0:
		s := sha256.Sum256(nil)
		return s[:]
	case 1:
		return t.leaves[lo]
	}
	key := [2]int{lo, hi}
	if h, ok := t.memo[key]; ok {
		return h
	}
	k := split(hi - lo)
	h := NodeHash(t.mth(lo, lo+k), t.mth(lo+k, hi))
	t.memo[key] = h
	return h
}

// InclusionProof returns the audit path for leaf index in the tree of the
// first size leaves: the sibling hashes from the leaf up to the root.
func (t *Tree) InclusionProof(index, size int) ([][]byte, error) {
	if size > len(t.leaves) || index < 0 || index >= size {
		return nil, ErrIndex
	}
	return t.path(index, 0, size), nil
}

func (t *Tree) path(m, lo, hi int) [][]byte {
	if hi-lo <= 1 {
		return nil
	}
	k := split(hi - lo)
	if m < k {
		return append(t.path(m, lo, lo+k), t.mth(lo+k, hi))
	}
	return append(t.path(m-k, lo+k, hi), t.mth(lo, lo+k))
}

// VerifyInclusion checks an audit path with the algorithm of RFC 9162
// section 2.1.3.2. leafHash is LeafHash(data), not the data itself.
func VerifyInclusion(leafHash []byte, index, size int, proof [][]byte, root []byte) bool {
	if index < 0 || index >= size {
		return false
	}
	fn, sn := index, size-1
	r := leafHash
	for _, p := range proof {
		if sn == 0 {
			return false
		}
		if fn&1 == 1 || fn == sn {
			r = NodeHash(p, r)
			for fn&1 == 0 && fn != 0 {
				fn >>= 1
				sn >>= 1
			}
		} else {
			r = NodeHash(r, p)
		}
		fn >>= 1
		sn >>= 1
	}
	return sn == 0 && bytes.Equal(r, root)
}

// ConsistencyProof proves that the tree of the first `first` leaves is a
// prefix of the tree of the first `second` leaves (RFC 6962 PROOF(m, D[n])).
func (t *Tree) ConsistencyProof(first, second int) ([][]byte, error) {
	if second > len(t.leaves) || first <= 0 || first > second {
		return nil, ErrIndex
	}
	if first == second {
		return nil, nil
	}
	return t.subproof(first, 0, second, true), nil
}

func (t *Tree) subproof(m, lo, hi int, complete bool) [][]byte {
	n := hi - lo
	if m == n {
		if complete {
			return nil
		}
		return [][]byte{t.mth(lo, hi)}
	}
	k := split(n)
	if m <= k {
		return append(t.subproof(m, lo, lo+k, complete), t.mth(lo+k, hi))
	}
	return append(t.subproof(m-k, lo+k, hi, false), t.mth(lo, lo+k))
}

// VerifyConsistency checks a consistency proof with the algorithm of
// RFC 9162 section 2.1.4.2.
func VerifyConsistency(first, second int, firstRoot, secondRoot []byte, proof [][]byte) bool {
	if first <= 0 || first > second {
		return false
	}
	if first == second {
		return len(proof) == 0 && bytes.Equal(firstRoot, secondRoot)
	}
	if len(proof) == 0 {
		return false
	}
	path := proof
	if first&(first-1) == 0 { // exact power of two
		path = append([][]byte{firstRoot}, proof...)
	}
	fn, sn := first-1, second-1
	for fn&1 == 1 {
		fn >>= 1
		sn >>= 1
	}
	fr, sr := path[0], path[0]
	for _, c := range path[1:] {
		if sn == 0 {
			return false
		}
		if fn&1 == 1 || fn == sn {
			fr = NodeHash(c, fr)
			sr = NodeHash(c, sr)
			for fn&1 == 0 && fn != 0 {
				fn >>= 1
				sn >>= 1
			}
		} else {
			sr = NodeHash(sr, c)
		}
		fn >>= 1
		sn >>= 1
	}
	return sn == 0 && bytes.Equal(fr, firstRoot) && bytes.Equal(sr, secondRoot)
}

// Diff compares two trees of the same size top-down, the way two replicas
// exchange hashes during anti-entropy: equal subtrees are skipped, unequal
// ones are split until single leaves remain. It returns the indexes of the
// divergent leaves and how many hash comparisons were needed.
func Diff(a, b *Tree) (leaves []int, compared int, err error) {
	if a.Size() != b.Size() {
		return nil, 0, ErrShape
	}
	var walk func(lo, hi int)
	walk = func(lo, hi int) {
		compared++
		if bytes.Equal(a.mth(lo, hi), b.mth(lo, hi)) {
			return
		}
		if hi-lo == 1 {
			leaves = append(leaves, lo)
			return
		}
		k := split(hi - lo)
		walk(lo, lo+k)
		walk(lo+k, hi)
	}
	if a.Size() > 0 {
		walk(0, a.Size())
	}
	return leaves, compared, nil
}

The tests check the published Certificate Transparency test vectors (empty tree, one leaf, eight leaves), every inclusion proof and every consistency proof for all sizes up to 70 and 40, forged leaves and rewritten history, the logarithmic proof length, and the diff:

go
package merkle

import (
	"bytes"
	"encoding/hex"
	"fmt"
	"testing"
)

// The eight inputs used by the Certificate Transparency reference test suite.
var ctInputs = [][]byte{
	{},
	{0x00},
	{0x10},
	{0x20, 0x21},
	{0x30, 0x31},
	{0x40, 0x41, 0x42, 0x43},
	{0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57},
	{0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f},
}

func hx(b []byte) string { return hex.EncodeToString(b) }

func TestKnownRoots(t *testing.T) {
	empty := New(nil)
	if got := hx(empty.Root()); got != "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" {
		t.Fatalf("empty root = %s", got)
	}
	tr := New(ctInputs)
	r1, _ := tr.RootAt(1)
	if got := hx(r1); got != "6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d" {
		t.Fatalf("root(1) = %s", got)
	}
	if got := hx(tr.Root()); got != "5dc9da79a70659a9ad559cb701ded9a2ab9d823aad2f4960cfe370eff4604328" {
		t.Fatalf("root(8) = %s", got)
	}
}

func makeTree(n int) *Tree {
	data := make([][]byte, n)
	for i := range data {
		data[i] = []byte(fmt.Sprintf("leaf-%d", i))
	}
	return New(data)
}

func TestEveryInclusionProofVerifies(t *testing.T) {
	tr := makeTree(70)
	for size := 1; size <= 70; size++ {
		root, _ := tr.RootAt(size)
		for i := 0; i < size; i++ {
			proof, err := tr.InclusionProof(i, size)
			if err != nil {
				t.Fatal(err)
			}
			leaf := LeafHash([]byte(fmt.Sprintf("leaf-%d", i)))
			if !VerifyInclusion(leaf, i, size, proof, root) {
				t.Fatalf("size %d index %d: valid proof rejected", size, i)
			}
			if VerifyInclusion(LeafHash([]byte("forged")), i, size, proof, root) {
				t.Fatalf("size %d index %d: forged leaf accepted", size, i)
			}
			if size > 1 && VerifyInclusion(leaf, (i+1)%size, size, proof, root) {
				t.Fatalf("size %d index %d: proof accepted at the wrong index", size, i)
			}
		}
	}
}

func TestProofLengthIsLogarithmic(t *testing.T) {
	tr := makeTree(1 << 10)
	proof, _ := tr.InclusionProof(517, 1<<10)
	if len(proof) != 10 {
		t.Fatalf("audit path length = %d, want 10 for 1024 leaves", len(proof))
	}
}

func TestEveryConsistencyProofVerifies(t *testing.T) {
	tr := makeTree(40)
	for second := 1; second <= 40; second++ {
		r2, _ := tr.RootAt(second)
		for first := 1; first <= second; first++ {
			r1, _ := tr.RootAt(first)
			proof, err := tr.ConsistencyProof(first, second)
			if err != nil {
				t.Fatal(err)
			}
			if !VerifyConsistency(first, second, r1, r2, proof) {
				t.Fatalf("%d -> %d: valid consistency proof rejected", first, second)
			}
			if first < second && VerifyConsistency(first, second, LeafHash([]byte("x")), r2, proof) {
				t.Fatalf("%d -> %d: wrong old root accepted", first, second)
			}
		}
	}
}

func TestRewrittenHistoryFailsConsistency(t *testing.T) {
	honest := makeTree(8)
	oldRoot, _ := honest.RootAt(5)
	// A log that rewrote entry 2 after publishing the 5-entry root.
	data := make([][]byte, 8)
	for i := range data {
		data[i] = []byte(fmt.Sprintf("leaf-%d", i))
	}
	data[2] = []byte("rewritten")
	evil := New(data)
	proof, _ := evil.ConsistencyProof(5, 8)
	if VerifyConsistency(5, 8, oldRoot, evil.Root(), proof) {
		t.Fatal("rewritten history passed the consistency check")
	}
}

func TestDiffFindsOnlyDivergentLeaves(t *testing.T) {
	a, b := makeTree(1024), makeTree(1024)
	leaves, compared, err := Diff(a, b)
	if err != nil || len(leaves) != 0 || compared != 1 {
		t.Fatalf("identical: leaves=%v compared=%d err=%v", leaves, compared, err)
	}
	data := make([][]byte, 1024)
	for i := range data {
		data[i] = []byte(fmt.Sprintf("leaf-%d", i))
	}
	data[300] = []byte("changed")
	data[301] = []byte("changed too")
	c := New(data)
	leaves, compared, _ = Diff(a, c)
	if len(leaves) != 2 || leaves[0] != 300 || leaves[1] != 301 {
		t.Fatalf("divergent leaves = %v", leaves)
	}
	// 1 root + 2 per level for 9 levels, then 2 extra at the split of 300/301.
	if compared > 2*10+3 {
		t.Fatalf("compared %d hashes, want a logarithmic number", compared)
	}
	if _, _, err := Diff(a, makeTree(3)); err != ErrShape {
		t.Fatalf("want ErrShape, got %v", err)
	}
}

func TestAppendKeepsOldRoots(t *testing.T) {
	tr := makeTree(5)
	before, _ := tr.RootAt(5)
	tr.Append([]byte("leaf-5"))
	after, _ := tr.RootAt(5)
	if !bytes.Equal(before, after) {
		t.Fatal("appending changed the root of an older size")
	}
}

The anti-entropy tree. Keys go to fanout^depth contiguous token ranges, so both replicas build the same shape; leaves hash sorted entries including tombstones; Diff reports rounds, hashes compared and divergent buckets; InBuckets is what gets streamed:

go
// Package antientropy builds the fixed-shape hash trees that replicas compare
// during anti-entropy repair (Dynamo section 4.7, Cassandra repair, Riak AAE).
//
// Keys are placed into fanout^depth buckets by token (the first 8 bytes of
// SHA-256 of the key), so every bucket is a contiguous token range and two
// replicas of the same range build trees with identical shape. A leaf hashes
// the sorted entries of its bucket (tombstones included); an inner node
// hashes its children. Diff walks both trees level by level and only asks for
// the children of nodes that differ.
package antientropy

import (
	"bytes"
	"crypto/sha256"
	"encoding/binary"
	"errors"
	"sort"
	"strconv"
)

// Entry is one replicated cell. Deleted marks a tombstone.
type Entry struct {
	Key     string
	Value   string
	TS      int64 // write timestamp used for last-write-wins
	Deleted bool
}

// ErrShape is returned when two trees were built with different parameters.
var ErrShape = errors.New("antientropy: trees have different shapes")

// Token maps a key onto the 64-bit ring.
func Token(key string) uint64 {
	s := sha256.Sum256([]byte(key))
	return binary.BigEndian.Uint64(s[:8])
}

// Bucket maps a key to one of n contiguous token ranges.
func Bucket(key string, n int) int {
	hi := Token(key) >> 32
	return int(hi * uint64(n) >> 32)
}

// Tree is a complete fanout-ary hash tree. levels[0] holds the root,
// levels[depth] holds one hash per bucket.
type Tree struct {
	Fanout, Depth int
	levels        [][][]byte
}

// Buckets is the number of leaves (token ranges).
func (t *Tree) Buckets() int { return len(t.levels[t.Depth]) }

// Root is the root hash.
func (t *Tree) Root() []byte { return t.levels[0][0] }

// Build hashes a replica's entries. Cost: one pass over the data (the
// "validation compaction" that Cassandra runs before a repair session).
func Build(entries map[string]Entry, fanout, depth int) *Tree {
	n := 1
	for i := 0; i < depth; i++ {
		n *= fanout
	}
	buckets := make([][]Entry, n)
	for _, e := range entries {
		b := Bucket(e.Key, n)
		buckets[b] = append(buckets[b], e)
	}
	leaves := make([][]byte, n)
	for i, es := range buckets {
		sort.Slice(es, func(a, b int) bool { return es[a].Key < es[b].Key })
		h := sha256.New()
		for _, e := range es {
			h.Write([]byte(e.Key))
			h.Write([]byte{0})
			h.Write([]byte(e.Value))
			h.Write([]byte{0})
			h.Write([]byte(strconv.FormatInt(e.TS, 10)))
			if e.Deleted {
				h.Write([]byte{0, 'D'})
			}
			h.Write([]byte{'\n'})
		}
		leaves[i] = h.Sum(nil)
	}
	levels := make([][][]byte, depth+1)
	levels[depth] = leaves
	for d := depth - 1; d >= 0; d-- {
		below := levels[d+1]
		cur := make([][]byte, len(below)/fanout)
		for i := range cur {
			h := sha256.New()
			for _, c := range below[i*fanout : (i+1)*fanout] {
				h.Write(c)
			}
			cur[i] = h.Sum(nil)
		}
		levels[d] = cur
	}
	return &Tree{Fanout: fanout, Depth: depth, levels: levels}
}

// Stats describes one comparison between two replicas.
type Stats struct {
	Rounds         int   // request/response round trips (levels descended)
	HashesCompared int   // hashes sent over the network and compared
	Divergent      []int // buckets whose contents differ
}

// Diff compares two trees top-down. The cost is bounded by the number of
// differences: identical replicas exchange one root hash.
func Diff(a, b *Tree) (Stats, error) {
	if a.Fanout != b.Fanout || a.Depth != b.Depth {
		return Stats{}, ErrShape
	}
	st := Stats{Rounds: 1, HashesCompared: 1}
	if bytes.Equal(a.Root(), b.Root()) {
		return st, nil
	}
	frontier := []int{0}
	for d := 1; d <= a.Depth; d++ {
		st.Rounds++
		var next []int
		for _, parent := range frontier {
			for c := parent * a.Fanout; c < (parent+1)*a.Fanout; c++ {
				st.HashesCompared++
				if !bytes.Equal(a.levels[d][c], b.levels[d][c]) {
					next = append(next, c)
				}
			}
		}
		frontier = next
	}
	st.Divergent = frontier
	return st, nil
}

// InBuckets returns the entries of the given buckets: what a replica streams
// to its peer for the divergent ranges. Everything else stays put.
func InBuckets(entries map[string]Entry, buckets []int, n int) []Entry {
	want := make(map[int]bool, len(buckets))
	for _, b := range buckets {
		want[b] = true
	}
	var out []Entry
	for _, e := range entries {
		if want[Bucket(e.Key, n)] {
			out = append(out, e)
		}
	}
	sort.Slice(out, func(i, j int) bool { return out[i].Key < out[j].Key })
	return out
}
go
package antientropy

import (
	"fmt"
	"testing"
)

func dataset(n int) map[string]Entry {
	m := make(map[string]Entry, n)
	for i := 0; i < n; i++ {
		k := fmt.Sprintf("user:%05d", i)
		m[k] = Entry{Key: k, Value: "v1", TS: 1}
	}
	return m
}

func clone(m map[string]Entry) map[string]Entry {
	c := make(map[string]Entry, len(m))
	for k, v := range m {
		c[k] = v
	}
	return c
}

func TestIdenticalReplicasExchangeOneHash(t *testing.T) {
	a := dataset(10000)
	st, err := Diff(Build(a, 16, 3), Build(clone(a), 16, 3))
	if err != nil {
		t.Fatal(err)
	}
	if st.HashesCompared != 1 || st.Rounds != 1 || len(st.Divergent) != 0 {
		t.Fatalf("identical replicas: %+v", st)
	}
}

func TestOneChangedKeyCostsOnePathOfHashes(t *testing.T) {
	a := dataset(10000)
	b := clone(a)
	b["user:04242"] = Entry{Key: "user:04242", Value: "v2", TS: 2}
	st, _ := Diff(Build(a, 16, 3), Build(b, 16, 3))
	if len(st.Divergent) != 1 || st.Divergent[0] != Bucket("user:04242", 4096) {
		t.Fatalf("divergent = %v", st.Divergent)
	}
	if want := 1 + 16*3; st.HashesCompared != want || st.Rounds != 4 {
		t.Fatalf("compared %d hashes in %d rounds, want %d in 4", st.HashesCompared, st.Rounds, want)
	}
	streamed := InBuckets(b, st.Divergent, 4096)
	if len(streamed) > 10 {
		t.Fatalf("streamed %d entries for one changed key", len(streamed))
	}
}

func TestTombstoneIsADifference(t *testing.T) {
	a := dataset(100)
	b := clone(a)
	b["user:00007"] = Entry{Key: "user:00007", TS: 5, Deleted: true}
	st, _ := Diff(Build(a, 4, 2), Build(b, 4, 2))
	if len(st.Divergent) != 1 {
		t.Fatalf("a tombstone must change the bucket hash: %+v", st)
	}
}

func TestLowResolutionOverstreams(t *testing.T) {
	a := dataset(10000)
	b := clone(a)
	b["user:00001"] = Entry{Key: "user:00001", Value: "v2", TS: 2}
	coarse, _ := Diff(Build(a, 2, 2), Build(b, 2, 2)) // 4 buckets
	fine, _ := Diff(Build(a, 2, 12), Build(b, 2, 12)) // 4096 buckets
	nc := len(InBuckets(b, coarse.Divergent, 4))
	nf := len(InBuckets(b, fine.Divergent, 4096))
	if nc < 1000 || nf > 20 {
		t.Fatalf("coarse streamed %d, fine streamed %d", nc, nf)
	}
}

func TestShapeMismatch(t *testing.T) {
	if _, err := Diff(Build(nil, 2, 3), Build(nil, 4, 3)); err != ErrShape {
		t.Fatalf("want ErrShape, got %v", err)
	}
}

The replica simulator. Hinted handoff bounded by HintWindow, blocking read repair on the contacted replicas only, pairwise Merkle repair that streams only divergent buckets, compaction that purges tombstones after GCGrace, and the two delete modes:

go
// Package kvsim is a single-process simulation of a leaderless replicated
// key-value store (Dynamo / Cassandra style) with the three convergence
// mechanisms: hinted handoff on the write path, blocking read repair on the
// read path, and Merkle-tree anti-entropy repair in the background. Deletes
// are either hard (remove the local copy) or tombstones with a grace period,
// so the resurrection ("zombie") failure can be reproduced in a test.
package kvsim

import (
	"sort"

	"academy/merkle-trees-anti-entropy/antientropy"
)

// DeleteMode selects how Delete is implemented.
type DeleteMode int

const (
	// HardDelete removes the local copy. Absence carries no timestamp, so a
	// replica that missed the delete looks like the only one with data.
	HardDelete DeleteMode = iota
	// Tombstones writes a timestamped delete marker that replicates like data
	// and is purged by compaction after GCGrace seconds.
	Tombstones
)

// Config mirrors the knobs of a real store.
type Config struct {
	Replicas   []string
	Mode       DeleteMode
	GCGrace    int64 // like Cassandra gc_grace_seconds
	HintWindow int64 // like Cassandra max_hint_window (seconds)
	Fanout     int   // Merkle tree branching factor
	Depth      int   // Merkle tree depth; buckets = Fanout^Depth
}

// Stats counts what each mechanism did.
type Stats struct {
	HintsStored, HintsDropped, HintsReplayed int
	ReadRepairs                              int
	RepairStreamed, RepairHashes             int
	TombstonesPurged                         int
}

type op struct {
	e      antientropy.Entry
	remove bool
}

type replica struct {
	up        bool
	downSince int64
	data      map[string]antientropy.Entry
}

// Cluster holds every replica and a logical clock in seconds.
type Cluster struct {
	cfg   Config
	now   int64
	seq   int64
	names []string
	reps  map[string]*replica
	hints map[string][]op
	Stats Stats
}

// New starts a cluster with every replica up at time 0.
func New(cfg Config) *Cluster {
	c := &Cluster{cfg: cfg, reps: map[string]*replica{}, hints: map[string][]op{}}
	for _, n := range cfg.Replicas {
		c.names = append(c.names, n)
		c.reps[n] = &replica{up: true, data: map[string]antientropy.Entry{}}
	}
	return c
}

// Now is the logical time in seconds.
func (c *Cluster) Now() int64 { return c.now }

// ts returns a unique, increasing write timestamp (milliseconds).
func (c *Cluster) ts() int64 {
	c.seq++
	return c.now*1000 + c.seq%1000
}

// Advance moves the clock and runs compaction on every live replica:
// tombstones older than GCGrace are purged.
func (c *Cluster) Advance(seconds int64) {
	c.now += seconds
	for _, n := range c.names {
		r := c.reps[n]
		if !r.up {
			continue
		}
		for k, e := range r.data {
			if e.Deleted && c.now-e.TS/1000 > c.cfg.GCGrace {
				delete(r.data, k)
				c.Stats.TombstonesPurged++
			}
		}
	}
}

// Down marks a replica unreachable.
func (c *Cluster) Down(name string) {
	r := c.reps[name]
	r.up, r.downSince = false, c.now
}

// Up brings a replica back and replays the hints stored for it.
func (c *Cluster) Up(name string) {
	r := c.reps[name]
	r.up = true
	for _, h := range c.hints[name] {
		c.apply(r, h)
		c.Stats.HintsReplayed++
	}
	delete(c.hints, name)
}

// Put writes key = value to every replica (down replicas get a hint).
func (c *Cluster) Put(key, value string) {
	c.write(op{e: antientropy.Entry{Key: key, Value: value, TS: c.ts()}})
}

// Delete removes key according to the configured DeleteMode.
func (c *Cluster) Delete(key string) {
	if c.cfg.Mode == Tombstones {
		c.write(op{e: antientropy.Entry{Key: key, TS: c.ts(), Deleted: true}})
		return
	}
	c.write(op{e: antientropy.Entry{Key: key}, remove: true})
}

func (c *Cluster) write(o op) {
	for _, n := range c.names {
		r := c.reps[n]
		switch {
		case r.up:
			c.apply(r, o)
		case c.now-r.downSince <= c.cfg.HintWindow:
			c.hints[n] = append(c.hints[n], o)
			c.Stats.HintsStored++
		default:
			c.Stats.HintsDropped++ // outside the hint window: only repair can fix it
		}
	}
}

func (c *Cluster) apply(r *replica, o op) {
	if o.remove {
		delete(r.data, o.e.Key)
		return
	}
	if cur, ok := r.data[o.e.Key]; !ok || cur.TS < o.e.TS {
		r.data[o.e.Key] = o.e
	}
}

// Read asks the named replicas (the consistency level is len(from)), returns
// the newest version, and performs a blocking read repair on every contacted
// replica whose digest differs before returning.
func (c *Cluster) Read(key string, from ...string) (string, bool) {
	var win antientropy.Entry
	have := false
	got := make(map[string]antientropy.Entry, len(from))
	for _, n := range from {
		r := c.reps[n]
		if !r.up {
			continue
		}
		e, ok := r.data[key]
		if ok {
			got[n] = e
			if !have || e.TS > win.TS {
				win, have = e, true
			}
		}
	}
	if !have {
		return "", false
	}
	repaired := false
	for _, n := range from {
		r := c.reps[n]
		if !r.up {
			continue
		}
		if e, ok := got[n]; !ok || e != win { // digest mismatch
			c.apply(r, op{e: win})
			repaired = true
		}
	}
	if repaired {
		c.Stats.ReadRepairs++
	}
	if win.Deleted {
		return "", false
	}
	return win.Value, true
}

// Repair runs Merkle-tree anti-entropy between every pair of live replicas
// and streams only the entries of divergent buckets, in both directions.
func (c *Cluster) Repair() {
	live := make([]string, 0, len(c.names))
	for _, n := range c.names {
		if c.reps[n].up {
			live = append(live, n)
		}
	}
	sort.Strings(live)
	buckets := 1
	for i := 0; i < c.cfg.Depth; i++ {
		buckets *= c.cfg.Fanout
	}
	for i := 0; i < len(live); i++ {
		for j := i + 1; j < len(live); j++ {
			a, b := c.reps[live[i]], c.reps[live[j]]
			st, _ := antientropy.Diff(
				antientropy.Build(a.data, c.cfg.Fanout, c.cfg.Depth),
				antientropy.Build(b.data, c.cfg.Fanout, c.cfg.Depth))
			c.Stats.RepairHashes += st.HashesCompared
			if len(st.Divergent) == 0 {
				continue
			}
			fromA := antientropy.InBuckets(a.data, st.Divergent, buckets)
			fromB := antientropy.InBuckets(b.data, st.Divergent, buckets)
			for _, e := range fromA {
				c.apply(b, op{e: e})
			}
			for _, e := range fromB {
				c.apply(a, op{e: e})
			}
			c.Stats.RepairStreamed += len(fromA) + len(fromB)
		}
	}
}

// Peek returns a replica's local cell without any repair, for tests.
func (c *Cluster) Peek(name, key string) (antientropy.Entry, bool) {
	e, ok := c.reps[name].data[key]
	return e, ok
}

The tests are the chapter's claims as code: hard deletes are resurrected by repair and by read repair, tombstones survive repair, tombstones purged before repair make a zombie, hints work inside the window, read repair fixes only contacted replicas, and repair cost follows the difference:

go
package kvsim

import (
	"fmt"
	"testing"
)

const (
	hour = int64(3600)
	day  = 24 * hour
)

func cluster(mode DeleteMode, grace int64) *Cluster {
	return New(Config{
		Replicas: []string{"a", "b", "c"}, Mode: mode,
		GCGrace: grace, HintWindow: 3 * hour, Fanout: 16, Depth: 2,
	})
}

// c goes down, stays down past the hint window, misses the delete, and
// comes back `after` seconds later.
func missDelete(c *Cluster, after int64) {
	c.Put("cart:42", "3 items")
	c.Down("c")
	c.Advance(4 * hour) // beyond max_hint_window: no hint for c
	c.Delete("cart:42")
	c.Advance(after)
	c.Up("c")
}

func TestHardDeleteIsResurrectedByRepair(t *testing.T) {
	c := cluster(HardDelete, 10*day)
	missDelete(c, 1*hour)
	c.Repair()
	if v, ok := c.Read("cart:42", "a", "b", "c"); !ok || v != "3 items" {
		t.Fatalf("expected the deleted cart to come back, got %q %v", v, ok)
	}
}

func TestHardDeleteIsResurrectedByReadRepairToo(t *testing.T) {
	c := cluster(HardDelete, 10*day)
	missDelete(c, 1*hour)
	if _, ok := c.Read("cart:42", "a", "c"); !ok {
		t.Fatal("a read that touches c sees the old row")
	}
	if _, ok := c.Peek("a", "cart:42"); !ok {
		t.Fatal("read repair copied the deleted row back to a")
	}
}

func TestTombstoneSurvivesRepair(t *testing.T) {
	c := cluster(Tombstones, 10*day)
	missDelete(c, 1*hour)
	if c.Stats.HintsDropped == 0 {
		t.Fatal("the delete should have fallen outside the hint window")
	}
	c.Repair()
	if _, ok := c.Read("cart:42", "a", "b", "c"); ok {
		t.Fatal("tombstone did not win")
	}
	if e, _ := c.Peek("c", "cart:42"); !e.Deleted {
		t.Fatal("repair should have streamed the tombstone to c")
	}
}

func TestTombstonePurgedBeforeRepairMakesAZombie(t *testing.T) {
	c := cluster(Tombstones, 1*day) // gc_grace shorter than the outage
	missDelete(c, 2*day)
	if c.Stats.TombstonesPurged != 2 {
		t.Fatalf("purged %d tombstones, want 2 (on a and b)", c.Stats.TombstonesPurged)
	}
	c.Repair()
	if v, ok := c.Read("cart:42", "a", "b"); !ok || v != "3 items" {
		t.Fatalf("expected a zombie, got %q %v", v, ok)
	}
}

func TestHintedHandoffInsideTheWindow(t *testing.T) {
	c := cluster(Tombstones, 10*day)
	c.Put("k", "v1")
	c.Down("c")
	c.Advance(1 * hour)
	c.Put("k", "v2")
	c.Up("c")
	if e, _ := c.Peek("c", "k"); e.Value != "v2" || c.Stats.HintsReplayed != 1 {
		t.Fatalf("hint not replayed: %+v %+v", e, c.Stats)
	}
}

func TestBlockingReadRepairFixesOnlyContactedReplicas(t *testing.T) {
	c := cluster(Tombstones, 10*day)
	c.Put("k", "v1")
	c.Down("c")
	c.Down("b")
	c.Advance(4 * hour) // past the hint window: no hints for b and c
	c.Put("k", "v2")
	c.Up("b")
	c.Up("c")
	if v, _ := c.Read("k", "a", "b"); v != "v2" {
		t.Fatalf("read returned %q", v)
	}
	if e, _ := c.Peek("b", "k"); e.Value != "v2" {
		t.Fatal("b was contacted and should be repaired")
	}
	if e, _ := c.Peek("c", "k"); e.Value != "v1" {
		t.Fatal("c was not contacted and must still be stale")
	}
	if c.Stats.ReadRepairs != 1 {
		t.Fatalf("read repairs = %d", c.Stats.ReadRepairs)
	}
}

func TestRepairCostFollowsTheDifference(t *testing.T) {
	c := cluster(Tombstones, 10*day)
	for i := 0; i < 5000; i++ {
		c.Put(fmt.Sprintf("user:%d", i), "v1")
	}
	c.Repair()
	if c.Stats.RepairStreamed != 0 || c.Stats.RepairHashes != 3 {
		t.Fatalf("in-sync replicas: %+v", c.Stats)
	}
	c.Down("c")
	c.Advance(4 * hour)
	c.Put("user:77", "v2")
	c.Up("c")
	c.Repair()
	if c.Stats.RepairStreamed > 2*60 {
		t.Fatalf("streamed %d entries for one missed write", c.Stats.RepairStreamed)
	}
}

The lab driver:

go
// Command aesim prints the lab output of the Merkle Trees, Read Repair,
// Anti-Entropy & Tombstones chapter: proofs, tree diff cost, branching
// factor trade-off, and the three delete scenarios.
package main

import (
	"encoding/hex"
	"fmt"

	"academy/merkle-trees-anti-entropy/antientropy"
	"academy/merkle-trees-anti-entropy/kvsim"
	"academy/merkle-trees-anti-entropy/merkle"
)

const hour = int64(3600)

func main() {
	proofs()
	fanout()
	deletes()
}

func proofs() {
	fmt.Println("== 1. RFC 6962 tree: root, inclusion proof, consistency proof")
	data := make([][]byte, 1_000_000)
	for i := range data {
		data[i] = []byte(fmt.Sprintf("cert-%d", i))
	}
	t := merkle.New(data)
	root := t.Root()
	p, _ := t.InclusionProof(123456, t.Size())
	ok := merkle.VerifyInclusion(merkle.LeafHash(data[123456]), 123456, t.Size(), p, root)
	fmt.Printf("leaves=%d root=%s...\n", t.Size(), hex.EncodeToString(root)[:16])
	fmt.Printf("inclusion proof for leaf 123456: %d hashes (%d bytes), valid=%v\n", len(p), 32*len(p), ok)
	old, _ := t.RootAt(600_000)
	cp, _ := t.ConsistencyProof(600_000, t.Size())
	fmt.Printf("consistency proof 600000 -> 1000000: %d hashes, valid=%v\n",
		len(cp), merkle.VerifyConsistency(600_000, t.Size(), old, root, cp))
}

func fanout() {
	fmt.Println("== 2. one divergent key among 100000: cost by branching factor")
	a := map[string]antientropy.Entry{}
	for i := 0; i < 100_000; i++ {
		k := fmt.Sprintf("user:%06d", i)
		a[k] = antientropy.Entry{Key: k, Value: "v1", TS: 1}
	}
	b := make(map[string]antientropy.Entry, len(a))
	for k, v := range a {
		b[k] = v
	}
	b["user:031337"] = antientropy.Entry{Key: "user:031337", Value: "v2", TS: 2}
	fmt.Printf("%-7s %-6s %-8s %-7s %-7s %s\n", "fanout", "depth", "buckets", "rounds", "hashes", "streamed")
	for _, s := range []struct{ f, d int }{{2, 4}, {2, 16}, {4, 8}, {16, 4}, {256, 2}, {65536, 1}} {
		st, _ := antientropy.Diff(antientropy.Build(a, s.f, s.d), antientropy.Build(b, s.f, s.d))
		n := 1
		for i := 0; i < s.d; i++ {
			n *= s.f
		}
		fmt.Printf("%-7d %-6d %-8d %-7d %-7d %d\n", s.f, s.d, n, st.Rounds, st.HashesCompared,
			len(antientropy.InBuckets(b, st.Divergent, n)))
	}
}

func deletes() {
	fmt.Println("== 3. replica c misses a delete (down 4h, hint window 3h)")
	for _, sc := range []struct {
		name  string
		mode  kvsim.DeleteMode
		grace int64
		after int64
	}{
		{"hard delete", kvsim.HardDelete, 240 * hour, hour},
		{"tombstone, gc_grace 10d, back after 5h", kvsim.Tombstones, 240 * hour, hour},
		{"tombstone, gc_grace 1d, back after 2d", kvsim.Tombstones, 24 * hour, 48 * hour},
	} {
		c := kvsim.New(kvsim.Config{Replicas: []string{"a", "b", "c"}, Mode: sc.mode,
			GCGrace: sc.grace, HintWindow: 3 * hour, Fanout: 16, Depth: 2})
		c.Put("cart:42", "3 items")
		c.Down("c")
		c.Advance(4 * hour)
		c.Delete("cart:42")
		c.Advance(sc.after)
		c.Up("c")
		c.Repair()
		v, found := c.Read("cart:42", "a", "b", "c")
		fmt.Printf("%-40s hints_dropped=%d purged=%d streamed=%d -> read found=%v %q\n",
			sc.name, c.Stats.HintsDropped, c.Stats.TombstonesPurged, c.Stats.RepairStreamed, found, v)
	}
}

The Go angle ​

Go package or clientUse hereNote
crypto/sha256Leaf and node hashessha256.Sum256(nil) is the RFC 6962 empty-tree root
encoding/binaryToken from the first 8 bytes of a hashbinary.BigEndian.Uint64
golang.org/x/mod/sumdb/tlogProduction RFC 6962-style tree used by the Go checksum databaseTiles, ProveRecord, CheckRecord, ProveTree, CheckTree
github.com/transparency-dev/merkleRFC 6962 hashers and proof verificationSource of the test vectors used above
github.com/gocql/gocqlCassandra reads at gocql.Quorum / gocql.LocalQuorumRead repair only happens above ONE
github.com/twmb/franz-go/pkg/kgoKafka tombstone: a *kgo.Record with Key set and Value: nilOnly meaningful on cleanup.policy=compact topics
database/sql / github.com/jackc/pgx/v5Soft delete and batched pruning (SQL in Solving)Prune in small batches to keep locks short
testingEvery claim on this page is a testgo test ./... runs in well under a second

Laravel ​

Before ​

A sync API that hard-deletes and lets clients poll updated_at > since: deleted documents never appear in the response, so offline clients keep them and upload them again.

php
<?php

namespace App\Http\Controllers\Before;

use App\Http\Controllers\Controller;
use App\Models\Document;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * The first version of an offline-capable sync API.
 *
 * - destroy() removes the row, so nothing records that the document existed.
 * - changes() returns rows updated since the client's last sync. A deleted row
 *   is simply absent, which looks the same as "unchanged" to the client, so an
 *   offline phone keeps the document and uploads it again on its next push.
 */
class DocumentSyncBefore extends Controller
{
    public function destroy(string $id): JsonResponse
    {
        DB::table('documents')->where('id', $id)->delete();

        return response()->json(status: 204);
    }

    public function changes(Request $request): JsonResponse
    {
        $since = $request->date('since') ?? now()->subYears(10);

        $rows = Document::query()
            ->where('updated_at', '>', $since)
            ->orderBy('updated_at')
            ->limit(1000)
            ->get(['id', 'version', 'payload', 'updated_at']);

        return response()->json(['changes' => $rows, 'server_time' => now()->toIso8601String()]);
    }
}

After ​

The model: SoftDeletes turns delete() into a tombstone (deleted_at), Prunable is the garbage collector with a configurable grace period, and every save bumps version and pins the row to its Merkle bucket:

php
<?php

namespace App\Models;

use App\Support\MerkleIndex;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Prunable;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * A document that offline clients replicate.
 *
 * SoftDeletes turns delete() into a tombstone (deleted_at is set, the row
 * stays), so the sync endpoint can tell clients "this was deleted". Prunable
 * is the garbage collector: tombstones older than the grace period are
 * removed for good by the scheduled model:prune command.
 */
class Document extends Model
{
    use HasUuids;
    use Prunable;
    use SoftDeletes;

    protected $fillable = ['title', 'payload'];

    protected function casts(): array
    {
        return [
            'payload' => 'array',
            'version' => 'integer',
            'sync_bucket' => 'integer',
        ];
    }

    protected static function booted(): void
    {
        // Every save (create, update, restore) bumps the version and pins the
        // row to its Merkle bucket. delete() on a soft-deleting model does not
        // call save(); the deleted flag itself changes the bucket hash.
        static::saving(function (Document $document): void {
            // HasUuids assigns the key in "creating", which runs after
            // "saving", so assign it here when the row is new.
            if (! $document->getKey()) {
                $document->setAttribute($document->getKeyName(), $document->newUniqueId());
            }
            $document->version = ($document->version ?? 0) + 1;
            $document->sync_bucket = MerkleIndex::bucketFor((string) $document->getKey());
        });
    }

    /**
     * Tombstones past the grace period. Prunable force-deletes soft-deleted
     * models that match this query.
     */
    public function prunable(): Builder
    {
        return static::onlyTrashed()
            ->where('deleted_at', '<=', now()->subDays((int) config('sync.tombstone_grace_days')));
    }

    /**
     * Runs before each row is removed for good: clean up stored files here.
     */
    protected function pruning(): void
    {
        // Storage::delete($this->attachment_path);
    }
}

The Merkle index: 256 buckets keyed by the first byte of SHA-256 of the id, leaves hash id:version:deleted lines with the 0x00 prefix, nodes with 0x01:

php
<?php

namespace App\Support;

use InvalidArgumentException;

/**
 * A two-level Merkle tree over 256 buckets, with the RFC 6962 hashing rules:
 * leaf = SHA-256(0x00 || bucket contents), node = SHA-256(0x01 || left || right).
 *
 * The leaf contents are the sorted lines "id:version:deleted" of the bucket,
 * tombstones included, so a delete changes the hash exactly like an update.
 */
final class MerkleIndex
{
    public const BUCKETS = 256;

    /** The bucket of a row: the first byte of SHA-256 of its id. */
    public static function bucketFor(string $id): int
    {
        return hexdec(substr(hash('sha256', $id), 0, 2));
    }

    /**
     * @param  iterable<array{id: string, version: int, deleted: bool}>  $rows
     */
    public static function leafHash(iterable $rows): string
    {
        $lines = [];
        foreach ($rows as $row) {
            $lines[] = $row['id'].':'.$row['version'].':'.($row['deleted'] ? 1 : 0);
        }
        sort($lines, SORT_STRING);

        return hash('sha256', "\x00".implode("\n", $lines));
    }

    /**
     * @param  list<string>  $leafHashes  hex, one per bucket, in bucket order
     */
    public static function root(array $leafHashes): string
    {
        if (count($leafHashes) !== self::BUCKETS) {
            throw new InvalidArgumentException('expected '.self::BUCKETS.' bucket hashes');
        }

        $level = array_map(hex2bin(...), $leafHashes);
        while (count($level) > 1) {
            $next = [];
            for ($i = 0; $i < count($level); $i += 2) {
                $next[] = hash('sha256', "\x01".$level[$i].$level[$i + 1], true);
            }
            $level = $next;
        }

        return bin2hex($level[0]);
    }

    /**
     * Bucket indexes whose hashes differ between server and client.
     *
     * @param  list<string>  $server
     * @param  list<string>  $client
     * @return list<int>
     */
    public static function divergent(array $server, array $client): array
    {
        $out = [];
        foreach ($server as $i => $hash) {
            if (! hash_equals($hash, $client[$i] ?? '')) {
                $out[] = $i;
            }
        }

        return $out;
    }
}

The sync endpoints: root comparison, then one round of bucket hashes; rows of divergent buckets are returned with withTrashed() so deletes travel; clients older than the grace period get 409 and must resync:

php
<?php

namespace App\Http\Controllers;

use App\Models\Document;
use App\Support\MerkleIndex;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * Merkle-based sync for offline clients.
 *
 * 1. GET  /sync/root  -> the root hash. Equal to the client's root: done.
 * 2. POST /sync/diff  -> the client sends its 256 bucket hashes; the server
 *    answers with every row (tombstones included) of the divergent buckets.
 *
 * A client whose last sync is older than the tombstone grace period may hold
 * rows whose tombstones were already pruned, so it must resync from scratch:
 * the same rule as repairing every Cassandra node within gc_grace_seconds.
 */
class SyncController extends Controller
{
    public function root(): JsonResponse
    {
        return response()->json([
            'root' => MerkleIndex::root($this->bucketHashes()),
            'buckets' => MerkleIndex::BUCKETS,
            'tombstone_grace_days' => (int) config('sync.tombstone_grace_days'),
            'server_time' => now()->toIso8601String(),
        ]);
    }

    public function diff(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'last_synced_at' => ['required', 'date'],
            'buckets' => ['required', 'array', 'size:'.MerkleIndex::BUCKETS],
            'buckets.*' => ['required', 'string', 'regex:/^[0-9a-f]{64}$/'],
        ]);

        $grace = (int) config('sync.tombstone_grace_days');
        if ($request->date('last_synced_at')->lt(now()->subDays($grace))) {
            return response()->json(['resync_required' => true], 409);
        }

        $divergent = MerkleIndex::divergent($this->bucketHashes(), array_values($validated['buckets']));

        $rows = Document::withTrashed()
            ->whereIn('sync_bucket', $divergent)
            ->orderBy('id')
            ->get(['id', 'version', 'title', 'payload', 'deleted_at'])
            ->map(fn (Document $d): array => [
                'id' => $d->id,
                'version' => $d->version,
                'deleted' => $d->trashed(),
                'title' => $d->trashed() ? null : $d->title,
                'payload' => $d->trashed() ? null : $d->payload,
            ]);

        return response()->json([
            'divergent_buckets' => $divergent,
            'rows' => $rows,
            'server_time' => now()->toIso8601String(),
        ]);
    }

    /**
     * One hash per bucket, tombstones included. For large tables keep these
     * in a sync_buckets table updated on write instead of scanning.
     *
     * @return list<string>
     */
    private function bucketHashes(): array
    {
        $byBucket = array_fill(0, MerkleIndex::BUCKETS, []);

        Document::withTrashed()
            ->toBase()
            ->select(['id', 'version', 'deleted_at', 'sync_bucket'])
            ->lazyById(2000, 'id')
            ->each(function (object $row) use (&$byBucket): void {
                $byBucket[(int) $row->sync_bucket][] = [
                    'id' => (string) $row->id,
                    'version' => (int) $row->version,
                    'deleted' => $row->deleted_at !== null,
                ];
            });

        return array_map(MerkleIndex::leafHash(...), $byBucket);
    }
}
php
<?php

use App\Http\Controllers\SyncController;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->group(function () {
    Route::get('/sync/root', [SyncController::class, 'root']);
    Route::post('/sync/diff', [SyncController::class, 'diff']);
});

Configuration, schema and the pruning schedule (onOneServer() and withoutOverlapping() so two servers never prune at once):

php
<?php

return [
    // How long a soft-deleted row (tombstone) is kept before model:prune
    // removes it. Clients offline longer than this must resync from scratch.
    'tombstone_grace_days' => (int) env('SYNC_TOMBSTONE_GRACE_DAYS', 30),
];
php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('documents', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->string('title');
            $table->json('payload')->nullable();
            $table->unsignedInteger('version')->default(0);
            $table->unsignedSmallInteger('sync_bucket');
            $table->timestamps();
            $table->softDeletes(); // deleted_at: the tombstone
            $table->index(['sync_bucket', 'id']);
            $table->index('deleted_at'); // the pruning query scans by age
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('documents');
    }
};
php
<?php

use App\Models\Document;
use Illuminate\Support\Facades\Schedule;

// Tombstone garbage collection. Run on one server only, never overlapping,
// and keep the grace period longer than the longest supported offline time.
Schedule::command('model:prune', ['--model' => [Document::class]])
    ->dailyAt('03:30')
    ->onOneServer()
    ->withoutOverlapping();

Tests for the hashing rules (a tombstone changes the leaf and the root, row order does not matter):

php
<?php

namespace Tests\Unit;

use App\Support\MerkleIndex;
use PHPUnit\Framework\TestCase;

class MerkleIndexTest extends TestCase
{
    public function test_empty_buckets_have_a_stable_root(): void
    {
        $leaves = array_fill(0, MerkleIndex::BUCKETS, MerkleIndex::leafHash([]));

        $this->assertSame(MerkleIndex::root($leaves), MerkleIndex::root($leaves));
        $this->assertSame(64, strlen(MerkleIndex::root($leaves)));
    }

    public function test_a_tombstone_changes_the_leaf_and_the_root(): void
    {
        $live = [['id' => 'a1', 'version' => 3, 'deleted' => false]];
        $dead = [['id' => 'a1', 'version' => 3, 'deleted' => true]];
        $this->assertNotSame(MerkleIndex::leafHash($live), MerkleIndex::leafHash($dead));

        $server = array_fill(0, MerkleIndex::BUCKETS, MerkleIndex::leafHash([]));
        $client = $server;
        $server[17] = MerkleIndex::leafHash($dead);
        $client[17] = MerkleIndex::leafHash($live);

        $this->assertNotSame(MerkleIndex::root($server), MerkleIndex::root($client));
        $this->assertSame([17], MerkleIndex::divergent($server, $client));
    }

    public function test_row_order_does_not_matter(): void
    {
        $a = ['id' => 'a', 'version' => 1, 'deleted' => false];
        $b = ['id' => 'b', 'version' => 2, 'deleted' => false];
        $this->assertSame(MerkleIndex::leafHash([$a, $b]), MerkleIndex::leafHash([$b, $a]));
    }

    public function test_buckets_are_in_range(): void
    {
        foreach (['0', 'x', '0195d7a2-6c1e-7a8b-9f00-000000000000'] as $id) {
            $bucket = MerkleIndex::bucketFor($id);
            $this->assertGreaterThanOrEqual(0, $bucket);
            $this->assertLessThan(MerkleIndex::BUCKETS, $bucket);
        }
    }
}

The Laravel angle ​

Laravel featureRole in this chapterNote (Laravel 13 docs)
SoftDeletes trait, $table->softDeletes()Tombstone column deleted_at"a deleted_at attribute is set on the model indicating the date and time at which the model was "deleted""
withTrashed() / onlyTrashed()Include tombstones in sync hashes and responsesWithout it, deletes are invisible to the sync API
trashed()Tell a tombstone from a live rowUsed to null the payload of deleted rows in responses
restore()Undo within the grace periodMass restore() dispatches no model events
forceDelete()Remove for goodWhat Prunable calls for soft-deleted models
Prunable + prunable() + pruning()Garbage collection with per-model cleanup"Soft deleting models will be permanently deleted (forceDelete) if they match the prunable query"
MassPrunableOne DELETE query, no eventsFaster; pruning() is not called
Schedule::command('model:prune')Daily GC--model, --except, --pretend
onOneServer(), withoutOverlapping()One pruner at a timeNeeds a shared cache driver for the lock
lazyById()Hash buckets without loading the tableChunked by primary key
Model events (trashed, forceDeleted, restored)Push invalidations to caches or searchtrashed fires on soft delete

Solving the classic problems ​

Deleted data came back (zombie rows) ​

Symptom: rows deleted days ago are returned again, usually after a node rejoined or was restored from a snapshot. Cause: a replica missed the delete and the tombstone was purged (older than gc_grace_seconds) before that replica was repaired, or the delete was a hard delete in a system that merges replicas.

SolutionHowAdvantageCost / limitation
Repair cadence below the grace periodFull or incremental repair of every node, finishing within gc_grace_seconds minus slackThe actual guaranteeDisk and network I/O on a schedule
Rebuild, do not rejoinA node down longer than gc_grace_seconds is wiped and re-bootstrappedNo stale data entersStreaming a full node
check_data_resurrectionStartup check in cassandra.yamlStops the mistake at the doorMust be enabled; heartbeat file per node
only_purge_repaired_tombstonesCompaction drops tombstones only from repaired dataPurge cannot outrun repairTombstones pile up if repair stops
Re-deleteIssue the delete again with a newer timestampFixes a known set of keysYou must know which keys came back
sql
-- Cassandra (CQL): keep the grace period above the repair cycle, purge only repaired data
ALTER TABLE shop.carts
  WITH gc_grace_seconds = 864000
  AND compaction = {'class': 'SizeTieredCompactionStrategy', 'only_purge_repaired_tombstones': 'true'};

-- re-delete known zombies with a timestamp newer than any old copy (microseconds)
DELETE FROM shop.carts USING TIMESTAMP 1795651200000000 WHERE cart_id = 42;

Repair takes forever or streams far too much ​

Symptom: a repair of one table streams gigabytes for a few changed rows, or never finishes inside the window. Cause: low tree resolution (too many keys per leaf), whole-node repairs, overlapping repair runs.

SolutionHowAdvantageCost / limitation
Subrange repairnodetool repair -st <start> -et <end>, or Reaper segments, or Auto Repair splittersHigher resolution per tree, small retryable unitsMany sessions to coordinate
More tree memoryRaise repair_session_space; set concurrent_merkle_tree_requestsFewer over-streamed bytesHeap pressure
Incremental between full runsnodetool repair (default) daily, --full weeklySkips already repaired dataRepaired set not re-checked
Preview firstnodetool repair --previewShows expected streaming without doing itStill builds trees
One schedulerReaper or Auto Repair, not both plus cronNo overlapping sessionsTool to operate

Queries fail with TombstoneOverwhelmingException ​

Symptom: Scanned over 100001 tombstones during query ...; query aborted, preceded for weeks by tombstone warnings. Cause: a delete-heavy access pattern inside a partition (queue tables, "delete the oldest" retention, overwriting collections).

SolutionHowAdvantageCost / limitation
Time-bucketed partitionsPartition key includes day or hour; drop whole bucketsOne partition tombstone per bucketQueries span buckets
TTL + Time Window CompactionUSING TTL and TWCS windowsWhole SSTables expireDo not mix TTL and non-TTL data
Range deletesDELETE ... WHERE pk = ? AND ts < ?One range tombstoneReads must still skip the range
Read from where live data startsClustering-range predicate after the deleted regionNever scans the tombstonesNeeds a known boundary
Move the queueA broker instead of a tableThe right toolMigration

A node was down longer than the hint window ​

Symptom: a node rejoins after five hours; reads at ONE from it return old data; nothing errors. Cause: hints stopped after max_hint_window (3 hours).

text
     Runbook
1    node back up, gossip shows UN
2    downtime > max_hint_window ? yes -> repair this node now: nodetool repair (or let the scheduler prioritise it)
3    downtime > gc_grace_seconds ? yes -> do not repair: wipe data and replace/rebootstrap the node instead
4    until repair finishes, read at LOCAL_QUORUM so blocking read repair covers hot keys

Offline clients resurrect deleted records ​

Symptom: documents deleted on the web reappear after a phone syncs. Cause: hard deletes and updated_at polling, or soft-deleted rows pruned before every client synced. Fix: tombstones in the sync payload, pruning after a grace period, and a hard rule for clients older than the grace period.

sql
-- PostgreSQL: soft delete as a tombstone, live-row index, batched GC
CREATE TABLE documents (
    id          uuid PRIMARY KEY,
    title       text NOT NULL,
    payload     jsonb,
    version     integer NOT NULL DEFAULT 1,
    sync_bucket smallint NOT NULL,
    updated_at  timestamptz NOT NULL DEFAULT now(),
    deleted_at  timestamptz            -- NULL = live, NOT NULL = tombstone
);
CREATE INDEX documents_live_idx ON documents (sync_bucket, id) WHERE deleted_at IS NULL;
CREATE INDEX documents_tombstone_age_idx ON documents (deleted_at) WHERE deleted_at IS NOT NULL;

-- delete = write a tombstone; strip the payload now if erasure requires it
UPDATE documents SET deleted_at = now(), payload = NULL, version = version + 1 WHERE id = $1;

-- GC: remove tombstones older than the grace period, 5000 at a time (repeat until 0 rows)
DELETE FROM documents
WHERE id IN (
    SELECT id FROM documents
    WHERE deleted_at < now() - interval '30 days'
    ORDER BY deleted_at
    LIMIT 5000
    FOR UPDATE SKIP LOCKED
);

-- bucket hashes for the sync endpoint (tombstones included)
SELECT sync_bucket,
       encode(sha256(convert_to(string_agg(id::text || ':' || version || ':' ||
              (deleted_at IS NOT NULL)::int, E'\n' ORDER BY id::text), 'UTF8')), 'hex') AS content_hash
FROM documents
GROUP BY sync_bucket
ORDER BY sync_bucket;

The SQL bucket hash shows the idea (it omits the RFC 6962 0x00 prefix, so it is not byte-identical to MerkleIndex::leafHash); the Laravel code is the version to ship. Go with database/sql runs the same GC statement in a loop until RowsAffected() returns 0.

A Kafka consumer missed a delete ​

Symptom: a cache rebuilt from a compacted topic still contains users that were deleted. Cause: the rebuild took longer than delete.retention.ms, so the tombstone was cleaned before the consumer reached it, after the consumer had already read the old value.

SolutionHowAdvantageCost / limitation
Longer tombstone retentiondelete.retention.ms above the longest full replay (for example 7 days)SimpleMore tombstones kept
Snapshot plus tailRebuild from a snapshot, then consume from its offsetFast rebuildsSnapshot management
Lag alertAlert when a rebuilding consumer's lag time approaches delete.retention.msEarly warningMonitoring only

Prove a record is in an audit log ​

Use the RFC 6962 tree: append each audit record as a leaf, publish the root (and size) daily somewhere you cannot silently edit, give auditors inclusion proofs for records and consistency proofs between published roots. The merkle package does exactly this; golang.org/x/mod/sumdb/tlog is the production implementation behind the Go checksum database.

Choosing ​

Which convergence mechanism for which drift ​

SituationMechanismExtra techniqueReason
Rolling restarts, short maintenanceHinted handoffKeep max_hint_window above the longest planned outageCheap, replays within minutes
Hot keys read at QUORUMBlocking read repairRead at LOCAL_QUORUMConverges what users see, free
Cold data, archives, anything deletedScheduled anti-entropy repairIncremental daily, full weekly, inside gc_grace_secondsThe only path that reaches unread data
Node down past the hint windowTargeted repair of that nodePrioritise in Reaper or Auto RepairHints no longer cover it
Node down past gc_grace_secondsReplace or rebootstrap, never rejoincheck_data_resurrectionRejoining resurrects deletes
Replication factor increased, node addedFull repairnodetool repair -fullNew replicas start empty
Suspected disk corruptionFull repair or --validate firstRiak: weekly tree regeneration does thisIncremental never re-checks repaired data
Phone or browser clientsMerkle bucket sync or changes feedTombstones in payload, resync after graceClients can be offline for weeks
Public, append-only evidenceRFC 6962 tree with published rootsInclusion + consistency proofsVerifiable by outsiders
Large files between serversrsync--checksum when timestamps lieRolling checksums find moved blocks

Which delete strategy ​

DataDelete strategyGrace / retentionWhy
Cassandra rows deleted by the applicationTombstones, coarsest level possiblegc_grace_seconds = repair cycle + slack (default 10 days)Correctness under replica failures
Cassandra data that only expiresTTL + TWCSLower gc_grace_seconds is safe if never deleted or updatedEvery replica expires on its own
Queue-like dataNot in Cassandra: a brokern/aTombstone overload
Compacted Kafka topicnull-value tombstonedelete.retention.ms above longest replayRebuilds must see deletes
SQL rows that clients or other systems copySoft delete + pruningLonger than the longest offline clientDeletes must reach copies
SQL rows nobody copiesHard deleteNoneSimplest; nothing to propagate
Personal data under erasure rulesTombstone with payload stripped now, row pruned laterShort, documentedErasure of content now, id later

In architecture: from a single process to a distributed system ​

Repair and tombstones exist because copies exist. Every step below adds a kind of copy, and each copy needs a way to learn about writes and deletes it missed.

Monolith: one process, one database ​

One PostgreSQL database with synchronous writes has no divergent replicas, so no anti-entropy. Deletes are still worth thinking about once anything outside the database keeps a copy: a browser cache, a CSV export, a search index updated by a cron job. Example: a Laravel app with a "trash" feature uses SoftDeletes for undo and Prunable to empty the trash after 30 days; nothing else copies the table, so a hard DELETE would also be correct. The PostgreSQL MVCC dead tuples that VACUUM removes are the database's own internal tombstones (MVCC, VACUUM & Bloat).

Modular monolith: boundaries without the network ​

Modules that keep their own read models (a search module, a reporting module) copy data from the owning module. If they are fed by "changed since" queries, hard deletes in the owner are invisible to them. Example: the billing module soft-deletes invoices and publishes an in-process InvoiceDeleted event; the reporting module removes its row on the event and also runs a weekly reconciliation that compares per-month hashes of invoice ids with billing (a two-level Merkle comparison) to catch missed events.

Microservices: every copy needs a delete path ​

Each service owns its data, and other services hold projections. Deletes must travel as events (outbox, Transactional Outbox), and every consumer must keep the delete long enough for its own replicas and caches. Example:

text
     users-service                     Kafka topic users (compacted)            search-service, mail-service
1    DELETE user 7 -> outbox row
2    relay publishes key=7, value=null  ->  tombstone at offset 9001
3                                                                               search: remove doc 7; mail: unsubscribe 7
4    nightly: each consumer sends per-bucket hashes of its user ids to users-service /reconcile
5    users-service returns divergent buckets -> consumer fixes them (catches lost events and zombies)

The reconciliation step is anti-entropy between services. It is what makes "eventually consistent" true when an event was lost, a consumer was rebuilt from an old snapshot, or a bug skipped messages.

Distributed data: replicas, caches, regions ​

Leaderless stores (Cassandra, ScyllaDB, Riak) need all three paths and a repair schedule inside gc_grace_seconds; multi-region Cassandra adds cross-datacenter repair (-dc, -dcpar, -local) and hints that are slower across regions (max_hints_delivery_threads). Leader-based stores (PostgreSQL, MySQL) ship a log to replicas and do not need Merkle repair for normal operation, but tools that verify replicas compare checksums of chunks of tables, the same idea. Caches in front of any store need deletes as invalidations, or a negative entry with a TTL, or they serve deleted data until expiry (Caching). CRDT-based stores turn deletes into set operations with their own tombstone or causal-context machinery (CRDTs).

Scaling path: 1x, 10x, 100x ​

ScaleWhat changesRepair and delete design
1x: one database, a few clientsCopies are rareSoft delete where copies exist; prune with model:prune
10x: replicas, a cache, a search index, mobile clientsMany copies with independent lagDeletes as events; Merkle bucket sync for clients; reconciliation jobs
100x: leaderless cluster, many regionsReplicas diverge dailyRepair scheduler (Reaper / Auto Repair), subrange repair, repair-age alerts against gc_grace_seconds, data models without queue-like tombstone churn

Lab: proofs, diff cost and the three delete scenarios ​

Part A runs on your machine in under a second (a single-process Go program; the output below is from a real run). Parts B and C need a Cassandra cluster and a Laravel app and are written as commands with expected output, not run.

A1. Run the tests and the lab driver.

bash
cd docs/snippets/system-design/merkle-trees-anti-entropy/go
go test ./...
go run ./cmd/aesim
text
ok   academy/merkle-trees-anti-entropy/antientropy
ok   academy/merkle-trees-anti-entropy/before
ok   academy/merkle-trees-anti-entropy/kvsim
ok   academy/merkle-trees-anti-entropy/merkle
== 1. RFC 6962 tree: root, inclusion proof, consistency proof
leaves=1000000 root=9b6f9226d33c8d01...
inclusion proof for leaf 123456: 20 hashes (640 bytes), valid=true
consistency proof 600000 -> 1000000: 15 hashes, valid=true
== 2. one divergent key among 100000: cost by branching factor
fanout  depth  buckets  rounds  hashes  streamed
2       4      16       5       9       6110
2       16     65536    17      33      2
4       8      65536    9       33      2
16      4      65536    5       65      2
256     2      65536    3       513     2
65536   1      65536    2       65537   2
== 3. replica c misses a delete (down 4h, hint window 3h)
hard delete                              hints_dropped=1 purged=0 streamed=2 -> read found=true "3 items"
tombstone, gc_grace 10d, back after 5h   hints_dropped=1 purged=0 streamed=2 -> read found=false ""
tombstone, gc_grace 1d, back after 2d    hints_dropped=1 purged=2 streamed=2 -> read found=true "3 items"

Read it as the chapter in numbers: a million-leaf log proves membership with 640 bytes; the same one-key difference costs 9 to 65,537 hash comparisons and 2 to 6,110 streamed keys depending only on tree shape; and the delete scenario reproduces the Cassandra documentation's "deletes without tombstones" and "tombstone expired before repair" cases.

A2. Break it on purpose. In kvsim_test.go, change GCGrace in TestTombstoneSurvivesRepair to 1 * hour and run go test ./kvsim/ -run Survives -v: the test now fails because the tombstone was purged during the outage. Change Fanout: 16, Depth: 2 to Fanout: 2, Depth: 1 in TestRepairCostFollowsTheDifference: the streamed count jumps to thousands (over-streaming).

B. Cassandra: a zombie in four commands (expected, not run). Three nodes, RF = 3, gc_grace_seconds lowered for the experiment only.

bash
cqlsh -e "CREATE KEYSPACE lab WITH replication = {'class':'SimpleStrategy','replication_factor':3};
          CREATE TABLE lab.t (id int PRIMARY KEY, v text) WITH gc_grace_seconds = 60;
          INSERT INTO lab.t (id, v) VALUES (1, 'alive');"
nodetool -h node1 disablehandoff; nodetool -h node2 disablehandoff  # no hints: simulate an outage past max_hint_window
nodetool -h node3 disablegossip && nodetool -h node3 disablebinary   # node3 stops receiving writes
cqlsh -e "CONSISTENCY QUORUM; DELETE FROM lab.t WHERE id = 1;"
sleep 120; nodetool -h node1 flush lab t; nodetool -h node1 compact lab t; nodetool -h node2 flush lab t; nodetool -h node2 compact lab t
nodetool -h node3 enablegossip && nodetool -h node3 enablebinary
nodetool -h node3 repair --full lab t
cqlsh -e "CONSISTENCY ALL; SELECT * FROM lab.t WHERE id = 1;"
text
 id | v
----+-------
  1 | alive          <- expected: the deleted row is back (a zombie)

Run nodetool enablehandoff on node1 and node2 afterwards. Repeat with the default gc_grace_seconds = 864000: the final select returns (0 rows) because the tombstone was still present and repair streamed it to node3.

C. Laravel: tombstones in the sync API (expected, not run).

bash
php artisan migrate
php artisan tinker --execute="\$d = App\Models\Document::create(['title' => 'note']); \$d->delete(); echo \$d->id;"
curl -s localhost:8000/api/sync/root -H "Authorization: Bearer $TOKEN"
# {"root":"5f1c...","buckets":256,"tombstone_grace_days":30,"server_time":"2026-11-26T10:00:00+00:00"}
curl -s -X POST localhost:8000/api/sync/diff -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
     -d '{"last_synced_at":"2026-11-20T00:00:00Z","buckets":[ ...256 hashes of an empty client... ]}'
# {"divergent_buckets":[173],"rows":[{"id":"...","version":1,"deleted":true,"title":null,"payload":null}],...}
php artisan model:prune --pretend
# expected: 0 Document records will be pruned (the tombstone is younger than 30 days)
curl -s -X POST localhost:8000/api/sync/diff ... -d '{"last_synced_at":"2026-09-01T00:00:00Z", ...}'
# HTTP 409 {"resync_required":true}

D. Proof by hand. With the eight CT test inputs from merkle_test.go, compute the audit path for index 5 with tree.InclusionProof(5, 8) and walk the four steps of the inclusion proof timeline on paper with the printed hashes; the result must equal 5dc9da79a70659a9....

Common misconceptions ​

BeliefReality
Quorum reads and writes make repair unnecessaryQuorums do not copy data to replicas that missed it; only repair guarantees convergence and delete propagation
A Merkle tree compares data cheaplyIt makes the network comparison cheap; building it reads all the data (validation compaction)
Read repair fixes every replica of a keyOnly the replicas the read contacted; none at ONE/LOCAL_ONE
read_repair_chance gives background repair for freeRemoved in Cassandra 4.0; it never reached cold data
Hinted handoff makes a returning node consistentOnly for outages shorter than max_hint_window (3h) with hint files intact
Deleting data frees space and speeds readsA delete is a write; space returns after compaction past gc_grace_seconds
Lowering gc_grace_seconds fixes tombstone problemsIt trades tombstone overhead for zombie risk; fix the data model instead
TTL avoids tombstonesExpired cells become tombstones; TTL + TWCS lets whole SSTables expire
Incremental repair is all you needRepaired data is never re-checked; run full repair periodically
nodetool repair repairs the clusterIt repairs the ranges of one node; use -pr on every node or a scheduler
Soft delete is only for undoIt is the tombstone every copy of the table needs to learn about deletes
CouchDB replication is Merkle-basedIt is a changes feed with checkpoints and _revs_diff
An inclusion proof proves a log is honestOnly relative to a root you trust; consistency proofs and gossip of tree heads are needed against split views

Cheat sheet ​

TopicRemember
Merkle treeLeaves hash data, nodes hash children, root summarises all; compare top-down
RFC 6962 hashingLeaf `SHA-256(0x00
Proof sizesInclusion ceil(log2 n), consistency ceil(log2 n) + 1; 1M leaves: 20 hashes
Diff costIdentical: 1 hash; k differences: about 1 + k * b * d hashes, d + 1 rounds
ResolutionKeys per leaf decide over-streaming; Cassandra: repair_session_space, subrange repair
Three pathsHints (write), read repair (read), anti-entropy (background); only the last is a guarantee
Hintsmax_hint_window 3h default; longer outage means repair that node
Read repairDigest requests, mismatch, full reads, newest wins, BLOCKING default, NONE for batch atomicity
Cassandra repairIncremental default, --full periodically, -pr per node, Reaper or Auto Repair, --preview, --validate
The ruleRepair every replica within gc_grace_seconds (default 864000 = 10 days)
Tombstone limitsWarn 1000, fail 100000 (TombstoneOverwhelmingException)
Tombstone kindsCell, row, range, partition, TTL; delete at the coarsest level
Kafkanull value = tombstone; delete.retention.ms 1 day default; slow rebuilds miss deletes
LaravelSoftDeletes = tombstone, withTrashed() in sync, Prunable + model:prune = GC after grace
ClientsInclude deletes in sync; refuse (409) clients older than the grace period

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Two replicas each hold 50 million keys in a tree with 65,536 leaves. They are identical except for one key. How many hashes are compared with fan-out 16, and roughly how many keys are streamed? Good to know ​

Answer

Answer: 65,536 = 16^4, so depth 4: 1 root + 16 per level x 4 levels = 65 hashes in 5 rounds. One leaf differs; it holds about 50,000,000 / 65,536, roughly 760 keys, which are streamed (over-streaming), not 50 million.

2 — Why does RFC 6962 prefix leaves with 0x00 and nodes with 0x01? Good to know ​

Answer

Answer: Domain separation. Without it, the 64 bytes of two child hashes could be presented as a leaf's data, producing the same root for a different list (a second preimage). The RFC: "This domain separation is required to give second preimage resistance."

3 — A browser holds a signed tree head for size 8 and receives the audit path [h4, h(6-7), h(0-3)] for leaf 5. Write the hash computations. Good to know ​

Answer

Answer: r = H(0x01 || h4 || leaf5), then r = H(0x01 || r || h(6-7)), then r = H(0x01 || h(0-3) || r); compare with the signed root. Index 5 is odd (sibling on the left), 2 is even (sibling on the right), 1 is odd (sibling on the left).

4 — A Cassandra node was down for five hours. Hints are enabled with defaults. Which writes did it miss permanently, and what fixes them? Important ​

Answer

Answer: Writes after the first three hours (max_hint_window = 3h): coordinators stopped generating hints. Hints replay the first three hours. The rest are fixed by read repair for keys read at QUORUM/LOCAL_QUORUM, and only fully by an anti-entropy repair of that node.

5 — Why can read repair at LOCAL_QUORUM not replace scheduled repair, even on a read-heavy table? Must-know ​

Answer

Answer: It repairs only keys that are read, and only on the replicas that read contacted. Cold keys and deletes of keys nobody reads are never repaired, and after gc_grace_seconds their tombstones are purged: resurrection.

6 — Describe the exact sequence that turns a delete into a zombie in Cassandra. Important ​

Answer

Answer: A replica misses the delete (down past the hint window); the other replicas keep the tombstone for gc_grace_seconds, then compaction drops the tombstone and the shadowed data; the replica returns with the old value; repair (or read repair) sees data on one replica and nothing on the others and copies the data back.

7 — Your team wants to lower gc_grace_seconds from 10 days to 1 hour on a table because of tombstone warnings. When is that safe? Important ​

Answer

Answer: Only when no replica can miss a delete for longer than an hour, which in practice means: the table is never explicitly deleted from or updated, and data only expires by TTL (every replica expires it independently). Otherwise fix the model (time buckets, range or partition deletes, TWCS) instead.

8 — Why should full repair still run if incremental repair runs every day? Important ​

Answer

Answer: Incremental repair marks data repaired and never compares it again. Disk corruption, operator mistakes and bugs in already repaired data are invisible to it; only a full repair (or --validate) re-checks the repaired set.

9 — A compacted Kafka topic has delete.retention.ms of 1 day. A service rebuilds its cache from offset 0, which takes 30 hours. What can go wrong? Important ​

Answer

Answer: It reads an old value for key k early; the tombstone for k (written after that value) is cleaned 24 hours after it was written; the consumer reaches that offset later and never sees the delete. The cache keeps k forever. Raise delete.retention.ms above the replay time or rebuild from a snapshot.

10 — An offline-first app keeps soft-deleted rows 30 days. A phone comes back after 45 days. What must the API do and why? Important ​

Answer

Answer: Refuse incremental sync (this page: 409 resync_required) and make the client download a fresh copy. Tombstones for documents deleted more than 30 days ago were pruned, so the phone's copies of them cannot be told apart from documents the server never received; syncing them would resurrect deleted data.

11 — Is CouchDB replication a Merkle-tree protocol? How does it carry deletes? Good to know ​

Answer

Answer: No. It reads the source's changes feed from a checkpoint, asks the target with _revs_diff which revisions it lacks, copies them and saves a checkpoint. A delete is a new revision with _deleted: true, so it replicates like any revision until _purge removes it.

12 — Why does Riak rebuild its AAE hash trees periodically even though they are updated on every write? Good to know ​

Answer

Answer: Trees updated on write reflect what was written, not what is on disk now. Regenerating "all hash trees from on-disk key/value data" (weekly by default) detects silent corruption of stored data, which incremental tree maintenance would never notice.

Glossary ​

TermMeaning
Merkle tree (hash tree)Tree whose leaves hash data blocks and whose inner nodes hash their children
Root hashThe hash at the top; equal roots mean equal contents (with overwhelming probability)
LeafBottom node: the hash of one item or one key range
Branching factor (fan-out)Children per inner node; higher means fewer rounds, more hashes per round
DepthLevels below the root; leaves = fan-out^depth for a complete tree
ResolutionKeys per leaf; low resolution causes over-streaming
Inclusion proof (audit path, audit proof)Sibling hashes from a leaf to the root that prove the leaf is in the tree
Authentication pathMerkle's 1979 name for the audit path
Consistency proofHashes proving a smaller tree is a prefix of a larger one (append-only growth)
Signed Tree Head (STH)A CT log's signed root hash and size
Certificate TransparencyPublic append-only logs of TLS certificates (RFC 6962, RFC 9162)
RFC 69622013 Experimental RFC defining the CT Merkle Tree Hash, audit paths and consistency proofs
Second preimageA different input with the same hash; prevented in RFC 6962 by the 0x00/0x01 prefixes
Content addressingNaming data by the hash of its content
Git objectBlob, tree, commit or tag stored under its hash; trees list child hashes
Anti-entropyBackground comparison and reconciliation of replicas (Demers 1987)
Active anti-entropy (AAE)Riak's continuous anti-entropy with persistent, write-updated hash trees
RepairCassandra's operator-run anti-entropy: Merkle trees per token range, stream differences
Full repairCompares all data in the ranges (nodetool repair --full)
Incremental repairCompares only unrepaired data, then marks it repaired (the default)
Repaired SSTableSSTable marked as covered by a completed incremental repair; compacted separately
Unrepaired SSTableSSTable with data not yet incrementally repaired
AnticompactionRewriting SSTables to split repaired ranges out after a repair
Validation compactionThe read of the data that builds Merkle trees during a Cassandra repair
Subrange repairRepair of a token range given by -st/-et, for higher resolution and smaller units
Primary range (-pr)The ranges for which a node is the first replica; repair them on every node to cover the ring once
nodetool repairCassandra CLI to run repair; options --full, -pr, -st/-et, --preview, --validate, -dc, -seq, -j
ReaperCentralised, stateful repair scheduler for Cassandra
Auto RepairCassandra's built-in repair scheduler (CEP-37, 6.0, backported to 5.0.8)
Row-level repairScyllaDB repair that checksums rows and reconciles sets instead of exchanging trees
Divergent rangeA token range whose hashes differ between replicas
Over-streamingStreaming more data than changed, because a leaf covers many keys
Read repairFixing stale replicas during a read on digest mismatch
Digest requestA read that returns only a hash of the data
Digest mismatchDigests from replicas differ from the full data's hash; triggers full reads and repair
Blocking read repairThe read waits until repair writes reach the consistency level (read_repair = 'BLOCKING')
Monotonic quorum readsA later quorum read never returns something older than an earlier one
read_repair_chancePre-4.0 probability of background read repair; removed in Cassandra 4.0
Hinted handoffCoordinator stores writes for a down replica and replays them later
Hint windowmax_hint_window: how long hints are generated for a down host (3h default)
Sloppy quorumWriting to the first N healthy nodes, not necessarily the key's home replicas (Dynamo)
Tombstone (delete marker)A timestamped record that a value was deleted; replicates like data
Death certificateDemers et al.'s 1987 name for a tombstone
ResurrectionDeleted data reappearing because a replica missed the delete
Zombie dataCassandra's name for resurrected data
gc_grace_secondsPer-table time tombstones are kept before compaction may drop them (864000)
tombstone_warn_thresholdTombstones scanned per query before a warning (1000)
tombstone_failure_thresholdTombstones scanned per query before abort (100000)
TombstoneOverwhelmingExceptionCassandra error when a query exceeds the failure threshold
Range tombstoneOne marker deleting a slice of rows in a partition
Partition tombstoneOne marker deleting a whole partition
TTL tombstoneAn expired cell, treated as a tombstone
CompactionMerging SSTables; drops shadowed data and old tombstones
only_purge_repaired_tombstonesCompaction option: drop tombstones only from repaired data
sstableexpiredblockersTool listing SSTables that block fully expired SSTables from being dropped
Kafka tombstoneA record with a key and null value in a compacted topic
delete.retention.msHow long Kafka keeps tombstones in compacted topics (1 day default)
Log compactionKafka keeping the latest value per key
XDELRedis Streams command that removes entries; internally marks them deleted
CouchDB replicationChanges-feed replication with checkpoints and _revs_diff
_purgeCouchDB endpoint that removes documents (including deleted ones) for good
rsyncFile sync sending only blocks the receiver lacks
Rolling checksumrsync's weak checksum that can slide one byte at a time cheaply
Soft deleteKeeping the row with deleted_at set instead of removing it
SoftDeletesLaravel trait implementing soft delete for Eloquent models
Prunable / MassPrunableLaravel traits that delete models matching prunable(); mass version runs one query
PruningScheduled removal of expired rows or tombstones (model:prune)
ResyncDiscarding a client's copy and downloading fresh data when it is older than the grace period

References ​

Built by Morteza Negahi