The Problem#
A key-value store is the simplest kind of database. You give it a key and a value, and later you give it the key and get the value back. There are no joins, no secondary queries and no schema. That simplicity is what lets a key-value store spread across hundreds of machines, accept writes even when some of those machines are down, and answer in a few milliseconds no matter how much data it holds.
In 2007, Amazon published the paper "Dynamo: Amazon's Highly Available Key-value Store" (DeCandia and colleagues, SOSP 2007). It described the store behind services such as the shopping cart. The paper combined a handful of known techniques into one design:
- consistent hashing for placement,
- N-way replication with tunable quorums,
- vector clocks for conflicting versions,
- hinted handoff for temporary failures,
- Merkle trees for repairing replicas,
- gossip for membership.
That design shaped a generation of databases, including Apache Cassandra, Riak and LinkedIn's Voldemort. "Design a distributed key-value store" is now one of the classic staff-level interview questions.
Here is the problem. Build a store that:
- holds about 100 TB across commodity machines,
- serves hundreds of thousands of reads and writes per second with single-digit millisecond latency,
- keeps accepting writes during machine failures, rack failures and network partitions,
- lets each application choose how much consistency it is willing to trade for latency and availability.
A leader-based design is the alternative, where one replica orders all writes for a shard. It is easier to reason about, but a shard cannot take writes while it has no leader. Amazon's requirement was "never reject an add-to-cart", which pushes towards a leaderless design, where any replica can accept a write. We will build the leaderless design. Later we will also explain when a leader-based design (Raft or Paxos per shard, as in DynamoDB, TiKV or CockroachDB) is the better answer, because a strong candidate knows both.
Analogy. Think of a library that keeps three copies of every book in three different branches. When you donate a new edition, the librarian you meet sends copies to all three branches but tells you "done" once two confirm. When you ask for the book, the librarian checks two branches and gives you the newest edition. If they find an old edition at one branch, they replace it. If a branch is closed, a neighbouring branch holds the book for it with a note, "deliver to branch C when it reopens". Once a month, branches compare catalogues to catch anything that slipped through. That is almost exactly the design on this page.
The concepts are covered in Quorums and Leaderless Replication, Consistent Hashing and Storage Engines: B-Trees vs LSM Trees. This page turns them into one design and explains every decision.
Clarifying Questions#
| Question | Assumed answer | Why it matters |
|---|---|---|
| What operations are needed? | get(key), put(key, value) and delete(key), with an optional TTL and an optional compare-and-set. No range scans across keys, and no secondary indexes. | Single-key operations let us hash-partition and serve every request from one replica set. Range scans would push us to range partitioning. |
| How much data? | 100 TB of logical data, growing 30-50% a year. Keys up to 1 KB, values typically 1-20 KB with a hard limit of 1 MB. | This sets the node count, the storage engine and the large-value policy. Values above 1 MB go to blob storage. |
| What traffic? | 300k reads and 100k writes per second on average, peaking at 3 times that. | Write-heavy enough that the storage engine must favour writes, which points to an LSM tree. |
| What latency? | p99 under 10 ms for reads and writes within a region. p50 around 1-2 ms. | This rules out cross-region round trips on the default path and makes tail latency a design goal. |
| What consistency? | Tunable per request. The default is a quorum: read-your-writes in the common case, with eventual convergence. Strong (linearizable) single-key writes are rare and optional. | This decides quorum sizes, conflict handling, and whether we need consensus at all. |
| Must writes succeed during failures and partitions? | Yes. "Always writable" for the default tier. A write should succeed if any replica, or even any node, can take it. | This is the decision that forces a leaderless design with sloppy quorums and conflict resolution. |
| How should concurrent writes to the same key be resolved? | The store keeps concurrent versions and returns them to the client to merge (Dynamo-style), or uses last-write-wins (Cassandra-style). Choose per table. | This is the core trade-off between correctness and simplicity. It affects the API (contexts and siblings) and the clocks. |
| Durability? | No acknowledged write may be lost when any single node or zone fails. Three replicas across three availability zones. | This sets the replication factor, the placement rules and the fsync policy. |
| Single region or multi-region? | Primary in one region, with asynchronous replication to a second region for disaster recovery. Active-active is a stretch goal. | Cross-region quorums would add 80-200 ms, so local quorums are the default. |
| Who are the clients? | Internal services, each with its own tables, via a client library. | We can use smart clients for routing and expose consistency levels in the API. |
| Is it multi-tenant? | Yes. Many teams share clusters, so we need per-table quotas. | One noisy tenant must not hurt the others' latency. |
Requirements#
Functional#
- Put.
put(key, value, context?)stores a value. The optional context, from a previous read, tells the store which versions this write replaces. - Get.
get(key)returns the value, or every concurrent version (siblings) with a context, when writes conflicted. - Delete.
delete(key, context?)removes a key, using a tombstone so the delete replicates like a write. - TTL. Values may expire automatically.
- Consistency per request. The caller chooses
ONE,QUORUM,LOCAL_QUORUMorALLfor reads and writes. - Conditional write (optional). Compare-and-set on a single key, for cases such as "create if not exists".
- Administration. Create a table with a replication factor and conflict policy. Add or remove nodes without downtime.
Non-Functional#
- Availability. 99.99% for writes at the default consistency level, which is about 4.4 minutes of unavailability a month. Writes keep working while one zone is down.
- Latency. p99 under 10 ms and p50 under 2 ms for single-key operations inside a region.
- Durability. Three replicas in three zones. An acknowledged quorum write survives the loss of any one zone.
- Scalability. Capacity and throughput grow linearly with nodes. Adding a node moves only about 1/N of the data.
- Decentralisation. No single point of failure and no special master on the data path. Every node runs the same software and can coordinate any request.
- Convergence. All replicas of a key end up with the same value once writes stop, even after failures. This is eventual consistency with a bounded repair time.
- Operability. Rolling upgrades, live rebalancing, repair, and clear metrics on replica divergence.
Capacity Estimation#
Data size. We hold 100 TB of logical data. With an average entry of about 10 KB (a 100-byte key, a 10 KB value, plus about 50 bytes of metadata: version, timestamp, TTL and flags), that is about 10^10 keys, ten billion.
Raw storage. Three replicas make 300 TB. An LSM storage engine needs headroom on top of that. Old SSTable versions sit on disk until compaction removes them. Tombstones and overwritten values wait to be purged. And compaction itself needs temporary space. With leveled compaction, space amplification is about 1.1-1.2 times. With size-tiered compaction, it can briefly reach 2 times during a large compaction. Planning for 1.5 times gives 450 TB of physical data. We keep disks at most about 60% full, so that a node can absorb a failed neighbour's share and compactions never run out of space. That means about 750 TB of raw disk.
Node count by storage. A typical storage node has 8 TB of NVMe SSD, 256 GB of RAM and 32 cores. 750 TB ÷ 8 TB ≈ 94 nodes. We round up to ~108 nodes, 36 per availability zone. Multiples of the zone count keep placement symmetrical.
Write throughput. Peak load is 300k writes per second, and each write goes to 3 replicas, so 900k replica writes per second, or about 8.3k per second per node. The bytes involved:
- Incoming data. 8.3k writes × 10 KB ≈ 83 MB/s per node. That goes once to the write-ahead log and later once to the first SSTable.
- Compaction. It rewrites data many times. Leveled compaction typically has a write amplification of 10-30. At 10 times that is about 830 MB/s of background writes per node at peak. A modern NVMe drive sustains 2-3 GB/s of sequential writes, so this fits, but it shows why compaction strategy and throttling are first-class design topics. Size-tiered compaction cuts write amplification to about 3-5, at the cost of read and space amplification.
Read throughput. Peak load is 900k reads per second. With QUORUM reads (R = 2 of 3), each read touches 2 replicas: 1.8M replica reads per second, or about 17k per node. Some designs ask one replica for the full value and the other for a digest, which saves bandwidth. Most reads should be served from memory: the block cache, the OS page cache and the memtable. With 256 GB of RAM per node holding about 4 TB of data, roughly 6% of the data fits in memory. Under a skewed (Zipf-like) workload, the hottest 6% of data typically serves well over half of the reads. The rest cost one or two SSD reads at about 100 µs each, thanks to Bloom filters and the SSTable index. 17k reads per second × 0.4 misses × 1.5 disk reads ≈ 10k IOPS per node, far below an NVMe drive's hundreds of thousands.
Network. Per node at peak: 83 MB/s of replica writes in, about 17k × 10 KB ≈ 170 MB/s of reads out, plus coordinator traffic and streaming during repair. That is about 2-3 Gbit/s, comfortable on a 25 Gbit/s NIC. Cross-zone traffic is the expensive part in the cloud. Two of the three replica writes cross zones, so at 300k writes per second × 10 KB × 2 = 6 GB/s of cross-zone traffic at peak. Cross-zone transfer charges can rival the cost of the servers. This is a real reason some teams choose zone-local reads, compression or tiered replication.
Metadata. The ring has 108 nodes with 256 virtual nodes each, about 27,600 tokens. That is a few hundred KB of membership state, which gossip spreads easily. Bloom filters at 10 bits per key: 10^10 keys × 3 replicas ÷ 108 nodes ≈ 2.8 × 10^8 keys per node × 10 bits ≈ 350 MB of RAM per node, a small fraction of 256 GB. The SSTable index, which samples one key per 4-64 KB block, adds similar amounts.
Summary. About 108 nodes. The cluster is disk- and compaction-bound, not CPU-bound. Writes dominate background I/O, reads dominate the memory budget, and cross-zone replication dominates the network bill.
Core Entities#
- Key. An opaque byte string of up to 1 KB. Its hash decides placement.
- Value. An opaque byte string of up to 1 MB. The store does not interpret it.
- Version. Metadata attached to each stored value: either a vector clock (a list of
node → counterpairs) or a timestamp for last-write-wins, plus a tombstone flag and an optional expiry time. - Context. An opaque token returned by
getand passed back onput. It encodes the versions the client has seen, so the store can tell an update from a concurrent write. - Token and token range. Each node owns positions (tokens) on a 64- or 128-bit hash ring. A token range is the arc of hash values owned by one virtual node.
- Preference list. The ordered list of N distinct physical nodes responsible for a key: the first N distinct nodes clockwise from the key's hash, filtered by zone so that replicas land in different zones.
- Hint. A write held by a substitute node for a replica that was unreachable, tagged with its intended owner.
- Merkle tree. A hash tree summarising the data in one token range on one replica, used to find differences cheaply.
- Membership state. Each node's view of the cluster: which nodes exist, their tokens, their status and their heartbeat counters.
How applications model data in a key-value store. Because the only query is "fetch by exact key", the data model becomes very flat. Joins and secondary filters are not available. An application therefore denormalises and stores the same data under several keys, one per access pattern. For example, it might store user:42, plus email:ann@example.com → 42 so it can look a user up by email. This makes reads one fast lookup, but it moves consistency work to the application: changing an email now means updating two keys that may live on different nodes, with no multi-key transaction. In practice most systems combine stores. A relational database stays the source of truth for data that needs joins and transactions, and the key-value store holds the high-volume, single-key data, such as sessions, carts, user preferences, feature flags, counters or a cache of computed results. Ask "what is my access pattern?" before you choose: if every read is by one identifier, a key-value store is a natural fit. If reads need filtering, sorting or joining, it is not. See Choosing a Database: A Decision Guide.
API Design#
The external API is a small RPC interface, usually gRPC or a binary protocol over TCP, called from a client library. Consistency levels are per request.
get(table, key, consistency = QUORUM)
-> { values: [bytes], context: bytes } // more than one value = siblings
-> NOT_FOUND
put(table, key, value, context = null, consistency = QUORUM, ttl_sec = null)
-> { context: bytes } // new version
// context = versions this write supersedes; null = blind write
delete(table, key, context = null, consistency = QUORUM)
-> ok // writes a tombstone
cas(table, key, expected_value_or_absent, new_value) // optional, slower
-> { applied: bool, current: bytes } // uses Paxos on the key's replicas
create_table(name, replication = {zone_aware: true, n: 3},
conflict_policy = VECTOR_CLOCK | LWW, default_ttl = null)
Consistency levels: ONE | TWO | QUORUM | LOCAL_QUORUM | EACH_QUORUM | ALL
Errors: UNAVAILABLE (not enough replicas), TIMEOUT (ack count unknown),
TOO_LARGE (value > 1 MB), THROTTLED (table quota exceeded)Three API details matter in an interview:
getcan return several values. With vector clocks, the store never silently discards a concurrent write. The client, or a merge function registered for the table, merges the siblings and writes back the result with the combined context.- A timeout is not a failure. If the coordinator collected only 1 of 2 required acknowledgements before timing out, the write may still land on all replicas later. The client must treat
TIMEOUTas "unknown". Retrying aputwith the same context is safe: it is idempotent because it produces the same logical version. TOO_LARGEenforces the blob policy. Large objects should be uploaded to object storage, and only the object's location and metadata stored in the key-value store (Deep Dive 11).
High-Level Design#
We build the design one requirement at a time, starting from a single machine and adding a component only when a requirement needs it.
1) Clients can put and get values on one machine#
Start with one node and a storage engine. The node must accept 8k or more writes per second of 10 KB values, survive crashes, and answer reads in about a millisecond. We use a log-structured merge tree (LSM tree), the design used by Bigtable, LevelDB, RocksDB and Cassandra. The write path has three steps:
- Append to the write-ahead log (WAL). Every write is first appended to a sequential log file on disk, so it survives a crash. Writes from many clients are grouped and fsynced together ("group commit"), so one fsync of about 0.1-1 ms makes hundreds of writes durable.
- Insert into the memtable. The write then goes into an in-memory sorted structure, usually a skip list, so recent data is readable immediately.
- Flush. When the memtable reaches a threshold, for example 64-256 MB, it is frozen and written to disk as an immutable, sorted file, an SSTable (sorted string table). The file has a block index and a Bloom filter. A new memtable takes over, and that part of the WAL can be discarded.
Reads check the memtable first, then SSTables from newest to oldest. The Bloom filter says "definitely not here" for most files without touching disk, and the block index finds the right 4-64 KB block for files that might contain the key. Compaction runs in the background, merging SSTables to drop overwritten values and expired tombstones, so reads touch only a few files.
Why an LSM tree and not a B-tree? Our workload is write-heavy and values are large. An LSM tree turns random writes into sequential ones, and its write throughput is limited by sequential bandwidth, not random IOPS. A B-tree updates pages in place. It reads better, but needs random writes, and suffers page splits and fragmentation under heavy write load. Deep Dive 1 compares them with numbers.
This is the same structure as the storage engine of a time-series database. There, data goes to a WAL for durability and to an in-memory buffer organised by series, and is flushed to immutable, compressed files with an index at the end, so a lookup is one seek to the index and one to the data. Background compaction merges small files into larger ones. The only real difference is the key: a time-series engine sorts by series and time to make range scans cheap.
2) The data does not fit on one machine#
100 TB and 400k operations per second need about 100 machines, so we partition the key space. Each key needs exactly one set of homes that every node and client can compute independently, and adding a node should move as little data as possible.
hash(key) mod Nmoves almost every key when N changes. It is not acceptable for a database that must rebalance live, because every resize would mean moving 100 TB.- Consistent hashing places every node on a ring of hash values, at several points called virtual nodes, or tokens. A key belongs to the first token clockwise from
hash(key). Adding a node takes only the arcs before its new tokens, about 1/N of the data, and with many virtual nodes it takes them evenly from all the existing nodes.
We hash keys with a fast, well-distributed function such as Murmur3, which Cassandra uses, or MD5, which the Dynamo paper used. Each physical node owns 128-256 virtual nodes. Hash partitioning gives up range scans across keys in exchange for even load. This is acceptable because our API has none. Deep Dive 2 covers token assignment and the alternatives.
Who handles a request? Any node can act as the coordinator for any key, because every node knows the full ring through gossip (section 7). A client can send a request to any node, or use a token-aware client that computes the preference list itself and sends the request straight to a replica. That saves a hop: about 0.5 ms in the same zone and 1-2 ms across zones.
3) Data must survive machine and zone failures#
We store each key on N = 3 nodes, its preference list. These are the first three distinct physical nodes clockwise from the key's hash. We skip virtual nodes that belong to a physical node already chosen, and we also skip nodes in a zone already used. So the three replicas are always on three machines in three zones. Losing any one machine, rack or zone leaves two copies.
The preference list is computed, not stored. Any node can work it out from the ring, so no lookup service is needed. In practice the list is slightly longer than N (for example, the first 5 eligible nodes), so that there are known fallbacks when one of the first three is down (section 5).
4) Clients choose consistency per request#
With three replicas there is a choice about how many must acknowledge a write (W) and how many must answer a read (R).
- The quorum rule. If R + W > N, every read set overlaps every write set in at least one replica. So a read sees the latest acknowledged write, as long as the same set of N nodes is used. With N = 3,
W = 2andR = 2is the classic configuration (the Dynamo paper reports (3, 2, 2) as common). One replica can be slow or down without blocking reads or writes. - Faster, weaker options.
W = 1, R = 1gives the lowest latency and highest availability, but no overlap, so reads can be stale.W = 3makes writes fragile.R = 1, W = 3suits read-heavy data that is rarely written. - Latency. The coordinator sends the request to all N replicas and waits for the fastest W or R answers. Waiting for 2 of 3 means the latency is the second-fastest response, which cuts the tail compared with waiting for all 3.
The coordinator returns UNAVAILABLE if fewer than W replicas are alive before it even tries, and TIMEOUT if they do not answer in time. Deep Dive 4 explains why quorums are not linearizable on their own, and what that means in practice.
5) Writes must succeed even when replicas are down#
If one of a key's three home replicas is down, a strict quorum (W = 2) still works with the other two. But if two are down, or a partition cuts the coordinator off from two of them, a strict quorum fails. Dynamo chose availability:
- Sloppy quorum. The coordinator writes to the first W healthy nodes on the extended preference list, even if they are not the key's home replicas.
- Hinted handoff. A substitute node stores the write with a hint: "this belongs to node C". It keeps checking C. When C is reachable again, the substitute delivers the write and deletes its local copy.
Writes keep succeeding through failures. The price is that a later read using the home replicas may miss a write that is sitting as a hint on a substitute. So a sloppy quorum is a durability guarantee, "W nodes have it", not a consistency guarantee. Deep Dive 6 covers hint limits and storage.
6) Replicas that diverge must converge#
Replicas drift apart for several reasons: a write reached 2 of 3 replicas, a hint expired, a disk was replaced. Three mechanisms repair them, at different speeds:
- Read repair (on the read path). The coordinator compares the versions returned by the replicas it read. If one is stale, it writes the newest version back to that replica. This fixes hot keys quickly.
- Hinted handoff (after short outages). Covered above.
- Anti-entropy (background). Each replica builds a Merkle tree, a hash tree over its data in each token range. Two replicas compare trees from the root down and exchange only the ranges whose hashes differ. This fixes cold keys that are never read and data lost through long outages. Deep Dive 7 does the maths.
Conflicts. Because any replica can accept a write, two clients can write the same key concurrently on different replicas. The store must detect this and resolve it. It can keep both versions as siblings using vector clocks, which can tell "B was written after seeing A" from "A and B were concurrent". Or it can use last-write-wins (LWW) by timestamp, which is simpler but silently drops one of the writes. Deep Dive 5 covers both.
7) Nodes must discover each other and detect failures#
There is no master, so every node needs to learn the ring and the health of other nodes by itself:
- Gossip. Once a second, each node exchanges its membership table (node, tokens, status, heartbeat counter, version) with a random peer. Each side keeps the newer entries. News spreads to all N nodes in O(log N) rounds, a few seconds for 108 nodes.
- Seed nodes. A few well-known addresses that new nodes contact first, so the cluster never splits into islands that do not know about each other.
- Failure detection. Each node decides locally whether a peer is up, using a phi accrual detector. This gives a suspicion level based on how late heartbeats are compared with their usual spacing, not a fixed timeout. A node that a coordinator believes is down is simply not sent requests. Hinted handoff covers its writes.
- Explicit membership changes. Permanently adding or removing a node is an administrator action recorded in the gossip state. A node that is merely unreachable keeps its tokens. That way a network glitch does not trigger a 4 TB data move. Deep Dive 8 explains why.
The full high-level design#
The request path for one key, with N = 3 replicas in three zones:
The cluster plane that every node runs, with no central master:
Each component in one line:
- Client library. It knows the ring (fetched from any node and refreshed periodically), sends each request to a replica of the key so the coordinator is local, applies the consistency level, and retries with idempotent contexts.
- Coordinator. It is any node that receives the request. It computes the preference list, fans out to N replicas, waits for W or R answers, reconciles versions, triggers read repair, and stores hints for replicas that are down.
- Replica storage engine. An LSM tree: group-committed WAL, skip-list memtable, immutable SSTables with Bloom filters and block indexes, and background compaction.
- Hints store. A local, separate log of writes for unreachable peers, replayed when they come back and dropped after a hint window (for example 3 hours).
- Anti-entropy repair. A scheduled job that builds Merkle trees per token range on each replica, compares them, and streams only the differing ranges.
- Gossip and membership. Peer-to-peer spread of the ring and of node state. Seed nodes join new members. Ring changes are explicit, persisted administrator actions.
- Failure detector. Each node runs it locally. It produces a suspicion score per peer so coordinators avoid sending requests to dead or very slow nodes. See Heartbeats, Failure Detection and Gossip.
- Streaming. It copies whole token ranges when nodes join, leave or are replaced, throttled so foreground latency stays within its SLO.
Key Flows#
A quorum write while one replica is down#
- The client sends the request to a node that is itself a replica of
cart:42(A). Its client library computed the preference list, so A coordinates locally and saves a network hop. - The coordinator builds the new version. It merges the clocks in the client's context, then increments its own counter. Because the write descends from everything the client read, it replaces those versions instead of becoming a sibling.
- A writes locally (WAL plus memtable, about 0.1-1 ms with group commit) and sends the write to B in parallel. C is believed down, so the write goes to the next healthy node, D in the same zone as C, tagged with a hint "for C".
- With W = 2, the client gets success after A and B acknowledge. D's acknowledgement can arrive later. Total latency is roughly one cross-zone round trip (1-2 ms) plus a local append, so p50 is about 2 ms.
- When gossip and the failure detector show C is back, D replays the hinted write to C and deletes it. If C stays down past the hint window, the hint is dropped and anti-entropy repair must fix C later.
A quorum read with read repair#
- The coordinator reads its own copy and asks the other replicas in parallel: one for the full value and one for just a digest (hash plus clock). Asking only one replica for the full 10 KB value saves bandwidth.
- If the digests match, the coordinator answers as soon as R = 2 responses are in. Here C's version is older. Its clock is dominated by A3 B1: every counter is less than or equal, and at least one is smaller.
- A dominated version is simply out of date, so the coordinator returns the newer one and asynchronously writes it back to C. That is read repair. Frequently read keys stay converged without waiting for background repair.
- If neither version dominated the other, they would be concurrent. The coordinator would return both values with a merged context, and the client would merge them and write back (Deep Dive 5).
- Latency is the second-fastest replica response, about 1-2 ms. This is why quorum reads tolerate one slow replica without hurting p99.
Data Model#
We are building the database, so the "data model" has three layers: the logical model the client sees, the on-disk record format, and the cluster metadata that every node gossips. The erDiagram shows the metadata and how it relates to stored data.
Logical model. A table is a map from key to value. Each stored value carries a version: a vector clock or a write timestamp, a tombstone flag, and an optional expiry time.
On-disk record (one entry in an SSTable or WAL):
| Field | Size | Purpose |
|---|---|---|
| key length and key | 2 B + up to 1 KB | Lookup and ordering inside the SSTable |
| version | vector clock about 10-50 B, or 8 B timestamp | Detect stale vs concurrent versions |
| flags | 1 B | Tombstone, TTL present, compression |
| expiry time | 4-8 B, optional | TTL. Expired records act as tombstones. |
| value length and value | 4 B + up to 1 MB | The payload, or a pointer to a blob in object storage |
| checksum | 4 B | Detect disk corruption on read and during compaction |
Where metadata lives. Membership and tokens live in each node's local system tables and are spread by gossip. There is no external database, which keeps the store free of single points of failure. Some systems keep the ring in a consensus store instead, such as ZooKeeper or etcd, accepting a dependency in exchange for simpler, strongly consistent topology changes (Deep Dive 8). Table schemas follow the same path. For the general trade-offs see Choosing a Database: A Decision Guide.
Keys and indexes.
- Partition key. The whole key, hashed with Murmur3 into a 64-bit token.
- Per-SSTable structures. Within each SSTable, records are sorted by key, with a sparse index (one entry per block) and a Bloom filter over all keys.
- No global secondary indexes. Applications that need lookup by another attribute maintain a second table as a manual index, accepting that the two tables can briefly disagree.
Retention.
- Overwritten versions are removed by compaction.
- Tombstones are kept for a grace period, for example 10 days, longer than the maximum time a replica can be out of repair. Then compaction purges them.
- Expired TTL values become tombstones and follow the same path.
Deep Dives#
1) What storage engine does each node run, and how is it tuned?#
Basic: a hash index over an append-only log (Bitcask-style). Writes are appended to a log file, and an in-memory hash table maps each key to the file offset of its latest value. Riak's Bitcask engine, described by Justin Sheehy and David Smith in 2010, works this way. A read is one hash lookup plus one disk seek. A write is one sequential append. Old values are reclaimed by "merging" log files in the background. It is simple and very fast, but every key must fit in RAM. Our 2.8 × 10^8 keys per node at about 100 bytes each would need around 28 GB of index just for keys, plus per-entry overhead. That is possible, but it caps how many small keys a node can hold, and it gives no ordered iteration, which Merkle tree building and range streaming want.
Better: a B-tree. It is ordered, reads take a predictable 3-4 page lookups (mostly cached), and it is used by most relational databases and by key-value engines such as LMDB and BoltDB. The weakness is writes. Each update rewrites a whole page, typically 4-16 KB, in place, and the update is also logged in the WAL, so a 100-byte change can cause 10 KB or more of random writes. Under 8k writes per second per node of 10 KB values, a B-tree spends its time on random I/O, page splits and fragmentation. Pages also end up partly empty, about 30-50% on average after random inserts.
Best: an LSM tree with leveled compaction, Bloom filters and tuned caching, plus key-value separation for large values. This is the design from the high-level section. Its tuning knobs are the real design work. "The Log-Structured Merge-Tree (LSM-Tree)" by Patrick O'Neil, Edward Cheng, Dieter Gawlick and Elizabeth O'Neil (Acta Informatica, 1996) introduced the idea. Bigtable (Chang and colleagues, OSDI 2006) made it famous. LevelDB and RocksDB are the common modern engines, and Cassandra and ScyllaDB have their own.
Compaction strategy sets three amplifications against each other:
| Strategy | How it works | Write amp | Read amp | Space amp | Best for |
|---|---|---|---|---|---|
| Size-tiered (STCS) | Merge SSTables of similar size into one bigger file | Low, about 3-5 | High: a key can be in many files | High: up to 2x during big merges | Write-heavy, rarely read |
| Leveled (LCS) | Levels L1..Ln, each 10x bigger. Files in a level do not overlap | High, about 10-30 | Low: at most one file per level | Low, about 1.1x | Read-heavy or overwrite-heavy |
| Time-window (TWCS) | Compact within time buckets, drop whole buckets on TTL expiry | Low | Low for recent-time reads | Low with TTLs | Time-series and TTL data |
For our mix, with 25% writes, many overwrites of the same keys (carts and sessions) and tight p99 reads, leveled compaction is the default. A write-heavy table, such as an event log with TTLs, gets time-window compaction. The compaction rate is throttled, for example to 200-400 MB/s per node, so it never starves foreground I/O. Compaction backlog (pending bytes) is a top-five alert, because a backlog means read amplification is climbing.
Why reads stay fast. With leveled compaction there are about 5-6 levels at a 10x fan-out for 4 TB per node. A read for a key that exists checks the memtable, then at most one candidate file per level. The Bloom filter rejects files that do not have the key without touching disk. At 10 bits per key with 7 hash functions, the false-positive rate is about 1%. So a lookup across 6 levels does about 0.06 wasted disk reads on average, plus one real read for the block that contains the key. That block is usually in the block cache when the key is hot. The worked number: a cold read is about 1.1 SSD reads × about 100 µs ≈ 0.1 ms on the node. Almost all of the 1-2 ms the client sees is network and queueing time.
Memtable, caches and compression. The memtable is usually a skip list: it is sorted, supports lock-free concurrent inserts, and can be flushed in key order without sorting. Its size trades memory for fewer, larger flushes. Larger memtables also absorb overwrites of hot keys before they ever reach disk. Two caches sit on the read path. The block cache holds recently read, decompressed SSTable blocks. The OS page cache holds compressed file pages. Index and Bloom filter blocks are pinned in memory, so a lookup never needs a disk read just to find out where to look. Blocks are compressed individually, with LZ4 for hot levels and Zstandard for the bottom level, where most data lives. Typical ratios of 2-4 times on text-like values cut disk usage, compaction I/O and streaming time by the same factor.
Durability settings. The WAL is fsynced on group-commit boundaries, for example every 1-10 ms or every batch. "Acknowledged" therefore means "on the WAL of W replicas". Cassandra's default of periodic sync every 10 seconds acknowledges writes before fsync and relies on replication across machines for durability. That is a legitimate choice, as long as you are clear that a simultaneous power loss across zones could lose up to 10 seconds of writes. We choose batched sync with a window of about 2 ms. On NVMe it costs little.
Large values: key-value separation. Compaction rewrites values on every level, so 1 MB values multiply write amplification. "WiscKey: Separating Keys from Values in SSD-Conscious Storage" (Lu, Pillai, Arpaci-Dusseau and Arpaci-Dusseau, FAST 2016) stores values in a separate value log and keeps only key → value pointer in the LSM tree. Compaction then moves small records, and write amplification drops sharply for large values. The cost is an extra read per lookup and a separate garbage collector for the value log. RocksDB offers this as "BlobDB". We enable it for tables whose average value is over about 4 KB.
See Storage Engines: B-Trees vs LSM Trees for the general theory.
2) How are keys partitioned and how are tokens assigned?#
Basic: one random token per node on a consistent hash ring. A key goes to the first node clockwise. This works, but with one point per node the arc sizes vary enormously. Arcs follow a roughly exponential distribution, so some nodes own two or three times their fair share, and a new node takes load from only one neighbour. When a node fails, all of its load lands on a single successor.
Better: many random virtual nodes per physical node. With 256 tokens per node, each node owns 256 small arcs scattered around the ring. Its total share has a relative standard deviation of about 1/√256 ≈ 6%. A joining node takes a slice from almost every other node, and a failed node's load spreads across many. Heterogeneous hardware is easy: give a bigger machine more tokens. This is what Dynamo and older Cassandra versions did. The cost is in operations. With 256 random tokens per node, every node shares replicas with almost every other node, so two simultaneous failures anywhere in a large cluster are likely to hit some key's 2 out of 3 replicas. Repair and streaming also touch many small ranges.
Best: fixed, equal-sized partitions assigned to nodes, with fewer, chosen tokens. The Dynamo paper describes this path. It compares three strategies:
- T random tokens per node, with partitions defined by token values.
- T random tokens per node, with the ring cut into Q equal-sized partitions.
- Q/S tokens per node with Q equal-sized partitions, where S is the number of nodes.
It reports that strategy 3 gave the best load balance and the most efficient handling of membership changes. The reason is that a partition becomes a unit that can be moved, backed up and summarised by its own Merkle tree. A node joining "steals" whole partitions instead of new random arcs. This is the same reasoning behind Riak's fixed ring of partitions and Redis Cluster's 16,384 slots.
For us: Q = 4,096 partitions, assigned by an algorithm that balances per node and per zone, giving about 38 partitions per node as first replica, or about 114 counting all three replicas, across 108 nodes. Cassandra's newer token allocation similarly chooses a small number of tokens per node (for example 8-16) with an allocator, rather than 256 random ones. Fewer tokens per node also reduce the number of distinct replica sets, which lowers the chance that two random node failures share a range.
Placement across zones. The preference list for each partition takes the next distinct node in each zone, so N = 3 means one replica per zone. Cassandra calls this NetworkTopologyStrategy with racks mapped to zones. A whole-zone failure then removes exactly one replica of every key. A quorum of 2 keeps working everywhere, and no key loses two copies.
Why not range partitioning? Ordering keys on the ring by their value rather than their hash, as Bigtable and HBase do with tablets, enables range scans like "all keys from user:42: to user:43:". But sequential or popular key ranges create hot spots, such as a new timestamp key always landing in the last range, and ranges must be split and merged dynamically. Our API has no cross-key scans, so hashing wins. A common compromise, used by Cassandra and DynamoDB, is a compound key: hash the partition key to place data, and sort clustering keys within a partition, so scans work within one partition, such as one user's items.
Hot partitions. Even placement of keys does not give even load if one key is hot. The mitigations are the same as in a cache:
- Detect hot keys by sampling.
- Spread writes for a hot logical key across sub-keys, for example
counter:42:shard7, and sum them on read. - Serve hot reads from replicas with
ONE, or from a cache in front. - Apply per-table and per-partition throttling, so one hot key cannot overload its three replicas.
DynamoDB's published design (Elhemali and colleagues, USENIX ATC 2022) describes adaptive capacity, which moves throughput to hot partitions and splits them. This is the managed-service version of the same idea.
3) What do quorums really guarantee, and how should N, R and W be chosen?#
Basic: "R + W > N means strongly consistent." This is the textbook statement, and it is a good first answer. If a write reached W replicas and a read asks R replicas with R + W > N, at least one replica in the read set has the write. The coordinator picks the newest version, so the read sees it.
Better: know exactly where the overlap argument breaks. The argument assumes a fixed set of N replicas and completed writes. Real systems violate both:
- Sloppy quorums. With hinted handoff, a write may have gone to D instead of C. A later read from A and C can miss it, even though R + W > N. Overlap holds only among home replicas.
- Partial writes. A write that reached 1 replica and then timed out is neither committed nor rolled back. A reader that hits that replica sees the new value. The next reader, hitting two others, sees the old value. The value appears and then disappears. That violates linearizability, even though each read was a quorum.
- Concurrent reads during a write. While a write is in flight, one quorum read can return the new value and a later one the old value, unless reads wait for read repair to complete before answering. Cassandra's blocking read repair at
QUORUMdoes this. It is what makes "monotonic quorum reads" work, at the cost of extra latency when replicas disagree. - Last-write-wins with clock skew. If versions are ordered by wall-clock timestamps, a write with an earlier timestamp from a node whose clock is behind loses to an older write, and the new value never becomes visible.
- Membership changes. While a node is joining or leaving, the "N replicas" of a range are changing. If reads and writes do not agree on which set they are using, the overlap can be lost.
So the honest statement is: R + W > N gives read-your-writes and usually-fresh reads in the normal case, not linearizability. For true linearizable single-key operations, use a consensus round (Deep Dive 10).
Best: choose N, R and W from failure tolerance and latency, and measure staleness.
| Setting (N = 3) | Write survives | Reads fresh? | Tolerates down replicas | Typical use |
|---|---|---|---|---|
| W = 2, R = 2 | Loss of 1 node | Yes, usually (quorum overlap) | 1 for reads and writes | Default for most data |
| W = 1, R = 1 | Possibly lost if that node dies before replicating | Often stale | 2 | Metrics, logs, best-effort caches |
| W = 3, R = 1 | Loss of 2 nodes | Yes, usually | 0 for writes, 2 for reads | Read-heavy, rarely updated config |
| W = 1, R = 3 | Weak | Yes, usually | 2 for writes, 0 for reads | Rare: write-heavy with careful reads |
LOCAL_QUORUM, N = 3 per region | Loss of 1 node per region | Fresh within the region | 1 per region | Multi-region default |
Latency maths. The coordinator waits for the k-th fastest of N responses. If each replica's latency is independent, with a 1% chance of exceeding 20 ms, then:
- W = 1: the write is slow only if all three replicas are slow: 10^-6.
- W = 2: it is slow if at least 2 of 3 are slow: about 3 × 10^-4.
- W = 3: it is slow if any is slow: about 3%.
So quorums are not just about consistency. Waiting for a majority hides one slow replica, which is how a Dynamo-style store hits a p99.9 SLA on imperfect machines. The Dynamo paper describes its SLAs at the 99.9th percentile, for example a 300 ms bound, for this reason.
How stale is "eventually"? "Probabilistically Bounded Staleness for Practical Partial Quorums" (Bailis, Venkataraman, Franklin, Hellerstein and Stoica, VLDB 2012) models how often a read sees the latest value, as a function of N, R, W and the measured latency distributions. Its striking finding is that with partial quorums such as R = W = 1, reads are usually consistent within tens to hundreds of milliseconds after a write, because replication normally completes quickly. That justifies ONE for many workloads. It is the quantitative answer to "how eventual is eventual consistency?", and you can instrument your own cluster the same way by tracking replication delay distributions.
Speculative retry: hiding the slow replica on reads too. When a read uses digests, the coordinator needs answers from specific replicas. If one of them is in a GC pause, waiting for it costs the whole pause. Speculative retry sends the same request to an additional replica once the first one has taken longer than, say, its own p99 latency. With 3 replicas, that extra request goes out on only about 1% of reads, so it adds about 1% load and cuts p99.9 sharply. It is the same idea as hedged requests in "The Tail at Scale" (Dean and Barroso, 2013). Pair it with latency-aware replica selection: the coordinator tracks a moving average of each replica's response time and sends full-data requests to the fastest one, so a degraded node naturally receives less traffic before the failure detector ever convicts it.
Practical rule. Use QUORUM or LOCAL_QUORUM for both reads and writes by default. Use ONE for data where a briefly stale read is harmless. Never mix ONE writes with ONE reads for data a user expects to see immediately after writing it. Measure the read-repair rate: a high rate means replicas often disagree, which hints at dropped writes, overloaded nodes or clock problems. See Quorums and Leaderless Replication.
4) How are concurrent writes detected and resolved?#
Basic: last-write-wins by timestamp. Every write carries a timestamp, from the client or the coordinator. Replicas keep the value with the highest timestamp, and ties are broken by node id. This is simple, needs no client cooperation, and keeps one value per key. Cassandra does this per column (cell). The problem: concurrent writes are silently discarded. Two people adding different items to the same shared cart at the same moment produce two writes, and one simply vanishes. Clock skew makes it worse. If node X's clock runs 50 ms fast, X's writes win against "later" writes from other nodes for 50 ms, and a client whose write was accepted may never see it take effect. Jepsen analyses by Kyle Kingsbury (2013) demonstrated exactly this kind of lost update under partitions in LWW-based stores. LWW is right when writes to one key are naturally serialised or idempotent, for example a single writer per key, immutable inserts, or "set the latest location". It is wrong for read-modify-write data with multiple writers.
Better: vector clocks with siblings, merged by the client (Dynamo's approach). Each version carries a vector clock, a map of node → counter. Vector clocks were introduced independently by Colin Fidge and Friedemann Mattern in 1988, and extend Leslie Lamport's 1978 logical clocks. The rules:
- When a coordinator node X handles a
putwith a context, the new clock is the context's clock with X's counter incremented. - Version V1 descends from V2 if every counter in V1 is at least the corresponding counter in V2. A descendant replaces its ancestor.
- If neither descends from the other, they are concurrent. Both are kept as siblings and returned together on the next
get.
A worked example on one cart key:
- Ann writes
[book]through node A. The clock is{A:1}. - Ann reads
{A:1}, adds a pen, and writes through A. The result is{A:2}, which descends from{A:1}and replaces it. - Ann's phone and laptop both read
{A:2}. During a partition, the phone adds a lamp through node B, giving{A:2, B:1}. The laptop adds a cup through node C, giving{A:2, C:1}. - Neither clock dominates: B:1 is not in the second, and C:1 is not in the first. They are siblings.
- The next
getreturns both values with the merged context{A:2, B:1, C:1}. The client's merge function (here a set union) produces[book, pen, lamp, cup]and writes it with that context. The new version,{A:3, B:1, C:1}, descends from both siblings and replaces them.
Two practical problems remain:
- Clock size. A clock gains an entry per coordinating node. Dynamo coordinates writes on preference-list nodes, so clocks stay small. It also truncates the oldest entry when the clock exceeds a threshold (the paper suggests about 10 entries), accepting a small chance of false conflicts.
- Deletes in merges. If Ann deletes the pen on one side while the other side keeps it, a simple union brings the pen back. The Dynamo paper notes that deleted cart items could reappear. The fix is to store removals explicitly, for example as tombstoned elements.
Best: version vectors with dots, or CRDTs where the data type allows it. Per-client vector clocks grow without bound. Per-server clocks can produce false siblings when one coordinator handles concurrent writes from two clients. Dotted version vectors (Preguiça, Baquero and colleagues) fix this by tagging each value with the exact event, its "dot", that created it. That gives precise concurrency detection with clocks sized by replicas, not by clients. Riak adopted them.
Better still, for data types with a natural merge, use CRDTs (conflict-free replicated data types; Shapiro, Preguiça, Baquero and Zawirski, 2011). For example, an observed-remove set for carts, a PN-counter for likes, or a last-writer-wins register only where LWW is truly acceptable. The store merges siblings automatically and deterministically, so clients never see conflicts and deletes behave correctly. The rule we adopt is per table:
- LWW for single-writer or immutable data. It is simplest and smallest.
- CRDT types for counters, sets and maps.
- Vector clocks with an application merge only when a custom merge is needed.
- Conditional writes (Paxos) when a conflict must be prevented rather than merged, for example usernames.
See Conflict Resolution, OT and CRDTs and Time, Clocks and Ordering.
5) How do sloppy quorums and hinted handoff work in detail?#
Basic: strict quorums only. If fewer than W home replicas are reachable, reject the write with UNAVAILABLE. This is simple and keeps quorum overlap honest. But in a partition that isolates a client's region from two replicas, every write fails, which is exactly what an "always writable" cart cannot accept.
Better: sloppy quorum plus hinted handoff. The coordinator walks the extended preference list and writes to the first W healthy nodes, preferring nodes in the same zone as the missing replica so the placement rules still hold. Each substitute stores the write in a separate hints log, keyed by the intended target, not in its own data files, because it does not own that range. When the failure detector shows the target is back, the substitute streams its hints to it, throttled, and deletes them once acknowledged.
The details that matter:
- Hint window. Hints are kept only for outages shorter than a configured window. Cassandra's default
max_hint_windowis 3 hours. After that, the target is considered too far behind, the substitute stops storing hints for it, and a full anti-entropy repair is required when it returns. Without a window, a dead node would make every other node accumulate its writes without limit. - Hints are not replicas. A write acknowledged as W = 2, with one home replica plus one hint, is durable on two machines. But it is readable from only one home replica until the hint is delivered. So
QUORUMreads may miss it. Cassandra makes this explicit: hints do not count toward any consistency level except a specialANYlevel, meaning "stored somewhere, even only as a hint". Dynamo counted sloppy writes toward W. That is a deliberate availability choice to state clearly in an interview. - Hint storms. When a node returns after a 2-hour outage, every other node may try to replay hints at once. At 8k writes per second, 2 hours of missed writes is about 58 million records, around 580 GB at 10 KB each. Replaying this unthrottled would overwhelm the node that just came back. Throttle replay per target, for example to 50-100 MB/s in total.
- Hints and deletes. Tombstones are hinted like any other write. This matters for the tombstone grace period (Deep Dive 9).
- Hint loss. If the substitute itself dies before delivering, those hints are gone. Anti-entropy is the safety net. This is why hinted handoff is an optimisation for short outages, never the only repair mechanism.
Best: hinted handoff tuned as one layer of a three-layer convergence strategy, with explicit consistency semantics. In order of speed:
- Hints for outages of minutes to hours.
- Read repair for hot keys on every read that sees a disagreement.
- Scheduled Merkle repair for everything else, completed within the tombstone grace period.
The client API keeps strict and sloppy modes separate:
QUORUMcounts only home replicas.- An explicit
ANYorSLOPPY_QUORUMaccepts substitutes, for workloads such as carts and event ingestion where never refusing a write matters more than an immediate fresh read.
We also expose the hints-pending gauge per target node. Rising hints for a node that gossip says is up usually means it is too overloaded to accept writes, which is an early warning of trouble.
6) How does anti-entropy repair find and fix differences efficiently?#
Basic: compare every key. Two replicas stream all their keys and versions to each other and compare them. With 4 TB per node and 2.8 × 10^8 keys, that is hours of disk and network traffic to find maybe a few thousand differences, and it must happen for every pair of replicas of every range. It does not scale.
Better: Merkle trees per token range. A Merkle tree, after Ralph Merkle's 1987 hash-tree construction, summarises data hierarchically:
- Split the token range into 2^d sub-ranges, the leaves.
- Hash all key-version pairs in each leaf.
- Each parent node is the hash of its children. The root is a hash of the whole range.
Two replicas exchange roots. If the roots are equal, the range is identical, so one hash comparison covers 4 TB. If they differ, the replicas compare children and descend only into subtrees whose hashes differ. Finally they stream only the leaves that differ.
The maths: with Q = 4,096 partitions, one partition holds 10^10 ÷ 4,096 ≈ 2.4 × 10^6 keys. A tree with d = 15 has about 32,000 leaves, so roughly 75 keys per leaf. If 100 keys differ, scattered across about 100 leaves, the replicas exchange about 100 × 15 hashes on the way down and stream about 100 leaves × 75 keys. That is 7,500 keys instead of 2.4 million, a saving of about 320 times. Deeper trees mean less over-streaming but more memory and hashing.
Best: incremental, scheduled, range-by-range repair with bounded impact. Building a Merkle tree requires reading the data, which is a full scan of the range on each replica. On a 4 TB node that is hours of disk bandwidth. Production systems therefore:
- Repair one range at a time, on a rolling schedule, so the whole cluster completes a cycle within the tombstone grace period, for example every 5-7 days with a 10-day grace.
- Use incremental repair. Mark SSTables as "repaired" after a successful repair, and on later runs build trees only over unrepaired data. This shrinks the work to recent writes.
- Throttle validation and streaming, so repair uses at most, say, 10-20% of disk and network.
- Keep trees per partition when fixed partitions are used (Deep Dive 2). A partition move then does not invalidate the trees for other ranges, which was one of the Dynamo paper's arguments for strategy 3.
- Prefer repairing from more replicas. With three replicas, a range is repaired by comparing all three pairs, or by building trees on all three and reconciling to the newest versions.
Repair status is a first-class metric: time since the last successful repair for each range. If a range goes longer than the grace period without repair, deleted data can come back (Deep Dive 9). That is one of the most common real production bugs in Dynamo-style stores.
7) How do nodes agree on membership and detect failures without a master?#
Basic: every node heartbeats every other node. It is simple and fast to detect failures, but costs O(N²) messages: 108 × 107 ≈ 11,600 heartbeats a second at one per second per pair. That is tolerable at 100 nodes and breaks at 1,000. More importantly, a fixed timeout ("down after 5 seconds without a heartbeat") is either too twitchy during GC pauses and network blips or too slow for real crashes.
Better: gossip for dissemination, phi accrual for detection.
- Gossip. Each node keeps a table with one row per node: address, tokens, status, plus a heartbeat generation (incremented on restart) and a heartbeat version (incremented every second while alive). Once a second it picks a random live peer, and occasionally a seed or an unreachable node, and they exchange digests: "I have node X at generation 7, version 1,234". Each side sends the rows where it has newer information. This is the anti-entropy style of epidemic protocol analysed by Alan Demers and colleagues in "Epidemic Algorithms for Replicated Database Maintenance" (PODC 1987). News reaches all N nodes in O(log N) rounds, roughly 7-12 seconds for 108 nodes (the maths deep dive below gives the constants). The load is constant per node, no matter how big the cluster is.
- Phi accrual failure detection. "The φ Accrual Failure Detector" (Hayashibara, Défago, Yared and Katayama, SRDS 2004) replaces the yes-or-no timeout with a suspicion level φ. Each node records the intervals between heartbeat updates it sees for a peer and fits a distribution to them. Given the time since the last update, φ = −log₁₀ P(a heartbeat would be this late). φ = 1 means about a 10% chance the peer is actually fine. φ = 8, Cassandra's default conviction threshold, means about a 10^-8 chance of a heartbeat being that late by normal variation. The detector adapts: a peer whose heartbeats are naturally jittery needs a longer silence before it is convicted.
Best: separate "unreachable" from "removed", and keep failure detection local. The Dynamo paper's key insight is that most failures are temporary: a reboot, a network blip, a long GC pause. So:
- Local, transient failure. When a coordinator believes a node is down, it simply routes around it. Hinted handoff covers writes, and reads go to other replicas. No data moves and no cluster-wide decision is needed. Different nodes may disagree for a few seconds about whether X is up, and that is fine.
- Permanent membership change. Adding, removing or replacing a node is an explicit administrator command. It is persisted and gossiped with a version, and it is what triggers token reassignment and data streaming. A node that is unreachable for an hour keeps its tokens. Without this rule, a 30-second partition could start terabytes of rebalancing, and that streaming load would cause more failures.
- Seeds prevent logical partitions. If two new nodes joined through different contact points at the same time, each might believe it was in a separate cluster. Every node gossips with seeds periodically, so all views merge.
- Bounded flapping. A recovering node is marked up only after several fresh heartbeats, and coordinators add it back gradually. Requests are routed by measured latency ("dynamic snitch" in Cassandra terms), so a node that is up but slow gets less traffic.
SWIM (Das, Gupta and Motivala, 2002) is an alternative membership protocol. It uses random probes plus indirect probes through other members before suspecting a node, and spreads membership updates piggybacked on those probes. It is used in HashiCorp's memberlist library. Either approach works. What matters is constant per-node overhead, adaptive or indirect detection, and the transient-versus-permanent distinction. See Heartbeats, Failure Detection and Gossip.
Where Dynamo-style gossip is weakest: topology changes. Two administrators adding nodes at once, or a token change gossiped while some nodes are down, can leave nodes with briefly different rings, and so briefly different replica sets. Cassandra historically suffered from races of this kind. Newer designs move the ring into a strongly consistent log while keeping data replication leaderless. Cassandra's transactional cluster metadata work and ScyllaDB's Raft-based topology are examples. We do the same: membership liveness by gossip, but token assignments committed through a small Raft group, with each ring change getting an epoch number that requests carry.
8) How are nodes added, removed and replaced without downtime?#
Basic: stop the cluster, recompute placement, copy data. It needs downtime, so it is unacceptable.
Better: bootstrap by streaming token ranges.
- Adding a node. It joins with its assigned tokens, or partitions. It computes which ranges it will own and streams them from the current replicas while in the
Joiningstate. During streaming, writes for those ranges go to both the old replicas and the joining node ("pending ranges"), so nothing is missed. Reads still go to the old replicas. When streaming finishes, the node announcesNormaland the old owners clean up the ranges they no longer own. - Removing (decommissioning) a node. The reverse: stream its ranges to their new owners, then leave.
- Replacing a dead node. Start a new node with the dead node's tokens. It streams the data for those ranges from the surviving replicas, then takes over. No other ranges move.
Best: plan moves at partition granularity, throttle them, and size for the time they take. The numbers are what make this an engineering problem. A node holds about 4 TB. Streaming at a throttled 200 MB/s takes 4 × 10^12 ÷ 2 × 10^8 = 20,000 s, about 5.5 hours, to bootstrap one node. During that window:
- The cluster runs with reduced redundancy for those ranges if the node is a replacement, since only 2 of 3 replicas are healthy. So a second failure in the same ranges would leave only one copy. Replacements are therefore the highest-priority operation, and the mean time to replace is a key input to durability estimates (see the maths deep dive).
- Streaming from many sources is faster. With fixed partitions spread across many nodes, a replacement can pull each partition from a different source in parallel, bounded by its own disk and NIC rather than by one peer. Twenty sources at 50 MB/s each fill a 1 GB/s ingest limit, so a node is rebuilt in about 1.1 hours.
- Add capacity before you need it. Disks above about 70-80% full make compaction risky, and adding nodes takes hours. Capacity planning triggers expansion at about 60% utilisation (see Capacity Planning and Load Testing).
- Add nodes one zone-triple at a time. Add one per zone, so the replica placement stays balanced across zones, and wait for each move to finish before starting the next. Concurrent topology changes are where gossip-based rings go wrong (Deep Dive 7).
- Clean up after. Old owners must delete ranges they no longer own. If a later topology change gives a range back to them, stale leftover data could resurface.
9) How do deletes and TTLs work when replicas can be offline?#
Basic: delete the key from each replica. Suppose replica C is down when key K is deleted from A and B. When C returns, anti-entropy compares A (no K) with C (K present) and cannot tell "K was deleted" from "K was written and A missed it". The newest-version rule copies K back. The deleted key resurrects. Removing data in a replicated, leaderless store therefore needs a record of the removal.
Better: tombstones. A delete is a write of a special marker, a tombstone, with its own version (clock or timestamp). It replicates, is hinted and is repaired exactly like a value, and wins over older versions during reads and repair. A TTL is the same idea: an expiry time stored with the value, after which the value behaves like a tombstone.
The cost is that tombstones take space and slow reads, so they must eventually be purged. Two problems follow:
- When is it safe to purge? Only after every replica has received the tombstone. Otherwise the purge reopens the resurrection bug. Systems use a grace period, such as Cassandra's
gc_grace_seconds, which defaults to 10 days. Compaction may drop a tombstone only once it is older than the grace period. That gives the rule every operator must know: every replica must be repaired at least once per grace period. A node that was down for longer than the grace period must be wiped and rebuilt, not brought back with its old data. - Tombstone-heavy reads. A queue-like pattern writes and then deletes many keys in one partition, or sets short TTLs on many entries. A read or scan of that partition must then step over thousands of tombstones to find live data, making reads slow and memory-hungry. Cassandra warns and eventually fails queries that scan too many tombstones. The design fix is to avoid modelling queues in a key-value store (use a log or a queue) and to use time-bucketed keys so whole buckets expire together.
Best: make deletion policy explicit per table and use the compaction strategy that matches it.
- Short-TTL, append-only data such as sessions, events and metrics uses time-window compaction. Data with the same expiry lands in the same SSTables, and a whole SSTable is dropped when everything in it has expired. No tombstone has to be merged.
- Range tombstones. "Delete everything in partition P with clustering key < X" is one tombstone, not millions.
- Repair before purge. Track the last full repair time per range. Only purge tombstones in ranges that have been repaired since the tombstone's creation. Some systems, for example ScyllaDB's repair-based tombstone garbage collection, tie purge eligibility to repair history instead of a fixed timer.
- The hint window must be shorter than the grace period, so that hinted deletes are delivered or dropped long before purge.
The general lesson: in a system without a leader, absence is not information. Every fact, including "this was deleted", must be stored, versioned and replicated like any other.
10) What if some operations need strong consistency?#
Some operations cannot be merged after the fact. "Claim the username ann" or "decrement stock only if it is above zero" must be prevented from happening twice, not reconciled later.
Basic: read, check, then write at QUORUM. Two clients both read "available", both write "taken by me", and LWW picks one. Both clients were told they succeeded. Quorums do not provide atomic read-modify-write.
Better: compare-and-set via a consensus round per key (lightweight transactions). Cassandra's lightweight transactions run Paxos among the key's replicas:
- Prepare and promise. The coordinator obtains a ballot number accepted by a majority.
- Read. It reads the current value from a majority.
- Propose and accept. If the condition holds, it proposes the new value, and a majority accepts it.
- Commit. It makes the accepted value visible.
That is about four round trips instead of one, so a 2 ms write becomes about 8-10 ms within a region. Throughput on a single hot key also drops sharply under contention, because competing ballots force retries. It is the right tool for rare operations that must not race, such as uniqueness checks, lock acquisition or idempotency records. It is the wrong tool for every write. Mixing LWT and non-LWT writes on the same key breaks the guarantees, so a table should choose one.
Best: decide whether the whole system should be leader-based instead. If most operations need linearizability, a leaderless store is the wrong foundation. The alternative design is a consensus group per partition:
- Each partition (range or hash slot) has a Raft or Multi-Paxos group of 3 replicas with a leader that orders all writes.
- Reads go to the leader, which holds a lease, for linearizable reads without an extra round trip.
- Writes are a single round trip from the leader to a majority.
- Leaders move on failure through elections, in a few seconds.
This is how DynamoDB works internally, per its 2022 paper (Multi-Paxos per partition, with a leader handling writes and strongly consistent reads). It is also how Google's Spanner, CockroachDB, TiKV and etcd work, despite DynamoDB's naming link to the original Dynamo. Trade-offs compared with leaderless:
| Aspect | Leaderless (Dynamo, Cassandra, Riak) | Leader per partition (DynamoDB, TiKV, CockroachDB) |
|---|---|---|
| Write availability in a partition | Any replica, or a substitute | Only the majority side, and only after a leader exists |
| Consistency | Tunable, eventual by default. Conflicts are possible | Linearizable per key or range. No siblings |
| Write latency | Fastest W of N, hides one slow replica | Leader to majority. A slow leader hurts until it is moved |
| Failover | None needed: requests route around a failed node | Leader election, about 1-10 s of unavailability for that partition |
| Complexity placed on | Applications (merges) and operations (repair, tombstones) | The consensus implementation and leader balancing |
A strong answer in an interview names this fork explicitly: "If the requirement is 'never refuse a write', I build Dynamo-style. If it is 'never show a stale or conflicting value', I build Raft per partition. Many real systems now pick the latter and buy availability back with fast elections." See Consensus: Raft and Paxos and CAP Theorem and PACELC.
11) How do applications handle multi-key updates and large values on a key-value store?#
Two requirements keep coming up: changes that span more than one key or store, and values too large for the store. Both have a known set of answers.
Multi-key and multi-store updates.
Basic: two stores, glued together with a distributed lock. Take a grocery delivery service in the style of Gopuff. It keeps inventory counts in a key-value store, because they are high-volume single-key reads and writes, and orders in a relational database. To place an order it would:
- Lock the inventory keys for the items.
- Create the order row.
- Decrement each item's inventory.
- Release the locks.
This lets each kind of data live in the store that suits it, but it has nasty failure modes:
- Crash between steps. If the service crashes after creating the order but before decrementing inventory, the stock looks available, and the next customer may be sold the same item. A sweeper must find half-finished orders and reverse them.
- Deadlock. If User 1 holds the lock on item A and wants B, while User 2 holds B and wants A, neither can proceed. The fixes are to acquire locks in a global order (sorted by item key), so the cycle cannot form, and to use lock leases with timeouts so a crashed holder does not block forever.
- Lock validity. A lock held in a store that can fail over or partition can be held by two clients at once. A process pausing past its lease is the classic case. The write must therefore carry a fencing token that the store checks. See Distributed Locks.
Better: make the critical invariant single-key, or use one transactional store. Often the cleanest fix is to put both pieces of state that must change together in one database with transactions. For example, keep inventory and orders in the same Postgres and decrement in the same transaction as the insert, which removes the crash window and the lock entirely. Alternatively, redesign so that the invariant lives in one key. For example, store per-warehouse stock as one key and decrement it with a conditional write (Deep Dive 10): cas(stock:sku42:wh7, 5 → 4). Then use an outbox, a record of pending side effects written with the main change, to create the order asynchronously.
Best: sagas with idempotent, compensating steps, when the stores really must be separate. Each step is a local atomic operation with an idempotency key, and each has a compensating action: "release reserved stock", "cancel order". A coordinator or event log drives the steps, retries until they succeed, and runs compensations on failure. You get no global lock and no deadlock, and every failure has a defined recovery path. The cost is that intermediate states are visible (for example "reserved"), so the product must tolerate them. See Distributed Transactions: 2PC, Sagas and Outbox and Idempotency and Safe Retries.
Manual secondary indexes. The same problem appears inside one key-value store when an application keeps a second table as an index, such as email → user_id next to user_id → profile. Changing an email touches two keys on different replica sets, with no transaction. The robust order is:
- Write the new index entry first. A conditional write rejects duplicates.
- Update the main record.
- Delete the old index entry last.
A crash part-way through then leaves an extra index entry pointing at a record that no longer matches. Readers detect this by checking that the record they fetch still carries the email they looked up, and they ignore entries that fail the check. A background job removes those dangling entries. The rule: the main record is the source of truth, and the index is a hint that readers verify.
Large values.
Basic: store the file in the key-value store. Values of many megabytes inflate compaction write amplification, cause latency spikes on the replicas that serve them, make streaming and repair slow, and can exceed message size limits. We reject values over 1 MB with TOO_LARGE for these reasons.
Better: store the blob in object storage and the metadata in the key-value store. The application uploads the file to object storage such as Amazon S3 or Google Cloud Storage, which scales almost without limit and has its own durability and lifecycle policies. The key-value store holds a small record: file:123 → {bucket, object_key, size, checksum, version}. This raises a consistency question between two stores:
- File uploaded, metadata write failed. This leaves an orphan blob. Fix it with a lifecycle rule or a cleanup job that deletes unreferenced objects older than a day.
- Metadata written, upload failed. This leaves a dangling pointer. Fix it by writing metadata with a
status = pendingfield, and flipping it toavailableonly after the upload is confirmed.
Best: upload directly to object storage and record the outcome. Routing the file through our servers means uploading it twice: once to us, once to blob storage. Instead the client gets a short-lived pre-signed URL, uploads directly, and the storage service's completion notification (or the client's confirmation, checked against the object's checksum) updates the metadata record to available. The key-value store then holds only metadata, kilobytes per file, which is what it is good at. See Pattern: Handling Large Files and Blobs and Object Storage and Blob Storage.
12) How does the store work across multiple regions?#
Basic: one cluster stretched across regions with global quorums. With N = 3 spread over three regions and QUORUM everywhere, every write waits for a cross-region round trip, 80-200 ms. The p99 goal of 10 ms is impossible, and a region failure isolates a third of the replicas. Global quorums suit only small, critical metadata.
Better: N replicas per region, LOCAL_QUORUM, and asynchronous cross-region replication. Each region has its own full set of 3 replicas. Cassandra does this with NetworkTopologyStrategy and a replication factor of 3 in each data centre. A write at LOCAL_QUORUM waits for 2 local replicas, about 2 ms, and the coordinator forwards it to one node in each remote region, which fans out locally. Remote regions converge within roughly the cross-region latency plus queueing, typically under a second.
- Reads at
LOCAL_QUORUMare fresh within a region. A user who writes in Europe and immediately reads in the US may see the old value. Route each user to a home region to avoid this ("sticky" routing). - Conflicts across regions are the same conflicts as before, just more frequent during inter-region partitions. The per-table policy applies: LWW, CRDTs or siblings.
EACH_QUORUMwaits for a quorum in every region. It is for the rare write that must be durable in all regions before acknowledging.- Repair must also run across regions. Cross-region bandwidth is expensive, so Merkle comparisons save a great deal compared with full scans.
Best: choose a per-table home region, or active-active, depending on conflict tolerance, and budget the replication lag.
- Active-active. Any region accepts writes for any key, with conflict handling. This is right for "always writable" data such as carts, presence and counters, using CRDTs. DynamoDB global tables historically resolved conflicts with last-writer-wins across regions. This is fine for data with one natural writer and lossy for concurrent writers.
- Home region per key. Writes for a key go to its home region, for example the user's region, and are replicated elsewhere for reads and disaster recovery. There are no cross-region conflicts, and the user sees their own writes. The cost is a remote write if the user travels, and a failover procedure to move the home when a region dies.
- Budget the recovery point. With asynchronous replication, a region loss can lose up to the replication lag of writes: at 1 s of lag and 100k writes per second, about 100k writes. If that is not acceptable for some table, that table needs synchronous cross-region writes and must accept the latency.
See Database Replication and Consistency Models.
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| One replica slow (GC pause, noisy disk) | p99 rises if requests wait for it | Wait for the fastest W or R of N, route by measured latency, speculative retry to another replica after a p99-based delay |
| A node dies | Its ranges drop to 2 of 3 replicas. Writes go to substitutes as hints | Sloppy quorum and hinted handoff, fast replacement by streaming from many sources, alert on time with reduced redundancy |
| A whole zone fails | Every range loses exactly one replica | Zone-aware placement (one replica per zone) so QUORUM keeps working. Capacity headroom so the surviving zones absorb the load |
| Network partition between zones | Coordinators on each side see different replica sets | Sloppy quorums keep writes available. Vector clocks or CRDTs merge after healing. Strict QUORUM callers get UNAVAILABLE on the minority side |
| Hot key or hot partition | Its 3 replicas saturate while the rest are idle | Hot-key detection, key splitting for write-hot counters, ONE reads or a cache for read-hot keys, per-partition throttling |
| Compaction falls behind | Read amplification and disk usage grow, p99 climbs | Throttled, prioritised compaction. Alert on pending bytes. The right strategy per table. Add nodes before disks exceed about 60% |
| Hint storm after an outage | The returning node is overloaded, it flaps, and more hints pile up | Throttled hint replay per target, hint window, gradual reintroduction of traffic |
| Range not repaired within the grace period | Deleted data resurrects after tombstone purge | Scheduled incremental repair with a cycle well under gc_grace, alert on time since last repair, rebuild nodes that are down too long |
| Clock skew under LWW | Newer writes lose to older ones and updates vanish | NTP or PTP with skew alarms, coordinator-assigned timestamps, vector clocks or CRDTs for multi-writer data |
| Concurrent topology changes | Nodes disagree on the ring and data lands on the wrong replicas | Serialise ring changes through a small consensus log with epochs, one change at a time |
| Tombstone-heavy partitions | Reads scan thousands of tombstones and time out | Time-window compaction, range tombstones, time-bucketed keys, no queue-like patterns |
| Sibling explosion | Values grow with unmerged siblings and reads slow down | Merge on read and write back, CRDT types, a sibling-count limit with alerts, dotted version vectors |
What Interviewers Expect#
Mid-level#
- Clarify the API (get, put, delete, with no range scans) and the scale, then do a quick capacity estimate that arrives at roughly 100 nodes.
- Partition with consistent hashing and explain why
mod Nfails. Replicate N = 3 and explain the R + W > N quorum rule. - Describe a basic write and read path through a coordinator, and name an LSM tree as the storage engine with a reason ("write-heavy").
- Recognise that conflicts can happen and name last-write-wins as a simple resolution.
Senior#
- Explain virtual nodes and zone-aware preference lists, and why that placement keeps quorums alive through a zone failure.
- Contrast strict and sloppy quorums, describe hinted handoff precisely, and say what it does and does not guarantee.
- Explain vector clocks with a worked example of siblings, and know when LWW is acceptable.
- Describe read repair and Merkle-tree anti-entropy, and why tombstones and a grace period are needed.
- Discuss storage-engine trade-offs: compaction strategies, Bloom filters, and the WAL fsync policy and what "acknowledged" means.
- Give latency reasoning: waiting for 2 of 3 hides one slow replica. Know that quorums are not linearizable, with an example.
Staff+#
- Frame the leaderless versus leader-per-partition decision from the requirements and argue for one, including when DynamoDB-style Multi-Paxos per partition is better.
- Discuss fixed partitions versus random tokens (the Dynamo paper's three strategies), the replica-set overlap risk, and how token choice affects durability.
- Quantify durability from failure rates and repair time. Name PBS-style staleness measurement and phi accrual detection.
- Handle operations: concurrent topology changes and why rings move into consensus logs, repair scheduling against
gc_grace, hint storms, compaction backlogs and cross-zone cost. - Cover the multi-region strategy (
LOCAL_QUORUM, home regions versus active-active with CRDTs, a recovery-point budget) and multi-key consistency (sagas, outbox, conditional writes).
Deep Dive: The mathematics of durability, quorums, Bloom filters and gossipShow
Durability: how likely is losing all three copies? Assume each node fails independently at an annual rate of 3%, so λ ≈ 3.4 × 10^-6 per hour, and a failed node's data is fully re-replicated in T = 2 hours. A range is lost only if, after one of its replicas fails, both other replicas fail within T. For a specific pair, that probability is about (λT)² = (6.8 × 10^-6)² ≈ 4.6 × 10^-11.
A failed node holds about 114 partition replicas, so about 114 such pairs are at risk: about 5 × 10^-9 per node failure. With 108 nodes × 3% ≈ 3.2 node failures a year, the expected loss events per year come to about 1.7 × 10^-8. That is astronomically durable, if failures are independent. Two lessons follow:
- Repair time matters as a square. Halving T cuts the risk by four. This is why parallel streaming from many sources (Deep Dive 8) is a durability feature, not just an operational nicety.
- Correlated failures dominate real risk. A power event, a bad kernel or firmware rollout, or an operator mistake can take out many nodes at once.
Replica-set placement and simultaneous failures. Suppose three nodes, one in each zone, fail together. Is some key lost? With 36 nodes per zone there are 36³ = 46,656 possible cross-zone triples.
- Fixed partitions. With Q = 4,096 partitions, at most 4,096 distinct triples hold data, so a random simultaneous triple failure loses data with probability at most about 4,096 ÷ 46,656 ≈ 9%.
- Random tokens. With 256 random tokens per node, almost every triple holds some range, so the probability is close to 100%.
"Copysets: Reducing the Frequency of Data Loss in Cloud Storage" (Cidon and colleagues, USENIX ATC 2013) formalises this. Deliberately limiting the number of distinct replica sets makes data loss far less frequent during correlated failures, at the cost of losing more data when it does happen, and of slower recovery because fewer nodes share each set. The total amount of data at risk is the same. What changes is how often a loss happens.
Quorum availability. If each replica is independently available with probability p = 0.999, then a quorum of 2 of 3 is available with probability p³ + 3p²(1 − p) ≈ 1 − 3(1 − p)² ≈ 1 − 3 × 10^-6, about "five and a half nines". Requiring all 3 gives p³ ≈ 0.997, worse than a single node. This is the arithmetic behind "never wait for all replicas". With sloppy quorums, the availability of writes becomes "any W of the whole cluster's nodes are reachable", which is essentially always.
Bloom filters. With m bits, n keys and k hash functions, the false-positive rate is p ≈ (1 − e^(−kn/m))^k. The optimal k is (m/n) ln 2, which gives p ≈ 0.6185^(m/n). So:
| Bits per key | Best k | False positives |
|---|---|---|
| 5 | 3-4 | ≈ 9% |
| 10 | 7 | ≈ 0.8% |
| 15 | 10 | ≈ 0.07% |
Each extra ~4.8 bits per key divides false positives by 10. For an LSM read touching 6 levels, the expected wasted disk reads are 6p. At 10 bits per key that is 0.05 extra reads, for about 350 MB of RAM per node. The formula is from Burton Bloom's 1970 paper "Space/Time Trade-offs in Hash Coding with Allowable Errors". See Probabilistic Data Structures for Big Data.
Leveled compaction write amplification. With a size ratio T between levels (usually 10), moving data from level i to level i + 1 rewrites the overlapping part of level i + 1. In the worst case that is about T bytes rewritten per byte pushed down. Over L levels the worst case is about T × L, roughly 60 for T = 10 and L = 6. Measured values are typically 10-30, because merges overlap only part of the next level and many keys are overwritten before they sink. Size-tiered compaction rewrites each byte about once per tier, so its write amplification is about the number of tiers (about 3-5), but a read may check several files per tier. These are the RUM (read, update, memory) trade-offs: no engine minimises all three.
Gossip convergence. In simple push gossip, where each informed node tells one random node per round, Boris Pittel's 1987 analysis shows that spreading to n nodes takes about log₂ n + ln n rounds. That is about 11-12 rounds for n = 108, so about 11 seconds at one round per second. Push-pull exchanges converge faster: Karp and colleagues (FOCS 2000) showed about log₃ n + O(log log n) rounds. The practical point is that convergence time grows logarithmically. Going from 100 to 10,000 nodes roughly doubles it.
Staleness after a write. With W = 1 and R = 1, a read issued t milliseconds after a write is stale if the replica it reads has not yet received the write. If replication delays are roughly exponential with mean 5 ms, P(a given other replica has not received the write by time t) = e^(−t/5). A read picks the write's replica with probability 1/3 and is then fresh, so P(stale) ≈ (2/3) × e^(−t/5). That is about 0.24 at 5 ms, 0.09 at 10 ms, and about 0.00003 at 50 ms. Probabilistically Bounded Staleness turns this kind of reasoning into measured predictions for real clusters.
Deep Dive: Dynamo, Cassandra, Riak, DynamoDB and what each one teachesShow
Amazon Dynamo (2007). The SOSP paper describes an internal store, not the later DynamoDB service. It used:
- consistent hashing with virtual nodes, evolving towards fixed equal-sized partitions,
- N replicas on a preference list, with configurable R and W (commonly (3, 2, 2)),
- sloppy quorums and hinted handoff,
- vector clocks with client-side reconciliation (the shopping cart merges by union),
- Merkle trees per key range for anti-entropy,
- gossip-based membership with explicit administrator-driven joins and leaves, and seed nodes.
The storage engine was pluggable: Berkeley DB, MySQL, or an in-memory buffer with persistent backing. Performance goals were expressed at the 99.9th percentile rather than as averages. It is a short, readable paper, and nearly every idea on this page traces back to it. Its most lasting lesson is not any single technique but the stance: a business requirement ("always accept add-to-cart") determines the consistency model, and the rest of the architecture follows from it.
Apache Cassandra. Avinash Lakshman, one of the Dynamo authors, and Prashant Malik built Cassandra at Facebook for inbox search. They described it in "Cassandra: A Decentralized Structured Storage System" (LADIS 2009). It combines Dynamo's distribution (ring, replication, gossip, hinted handoff, tunable consistency) with Bigtable's data model and storage (column families, memtables, SSTables and compaction). Key differences from Dynamo:
- Last-write-wins per cell with timestamps instead of vector clocks. It is simpler for applications, but lossy under concurrent writes.
- Partition and clustering keys, so a partition can be scanned in order.
- Phi accrual failure detection.
- Lightweight transactions via Paxos.
- Rack- and data-centre-aware replication with
LOCAL_QUORUM.
Its operational reputation comes from the same places this page warns about: repair within gc_grace_seconds, tombstone-heavy reads, compaction strategy choice, and topology-change races. Newer versions address these, for example with transactional cluster metadata.
ScyllaDB is a C++ reimplementation compatible with Cassandra. It is built on the Seastar framework with a shard-per-core architecture: each CPU core owns a slice of the data and runs its own event loop, without locks shared across cores. It shows how much of a node's throughput depends on the engine's concurrency model rather than the distributed design.
Riak (Basho). The most faithful open-source Dynamo implementation. It has a fixed ring of partitions (vnodes) claimed by physical nodes, vector clocks and later dotted version vectors, siblings returned to clients, and the Bitcask and LevelDB storage backends. It also added built-in CRDT data types (counters, sets, maps), which made conflict resolution automatic for common cases. Riak showed both the power and the cost of exposing siblings to application developers: correct, but demanding. That experience is part of why CRDTs became the recommended path.
Project Voldemort (LinkedIn) was another Dynamo-inspired store. It was notable for read-only stores built offline in Hadoop and swapped in atomically, a pattern for serving large batch-computed datasets (such as recommendations) with key-value latency.
Amazon DynamoDB. A managed service launched in 2012. Its 2022 USENIX ATC paper (Elhemali and colleagues) describes a design that differs substantially from the 2007 paper:
- Partitions are replicated with Multi-Paxos, and a leader serves writes and strongly consistent reads.
- Request routers use a metadata service to find partition leaders.
- Admission control and adaptive capacity provide predictable performance in a multi-tenant system.
In other words, Amazon's own managed key-value store chose leader-based replication per partition for predictable consistency and operability, and kept the ideas of the original (partitioning, replication across zones, a simple API) rather than its leaderless mechanics. It is the best evidence for the trade-off discussion in Deep Dive 10.
Leader-based ordered key-value stores. Google's Bigtable (OSDI 2006) and its open-source sibling HBase partition by key range into tablets or regions. Each is served by exactly one server at a time, on top of a replicated file system (GFS or HDFS), with a lock service (Chubby or ZooKeeper) to guarantee single ownership. TiKV and CockroachDB's storage layer use Raft per range on RocksDB-style LSM engines. FoundationDB provides an ordered, transactional key-value store with strict serializability. It is known for its deterministic simulation testing, in which the whole cluster runs inside a simulator that injects failures reproducibly. These systems show the other branch of the design tree: ordered keys, range scans, transactions, and leaders instead of quorums.
Lessons from testing and production:
- Last-write-wins loses data under concurrency. Jepsen's 2013 analyses of Riak and Cassandra configurations showed acknowledged writes disappearing under partitions when LWW was in use. Choose LWW only when that is acceptable.
- Repair is not optional. The most common serious incident in leaderless stores is resurrected deletes or permanently diverged replicas after repair stopped running unnoticed.
- Membership must be boring. Topology changes are rare but dangerous. Systems are moving them into consensus logs.
- Predictability beats peak speed. DynamoDB's paper emphasises consistent latency under multi-tenancy. Admission control, throttling and isolation matter as much as raw throughput.
Deep Dive: Variant: a key-value store for a search engine's query resultsShow
A classic interview variant asks for "a key-value store for a search engine". It really means a key-value cache of recent query results, which needs a much simpler design than a durable Dynamo-style store, and it is worth showing that you can tell the difference.
Requirements and numbers. There are 10 million users and 10 billion queries a month, which is about 4,000 requests per second on average (a month is about 2.5 million seconds). Traffic is very uneven: popular queries should almost always be cached. Each entry maps a normalised query string (about 50 bytes) to a result list. Storing titles (about 20 bytes) and snippets (about 200 bytes) gives about 270 bytes per entry. If every query were unique and kept, that would be 2.7 TB a month. Memory is limited, so we must choose what to keep: evict by LRU and expire by TTL.
The query path.
- The web server, acting as a reverse proxy, forwards the query to the Query API.
- The Query API normalises it: strip markup, split it into terms, fix typos, lower-case it, and convert it to a canonical boolean form. That way "Pizza NYC" and "pizza nyc" share one cache key. Normalisation quality directly sets the hit ratio.
- It looks up the normalised query in the memory cache. On a hit, it moves the entry to the front of the LRU list and returns the results. Memory reads take microseconds. Reading 1 MB sequentially from memory takes about 250 µs, about 4 times faster than SSD and about 80 times faster than spinning disk.
- On a miss, it asks the reverse-index service for matching, ranked document ids, then asks the document service for titles and snippets. It stores the result in the cache at the front of the LRU list.
The cache itself is the hash map plus doubly linked list from the distributed cache case study. Lookups go through the map, new entries go to the head of the list, and evictions come from the tail.
When to refresh entries. Cached results go stale when page contents change, when pages are added or removed, or when ranking changes. Tracking every dependency is impractical, so the simple, robust answer is a TTL on every entry. It is minutes to hours for most queries and shorter for news-like queries, with cache-aside filling on the next miss. Popular queries can be refreshed ahead of expiry, which keeps them always warm.
Scaling to many machines. There are three options:
- Each machine keeps its own independent cache. It is simple, but the hit ratio is low, because every machine must warm each popular query separately.
- Each machine has a full copy. It is simple and good for reads, but it wastes memory, and the total capacity is that of one machine.
- Shard the cache with
machine = hash(query), using consistent hashing so adding machines moves few keys. It is more complex, but it is the right choice: total capacity is the sum of all machines, and each query is cached once.
Replicas of shards, or a small local L1 for the very hottest queries, handle read hot spots.
Why it is not the Dynamo design. It needs no quorums, vector clocks, hinted handoff, Merkle repair or tombstones, because nothing is a source of truth and losing an entry costs only a recomputation. Saying that explicitly, and mapping the problem to a cache with LRU, TTL and sharding, is the correct answer. Durability machinery would be over-engineering. See Distributed Caching with Redis and Memcached and Caching Strategies: Cache-Aside, Read-Through, Write-Through, Write-Behind.
Deep Dive: Building, testing and operating the storeShow
Stage 1: do not build it. For most companies, the right answer is a managed store: DynamoDB, Cassandra-as-a-service, Bigtable or Cosmos DB. Or run Cassandra or ScyllaDB yourself. The design work is choosing keys, consistency levels and conflict policies per table, and capacity planning. Interviewers like hearing this, as long as you can then design the internals when asked. See Amazon DynamoDB in Practice and Apache Cassandra in Practice.
Stage 2: build the core. A single-node LSM engine (RocksDB embedded is the usual choice), a ring with fixed partitions, a coordinator with N, R and W, LWW, read repair and a simple streaming bootstrap. Prove correctness on 3-6 nodes before adding sloppy quorums or vector clocks.
Stage 3: availability and convergence. Sloppy quorums, hinted handoff, Merkle repair, gossip with phi accrual, then vector clocks or CRDT types per table. Then multi-region with LOCAL_QUORUM, and topology changes committed through a consensus log.
Testing.
- Model-based tests. Run random sequences of puts, gets and deletes against a reference model that tracks the set of allowed outcomes (concurrent writes may produce siblings). Check that no acknowledged write vanishes under the chosen consistency level.
- Fault injection in the style of Jepsen. Partition the network between zones, pause processes (simulating GC), skew clocks, and kill nodes during streaming. Check the history with a linearizability or causal-consistency checker for the guarantees each consistency level claims.
- Deterministic simulation, as FoundationDB does. Run the whole cluster in a single-threaded simulator with controlled time and network, so a failing schedule can be replayed exactly. This is the most effective known way to find rare distributed bugs.
- Repair and resurrection tests. Delete keys while a replica is down, keep it down past the hint window, then repair. Assert that deleted keys never come back, before and after the grace period.
- Load tests at production shape. Run Zipfian key popularity, the real value-size distribution, compaction running and one node replacing. Measure p99 during the worst moment, not the average.
What to watch.
- p50, p99 and p999 latency per operation and consistency level, plus coordinator timeouts and
UNAVAILABLErates. - The read-repair rate and mismatched digests: replica divergence.
- Hints pending per target, and hints dropped past the window.
- Time since the last successful repair per range, compared with
gc_grace. - Compaction pending bytes, SSTables per read, Bloom false-positive rate, and tombstones scanned per read.
- Disk usage per node: keep it under about 60-70%.
- Gossip state: nodes down as seen by each node, and disagreement between views.
- Cross-zone and cross-region bytes, which are a large part of the bill.
Cost. 108 storage nodes with NVMe is the main hardware cost, and cross-zone replication traffic can be a comparable cloud line item. The levers:
- Compression in SSTables, typically 2-4 times for text-like values, which reduces disk and streaming.
- The right compaction strategy, which cuts disk bandwidth.
- Tiering cold data to cheaper storage.
- A replication factor chosen per table (some derived data can use N = 2).
- Avoiding over-provisioned consistency (
ALL), which adds latency without benefit.
Key Takeaways#
- The requirement picks the architecture. "Never refuse a write" leads to a leaderless Dynamo design with sloppy quorums, hinted handoff and conflict resolution. "Never show a stale or conflicting value" leads to Raft or Paxos per partition, as in DynamoDB, TiKV and Spanner. See Consensus: Raft and Paxos.
- Placement: consistent hashing with fixed partitions or virtual nodes, a preference list of N = 3 distinct nodes in distinct zones, and token-aware clients. See Consistent Hashing and Partitioning and Sharding.
- Quorums: R + W > N gives overlapping quorums and hides a slow replica. It is not linearizability, and sloppy quorums weaken it further. See Quorums and Leaderless Replication.
- Conflicts: last-write-wins is simple but loses concurrent writes. Vector clocks detect concurrency and return siblings. CRDTs merge automatically. Choose per table.
- Convergence needs three layers: hinted handoff for short outages, read repair for hot keys, and Merkle-tree anti-entropy for everything else, finished within the tombstone grace period so deletes never resurrect.
- Each node is an LSM tree: a WAL with group commit, a memtable, SSTables with Bloom filters, and a compaction strategy matched to the workload. See Storage Engines: B-Trees vs LSM Trees.