What you'll learn: By the end of this lesson you will be able to (1) design a partitioned, replicated key-value store from the ring up, (2) choose N, R and W and say what each choice buys, (3) explain how versions, conflicts, hinted handoff and anti-entropy repair keep replicas converging, (4) describe the per-node storage path, and (5) say when a consensus-based store is the better answer.
This is an educational reference design, not the verified internal architecture of any company. It follows the public design of Dynamo-style stores, as described in the original Dynamo paper and in the Apache Cassandra documentation, and it is a teaching sketch rather than a copy of either system.
A town keeps its records in a hundred filing cabinets spread over many buildings. Each record has a home cabinet, and two neighbouring cabinets keep copies. To file a record a clerk needs two of the three cabinets to confirm; to read it, two of the three to answer. If one building floods, the clerk files the record in a spare cabinet with a note "belongs to the cabinet in building A, return it when it dries out". Once a month, clerks compare summaries of two cabinets and re-copy only the drawers that differ.
That is a distributed key-value store: a ring of cabinets, copies, two-out-of-three confirmation, notes for absent neighbours, and periodic comparison. This lesson builds it step by step. It assumes consistent hashing and quorum reads and writes, and uses the case study template from the case studies overview.
The core idea
A key-value store trades a rich query model for scale and availability: one key, one opaque value, a handful of operations, and every operation routed to a small set of replicas chosen by a hash.
Four mechanisms do the work, and each answers one question:
| Question | Mechanism |
|---|---|
| Which nodes own this key? | Consistent hashing with virtual nodes, and a preference list of N replicas |
| When is a read or write successful? | R and W counts, with R + W > N for overlap |
| What if replicas disagree? | Versions (vector clocks) and reconciliation |
| How do replicas converge after failures? | Hinted handoff, read repair, Merkle-tree anti-entropy |
Requirements and scope
Functional:
put(key, value),get(key)anddelete(key)on opaque byte values.- Single-key operations only: no joins, no multi-key transactions, no secondary indexes.
- Values up to about 1 MB, consistent with the Dynamo paper's stated target of "relatively small (usually less than 1 MB)" objects.
- Add and remove nodes without downtime.
Out of scope: range scans, secondary indexes, multi-key transactions, security and tenancy (the Dynamo paper assumes a trusted, non-hostile environment; this design does too), and multi-region replication, which is only sketched.
Non-functional (assumptions):
- Always writable: a write should succeed when a single zone is down, even when some replicas are unreachable.
- Tunable consistency per request or per table.
- Latency at the tail, p99, under 20 ms inside a region (assumption).
- No acknowledged write lost on a single node failure.
- Operationally boring: no single coordinator node, no manual rebalancing for routine failures.
Back-of-envelope estimate
All numbers are illustrative assumptions.
| Quantity | Assumption | Result |
|---|---|---|
| Keys | 1 billion | |
| Average value size | 2 KB | 2 TB of raw data |
| Replication factor N | 3 | 6 TB stored |
| Peak operations | 300,000 per second, 80% reads | 240,000 reads and 60,000 writes per second |
| Replica operations | Writes touch 3 replicas, reads touch R = 2 | 180,000 + 480,000 = 660,000 replica operations per second |
| One node | assume 20,000 operations per second, to be measured | 660,000 / 20,000 = 33 nodes |
| Headroom | run at about 60% of the ceiling | 33 / 0.6 = 55 nodes |
| Data per node | 6 TB over 55 nodes | about 110 GB per node |
Operation rate, not capacity, sizes this cluster: 110 GB per node is small. A cluster sized by data would be far smaller and fall over at peak. Check both constraints and take the larger.
API design
put(key, value, context?) -> { ok, version } W replicas must acknowledge
get(key) -> { values[], context } R replicas must answer; may return several versions
delete(key, context?) -> { ok } a write of a tombstone, kept for a retention period
Per request (optional): consistency = ONE | QUORUM | ALL
This mirrors the Dynamo paper's interface: get(key) returns a single object or a list of objects with conflicting versions along with a context, and put(key, context, object) writes replicas, where the context is opaque to the caller and carries version metadata. The context returned by get is passed back to put, which lets the store tell an update that builds on what the client saw from a concurrent one.
Returning a list of siblings is a real API commitment: clients must be able to merge. A store that only returns one value must pick a winner itself, which is the "last write wins" option discussed below.
Data model
The node-local record is simple.
- Key: opaque bytes, hashed to a position on the ring. Dynamo applies an MD5 hash to the key to produce a 128-bit identifier that selects the nodes responsible.
- Value: opaque bytes.
- Metadata: a version (vector clock or timestamp), and a tombstone flag for deletes.
Figure 1. A record and its version metadata. How to read this: the value is opaque; everything the system reasons about is the key, the version and the tombstone flag.
On disk the store keeps these records in a log-structured engine; see the storage deep dive below and storage engines.
High-level design
Figure 2. Any node can coordinate; the coordinator fans out to the key's replicas. How to read this: the client reaches a node that owns the key (or any node, which forwards); the coordinator talks to the other replicas in the preference list; nodes learn each other's state by gossip.
There is no master. Every node holds the ring layout and can route. The Dynamo paper describes this as a zero-hop design in which each node keeps enough routing information locally to route a request directly to the right node, chosen to avoid the latency variability of multi-hop routing. The cost is that every node must have a view of membership, which the paper notes works for a few hundred nodes and gets harder at tens of thousands.
How a write travels
- The client library hashes the key and sends the request to a node in the key's preference list (or any node, which forwards it).
- The coordinator builds the new version (a vector clock that supersedes the one in the supplied context) and writes it locally.
- It sends the version to the other N - 1 replicas, and waits for W - 1 acknowledgements.
- It replies when W replicas have written. Remaining replicas continue in the background.
Figure 3. A write with W = 2 and a read with R = 2 on three replicas. How to read this: the write is acknowledged after two replicas have it; the third catches up. The later read sees both versions, returns the newer, and repairs the stale replica.
Reference deployment topology
Replicas of a key should not share a failure domain. The preference list is built to skip nodes in the same zone, so the three replicas of a key sit in three zones. The Dynamo paper does the same across data centres: it constructs the preference list so the storage nodes are spread across multiple data centres, which lets the system survive an entire data-centre failure.
Figure 4. One replica of each key per zone. How to read this: three nodes stand for three zones, each of which holds many nodes in practice. A zone outage leaves two of three replicas, so W = 2 and R = 2 still succeed.
Deep dive 1: partitioning and the preference list
Partitioning is consistent hashing. The hash output range is a ring; each node is assigned positions (tokens) on it; a key is hashed and walks clockwise to the first node. The Dynamo paper lists the problem with the basic scheme (random positions give uneven load, and it ignores differences in node capacity) and the fix, virtual nodes: each physical node takes several positions. With virtual nodes, a failed node's load spreads over many others, a new node takes a similar amount from each existing node, and the number of virtual nodes can follow a node's capacity. The Cassandra documentation describes the same idea and notes that its older default was 256 tokens per node, with newer allocation needing far fewer. See consistent hashing for the mechanics and a lab.
The preference list for a key is the first N distinct physical nodes found walking the ring from the key's position. Distinct matters: with virtual nodes, the next positions can belong to the same machine, so the list skips repeats. In this design it also skips nodes in the same zone.
Hot keys and skew. Hashing spreads keys, not load: one very popular key still lands on one replica set. The Dynamo paper's design assumes there are enough popular keys that load spreads across nodes. Where one key dominates, cache in front of the store or split the key in the application. See hot partitions and resharding.
Deep dive 2: replication and the quorum choice
With N replicas, a successful read needs R and a successful write needs W. Setting R + W > N makes the read and write sets overlap, so a read meets at least one replica that has the latest acknowledged write. The Dynamo paper adds that latency is dictated by the slowest of the R or W replicas, which is why R and W are usually below N. It reports (N, R, W) = (3, 2, 2) as the common configuration across its instances.
| Setting (N = 3) | Read | Write | Behaviour |
|---|---|---|---|
| R = 2, W = 2 | Quorum | Quorum | Overlap; one replica may be down for either operation |
| R = 1, W = 3 | Fast reads | Slow, fails if any replica is down | Read-optimised; writes lose availability |
| R = 3, W = 1 | Slow reads | Fast, always writable | Write-optimised; reads lose availability |
| R = 1, W = 1 | Fast | Fast | No overlap; stale reads are normal |
The paper also notes that raising W shrinks the window in which a write exists on too few nodes, at the price of more rejected writes when nodes are down, and that setting W to 1 makes a write succeed as long as one node can take it. The Cassandra documentation expresses the same choice as consistency levels: ONE, QUORUM (a majority, n/2 + 1) and ALL, with writes always sent to all replicas, and it points out that picking read and write levels whose replica sets overlap is common.
Overlap is not the same as linearizability. Concurrent writes, sloppy quorums (below) and a read that coordinates with a lagging replica can all still return an old value; see consistency models and quorum reads and writes, whose lab shows these cases.
Deep dive 3: versions, conflicts and reconciliation
If writes are always accepted, two clients can update the same key on different replicas at once. The store must detect that and not silently drop one.
Vector clocks. Each version carries a list of (node, counter) pairs. Version A supersedes version B if A's counters are all at least B's; otherwise the two are concurrent and both are kept as siblings. A read returns all siblings with the context, and the client (or a merge function) writes back a merged value whose clock supersedes them. Dynamo pushes this reconciliation to reads so that writes are never rejected, and gives the shopping cart, where a customer may add or remove items during failures, as the motivating example. See logical and vector clocks.
Clock growth. Clocks can grow when writes are handled by nodes outside the top N of the preference list. Dynamo stores a timestamp with each pair and, when the number of pairs reaches a threshold (it says "say 10"), removes the oldest. The paper acknowledges that truncation can make descendant relationships inexact, and says the problem had not surfaced in production.
How often are there siblings? In the paper's 24-hour measurement of a shopping cart service, 99.94% of requests saw exactly one version. It attributes growth in divergent versions more to the number of concurrent writers, often automated clients, than to failures. That is one service's measurement, not a general rate.
Last write wins. The simpler alternative keeps the version with the latest timestamp and discards the rest. It needs no client merge logic, and it silently loses one of two concurrent writes, and depends on clocks that can be wrong. Use it where overwriting is acceptable and each key has one logical writer; use siblings or CRDTs where concurrent updates must merge.
Figure 5. Choosing a conflict strategy. How to read this: the question is whether concurrency on one key is possible and whether values merge mechanically.
Deep dive 4: failures, hinted handoff and anti-entropy
Three mechanisms, working at three speeds.
Hinted handoff (seconds to hours). A strict quorum over the first N replicas would refuse writes whenever one is down. Dynamo uses a "sloppy quorum": reads and writes go to the first N healthy nodes on the preference list, which may not be the first N on the ring. If node A is down, its replica goes to the next node D with a hint naming A. D keeps hinted replicas in a separate local store, and when it sees A is back it hands the replica over and may then delete it. The paper says this keeps reads and writes from failing because of temporary node or network failures, and that it works best when membership churn is low. Cassandra's documentation lists hinted handoff and read repair as best-effort techniques to drive convergence. A write acknowledged through a hint is durable, but a read that does not reach the hint holder may not see it until the hint is delivered.
Read repair (on the read path). When a read finds replicas at different versions, the coordinator returns the newest and writes it to the stale ones, as in Figure 3. It repairs only keys that are read.
Anti-entropy with Merkle trees (minutes to days). Keys that are never read, or whose hints were lost, need a background sweep. Each node keeps a Merkle tree, a hash tree whose leaves are hashes of individual keys' values, for each key range it hosts. Two replicas exchange tree roots; equal roots mean no work; otherwise they descend into children until they find the specific keys that differ, so only those are transferred. The paper notes a drawback: when a node joins or leaves, many ranges change and trees must be recomputed, which its refined partitioning scheme addresses. Cassandra supports full and incremental repair, the latter limited to partitions changed since the last repair.
Failure detection and membership. Nodes learn who is up through gossip. In Dynamo, membership changes are issued by an administrator, written to a persistent history and propagated by a gossip protocol in which each node contacts a random peer every second. Failure detection is local and decentralised: a node that does not get a response from a peer treats it as failed for its own routing and retries later. Cassandra's gossip documentation describes the once-per-second exchange and a phi accrual failure detector. See gossip protocols and failure detectors.
A permanent node loss is a different event from a transient outage. Treating every outage as permanent causes needless re-replication; treating a dead node as transient leaves data under-replicated. Dynamo's design uses an explicit administrative step to add or remove a node, partly for that reason.
Deep dive 5: the node-local storage engine
Each node stores its share in a log-structured engine. The Cassandra storage-engine documentation lists the write path in order: append to a commit log, write to a memtable, flush the memtable to disk, store it as an SSTable. The commit log is append-only and exists so that data can be recovered after an unexpected shutdown, with durability depending on its configured sync mode. The memtable buffers writes in sorted order and serves reads without touching disk until it reaches a limit, when it is flushed as an immutable SSTable. A partition can therefore be spread across several SSTables, and compaction merges them in the background, at the cost of rewriting data (write amplification). Bloom filters over each SSTable's partition keys speed reads by skipping files that cannot hold the key.
This explains the shape of the store's performance. Writes are sequential appends, so they are fast and steady. Reads may touch several files, so they are helped by filters and caches, and hurt by a compaction backlog. Deletes are writes of tombstones, which must be kept long enough for every replica to see them, or a stale replica can bring a deleted value back. See storage engines for B-tree and LSM trade-offs.
Deep dive 6: when a consensus store is the better answer
Everything above is an AP-leaning design: always writable, eventually consistent, conflicts resolved at read time. Some key-value workloads need the opposite: a single agreed order, linearizable reads, compare-and-set, small metadata such as locks, leader records and configuration.
Raft is the usual building block. It elects a leader that manages a replicated log; an entry is committed once it is replicated on a majority of servers; a cluster makes progress as long as a majority is up. The paper notes that Raft produces a result equivalent to (multi-)Paxos. A Raft-based store is simple to reason about and gives strong guarantees, but each write goes through one leader, availability depends on a majority being reachable, and throughput does not scale by adding nodes to one group. To scale, such systems shard the key space into many independent groups. See consensus and leader election.
| Need | Dynamo-style | Raft-based |
|---|---|---|
| Always accept writes during a partition | Yes (sloppy quorum, siblings) | No: the minority side cannot commit |
| Single order, compare-and-set | No | Yes |
| Scale writes by adding nodes | Yes, by partitioning | Only by adding more groups |
| Typical use | Carts, sessions, profiles, feature state | Locks, configuration, leader records, metadata |
Failure modes
| Failure | Effect | Mitigation |
|---|---|---|
| One replica down | Operations at R = 2, W = 2 still succeed | Hints, read repair, alert on down time |
| Zone down | One replica per key lost | Zone-aware preference list |
| Network partition | Two sides accept writes | Siblings, merge on read; sloppy quorum |
| Hint holder dies | Hinted writes lost | Anti-entropy repair covers it |
| Stale replica returns | Old data or resurrected deletes | Tombstone retention longer than repair interval |
| Hot key | One replica set saturated | Cache, split key, throttle |
| Compaction backlog | Read latency rises | Compaction throttling, capacity headroom, alerts on SSTable count per read |
| Clock skew with last write wins | Newer write loses | Prefer vector clocks, or accept the risk explicitly |
| Large values | Slow replication and repair | Cap value size; store blobs elsewhere |
Trade-offs worth stating
| Decision | Option A | Option B | How to choose |
|---|---|---|---|
| Consistency | Quorum, R + W > N | ONE for reads | Quorum for correctness-sensitive keys; ONE for cache-like reads |
| Conflicts | Vector clocks and siblings | Last write wins | Siblings when concurrent writes matter; last write wins for single-writer keys |
| Membership | Full view on every node | Hierarchical or external service | Full view up to a few hundred nodes; beyond that, rethink |
| Storage | LSM tree | B-tree | LSM for write-heavy; B-tree for read-heavy point lookups |
| Coordination | Any node coordinates | Client-aware routing | Client-aware routing for lower latency, at the cost of client complexity |
| Model | Eventually consistent | Consensus-based | Match to the business need for order and linearizability |
Interview cheat sheet
| Step | What to say | Key numbers (illustrative) |
|---|---|---|
| Requirements | get, put, delete on opaque values; always writable; tunable consistency | Values under 1 MB |
| Estimate | Operations per second size the cluster, not data | 660,000 replica ops per second, 55 nodes |
| API | get returns siblings plus context; put takes the context | Consistency level per request |
| Data | Key, value, version, tombstone; LSM on disk | Commit log, memtable, SSTables |
| Design | Ring with virtual nodes, preference list, any node coordinates | N = 3, R = 2, W = 2 |
| Deep dives | Quorums, vector clocks, hinted handoff, Merkle repair, gossip | Merkle trees compare roots first |
| Failures | Node, zone, partition, stale replica, compaction backlog | Zone-aware replicas |
| Trade-offs | Availability against consistency; AP store against Raft | Match to the workload |
Build it
There is no lab for this lesson. The mechanisms it describes are each covered by a lab that already exists in the repository: the ring and virtual nodes by examples/backend/labs/consistent-hash-ring, quorum overlap by examples/backend/labs/quorum-register, sloppy quorums and hinted handoff by examples/backend/labs/quorum-sloppy-and-hinted-handoff, and version vectors by examples/backend/labs/logical-and-vector-clocks. Run those and read their README files; none of them is a complete store, and this lesson shows no output of its own.
In practice: operating the reference design
This is a realistic scenario, not a case history. It is a composite built from common production patterns and describes no specific company; every number is an illustrative assumption.
Assume a team of six runs a 55-node cluster for session and profile data across three zones, with N = 3 and default consistency QUORUM, on commodity VMs. Repairs run on a schedule from a job runner, and the usual metrics stack provides dashboards.
SLOs and dashboards
| SLI | SLO (assumed) | Dashboard panels |
|---|---|---|
| Read latency | p99 under 20 ms | Latency per node, SSTables touched per read, cache hit rate |
| Write latency | p99 under 20 ms | Commit log sync time, replica ack latency |
| Availability | 99.95% of requests succeed at QUORUM | Errors by reason, unavailable-replica count |
| Convergence | Repair completes within the tombstone retention window | Last repair time per range, pending hints, dropped hints |
| Capacity | Disk under 60%, compaction pending low | Disk per node, pending compactions |
Capacity-review cadence
- Weekly: pending compactions, hot keys, hints stored and delivered.
- Monthly: data growth against the 6 TB assumption, operations per node against the 20,000 ceiling.
- Quarterly: a zone-loss drill: take a zone out and confirm QUORUM operations still pass.
Runbook
| Symptom | Likely cause | First check | Mitigation |
|---|---|---|---|
| Read latency rises on a few nodes | Compaction backlog or a hot key | Pending compactions, per-key rates | Throttle or schedule compaction, cache the key |
| Reads return old values after an outage | Hints not delivered yet, repair overdue | Hint queue, last repair time | Wait for hints, run repair on the range |
| Deleted keys reappear | Repair interval longer than tombstone retention | Retention and repair schedule | Repair then extend retention, re-delete |
| Writes failing at QUORUM | Two replicas of a range down | Node and zone status | Restore nodes; lower consistency for tolerant keys only |
| Many siblings for a key | Concurrent writers, often automation | Writers for that key | Add a merge step or serialise the writer |
Decision record: default consistency level
| Field | Entry |
|---|---|
| Context | Session and profile data tolerates brief staleness but not loss. A single zone may be down. |
| Decision | N = 3, writes at QUORUM, reads at QUORUM; reads at ONE allowed for cache-like data on request. |
| Consequences (good) | Overlap on every read; one zone can fail with no errors. |
| Consequences (bad) | Reads cost two replica reads; a second failure in the same range makes it unavailable. |
| Revisit when | Read cost dominates the bill, or a workload needs a single order or compare-and-set. |
The 2 a.m. failure
A node is down for most of a day for a hardware swap, and the stored hints for it exceed the retention window, so some are dropped. The node returns and answers reads with data that is hours old for keys written during the outage. Clients reading at QUORUM are fine because they meet an up-to-date replica; the few reads at ONE see the stale copy. The first check is hints stored and dropped and the last repair time for that node's ranges. The mitigation is to run repair for the node's ranges before sending it ONE traffic. The lasting fix is a runbook step that makes repair after any long outage mandatory, and an alert on dropped hints.
Architect's notes
- Say what each mechanism is for. Hints are for short outages, read repair for hot keys, Merkle repair for everything else.
- Settle the conflict model with the application team on day one. Siblings need client code, and last write wins needs one logical writer.
- Repair on a schedule, and keep tombstones longer than the repair interval. Otherwise deletes come back.
- Test the zone-loss case. The design promises it; only a drill shows it.
- Be honest that this is eventual consistency. If product needs "read your latest write", say which requests use QUORUM and what that still does not guarantee.
Common mistakes
- Assuming R + W > N means linearizable. Overlap helps, but sloppy quorums, concurrent writes and lagging coordinators still produce stale or conflicting reads.
- Dropping conflict handling. Without siblings or a merge rule, one of two concurrent writes is silently lost.
- Tombstones that expire before repair. A stale replica then resurrects a deleted value.
- Treating a transient outage as permanent. It triggers needless re-replication; use an explicit step for permanent removal.
- Sizing by data only. Operations per second often set the node count.
- Putting large values in the store. Replication and repair slow with value size.
Key takeaways
- A key-value store is a hash ring, a preference list of N replicas and a rule for how many must answer.
- R + W > N gives overlap; it is a statement about quorums, not a promise of a single global order.
- Concurrency is handled by versions: vector clocks and siblings, or an explicit last-write-wins choice.
- Three repair mechanisms at three speeds: hinted handoff, read repair and Merkle-tree anti-entropy.
- The node-local engine is an append-only commit log, a memtable and immutable sorted files merged by compaction.
- When a single order or compare-and-set is needed, use a consensus-based store instead, and shard it by groups.
Practice exercises
Exercise 1 - Starter (30 min): Redo the estimate with 500,000 operations per second at 50% reads, N = 3, R = 2, W = 2, a node ceiling of 25,000 operations per second and 60% headroom. How many nodes?
Exercise 2 - Intermediate (2 hours): For N = 5, list the (R, W) pairs that satisfy R + W > N and give one workload for each of R = 1, R = 3 and W = 1.
Exercise 3 - Intermediate (2 hours): Two clients update the same key on different replicas during a partition. Draw the vector clocks before, during and after, show the siblings a reader receives, and write the merge for a shopping cart.
Exercise 4 - Advanced (half day): Design the repair schedule: how often to run Merkle repair, how long to retain tombstones and hints, and what you alert on. Explain what goes wrong if the repair interval exceeds the tombstone retention.
Related reading
- Consistent hashing - the ring, virtual nodes and the lab.
- Quorum reads and writes - R + W > N, sloppy quorums and read repair, with labs.
- Multi-leader and leaderless replication - conflicts and repair in leaderless stores.
- Logical and vector clocks - version vectors and concurrency detection.
- Gossip protocols and failure detectors - membership and phi accrual.
- Storage engines - LSM trees, compaction and amplification.
- Consensus and leader election - the Raft-style alternative.
The other side of this topic is the client library: it hashes keys, retries sensibly, and merges siblings.
Official documentation
- DeCandia et al., Dynamo: Amazon's Highly Available Key-value Store (SOSP 2007).
- Apache Cassandra, Dynamo architecture: partitioning, consistency levels, hints, repair, gossip.
- Apache Cassandra, Storage engine: commit log, memtable, SSTables, compaction.
- Ongaro and Ousterhout, In Search of an Understandable Consensus Algorithm (Raft).