TExcelTAD
Home › System Design › Design a Key-Value Store

Design a Key-Value Store

A distributed key-value store offers two operations, put(key, value) and get(key), across many machines, with no single point of failure. Amazon's Dynamo paper described the classic design, and Cassandra, Riak, ScyllaDB and DynamoDB all descend from it. This case study puts together several lessons: consistent hashing, replication, quorums, versioning and failure detection.

1. Requirements

  • put / get of values up to 1 MB; keys are strings.
  • Always writable (AP): a shopping cart must accept writes even during a partition.
  • Tunable consistency: callers choose N, R, W.
  • Scales horizontally to hundreds of nodes; adding a node needs no downtime.
  • p99 latency under 10 ms within a region.

2. Estimates

python · try it yourself
keys = 2_000_000_000
avg_value_kb = 2
replicas = 3
node_disk_tb = 4
target_fill = 0.6                       # leave room for compaction and growth
ops_per_s = 400_000
node_ops = 20_000

data_tb = keys * avg_value_kb * 1_000 / 1e12
nodes_for_data = -(-data_tb * replicas // (node_disk_tb * target_fill))
nodes_for_ops = -(-ops_per_s * replicas // node_ops)     # each op touches ~N replicas
print(f"raw data: {data_tb:.0f} TB, with {replicas} replicas: {data_tb * replicas:.0f} TB")
print(f"nodes needed for storage: {nodes_for_data:.0f}, for throughput: {nodes_for_ops:.0f}")
raw data: 4 TB, with 3 replicas: 12 TB
nodes needed for storage: 6, for throughput: 60

Here throughput, not storage, decides the cluster size: about 60 nodes. That is common for small values; for large values (images, documents) it's usually the other way round.

3. Architecture

text
client -> any node (coordinator for this request)
             | consistent hashing ring with virtual nodes
             v
   key -> preference list [n3, n7, n1]  (first N distinct nodes clockwise)
   put: send to all N, succeed after W acks
   get: ask N (or R), wait for R answers, return newest, read-repair the rest

each node: commit log (durability) -> memtable -> SSTables on disk (LSM tree) + Bloom filters
membership & failure detection: gossip protocol
Problem Technique
Partitioning Consistent hashing with virtual nodes
Replication N replicas on the next distinct nodes on the ring
Consistency Quorums (R + W > N), tunable per request
Conflicts Versions: vector clocks (Dynamo, Riak) or last-write-wins timestamps (Cassandra)
Temporary failures Sloppy quorum + hinted handoff
Permanent failures Anti-entropy with Merkle trees
Membership Gossip

4. A working model

The model below puts the pieces together: a ring with virtual nodes, preference lists, quorum writes and reads, versions, read repair, and a node failure handled with a hint.

python · try it yourself
import bisect
import hashlib

def h(s):
    return int(hashlib.md5(s.encode()).hexdigest(), 16)

class Node:
    def __init__(self, name):
        self.name, self.data, self.up, self.hints = name, {}, True, []

class KVStore:
    def __init__(self, names, n=3, r=2, w=2, vnodes=16):
        self.nodes = {name: Node(name) for name in names}
        self.n, self.r, self.w = n, r, w
        self.ring = sorted((h(f"{name}#{i}"), name) for name in names for i in range(vnodes))
        self.hashes = [p for p, _ in self.ring]

    def preference_list(self, key, extra=0):
        i, chosen = bisect.bisect_right(self.hashes, h(key)), []
        while len(chosen) < self.n + extra:
            name = self.ring[i % len(self.ring)][1]
            if name not in chosen:
                chosen.append(name)
            i += 1
        return chosen

    def put(self, key, value, version):
        acks, owners = 0, self.preference_list(key)
        stand_ins = iter(self.preference_list(key, extra=2)[self.n:])
        for name in owners:
            target = self.nodes[name]
            if not target.up:                          # sloppy quorum: next healthy node keeps a hint
                target = self.nodes[next(stand_ins)]
                target.hints.append((name, key, value, version))
            target.data[key] = (version, value)
            acks += 1
        return "ok" if acks >= self.w else "failed"

    def get(self, key):
        answers = [(name, self.nodes[name].data.get(key)) for name in self.preference_list(key)
                   if self.nodes[name].up][: self.r]
        newest = max((a for _, a in answers if a), default=None)
        for name, a in answers:                        # read repair
            if a != newest:
                self.nodes[name].data[key] = newest
        return newest

    def recover(self, name):
        self.nodes[name].up = True
        for node in self.nodes.values():               # hinted handoff
            for owner, key, value, version in [x for x in node.hints if x[0] == name]:
                self.nodes[name].data[key] = (version, value)
                node.hints.remove((owner, key, value, version))

store = KVStore(["n1", "n2", "n3", "n4", "n5"])
key = "cart:ana"
owners = store.preference_list(key)
print("preference list:", owners)

print("put v1:", store.put(key, ["lamp"], version=1))
store.nodes[owners[1]].up = False
print(f"{owners[1]} goes down; put v2:", store.put(key, ["lamp", "mug"], version=2))
holder = [n.name for n in store.nodes.values() if n.hints]
print("hint held by:", holder)
print("get:", store.get(key))
store.recover(owners[1])
print(f"{owners[1]} recovers, has:", store.nodes[owners[1]].data[key])
preference list: ['n1', 'n5', 'n3']
put v1: ok
n5 goes down; put v2: ok
hint held by: ['n2']
get: (2, ['lamp', 'mug'])
n5 recovers, has: (2, ['lamp', 'mug'])

The write still succeeded with one owner down, because another node accepted it with a hint; when the owner recovered, the hint was handed back.

5. Conflicts: vector clocks

With an always-writable store, two clients can update the same key concurrently on different replicas. Timestamps (last-write-wins) silently drop one update. Vector clocks detect the conflict instead: each version carries a counter per node that modified it.

python · try it yourself
def descends(a, b):            # does version a include everything in version b?
    return all(a.get(node, 0) >= count for node, count in b.items())

def compare(a, b):
    if a == b:
        return "equal"
    if descends(a, b):
        return "a is newer"
    if descends(b, a):
        return "b is newer"
    return "CONFLICT (concurrent)"

v1 = {"n1": 1}                          # cart = [lamp] written via n1
v2 = {"n1": 2}                          # updated again via n1
v3a = {"n1": 2, "n2": 1}                # client A adds mug via n2
v3b = {"n1": 2, "n3": 1}                # client B adds pen via n3, concurrently

print("v2 vs v1:  ", compare(v2, v1))
print("v3a vs v2: ", compare(v3a, v2))
print("v3a vs v3b:", compare(v3a, v3b))

# The application merges siblings, e.g. union of cart items, and writes a new version
merged_items = sorted({"lamp", "mug"} | {"lamp", "pen"})
merged_clock = {n: max(v3a.get(n, 0), v3b.get(n, 0)) for n in v3a.keys() | v3b.keys()}
merged_clock["n1"] += 1
print("merged:", merged_items, dict(sorted(merged_clock.items())))
v2 vs v1:   a is newer
v3a vs v2:  a is newer
v3a vs v3b: CONFLICT (concurrent)
merged: ['lamp', 'mug', 'pen'] {'n1': 3, 'n2': 1, 'n3': 1}

Dynamo returned both "siblings" to the shopping cart service, which merged them with a union. That is why a deleted item could occasionally reappear in an Amazon cart: the price of never rejecting a write.

6. Detecting divergence: Merkle trees

Replicas that missed writes (beyond what hints cover) are repaired by anti-entropy: nodes compare a Merkle tree (a tree of hashes) of each key range. Equal root hashes mean the range is identical; otherwise they descend only into differing branches, exchanging very little data.

python · try it yourself
import hashlib

def digest(s):
    return hashlib.sha256(s.encode()).hexdigest()[:8]

def merkle(items):                       # items: sorted list of "key=value"
    level = [digest(x) for x in items]
    tree = [level]
    while len(level) > 1:
        level = [digest(level[i] + (level[i + 1] if i + 1 < len(level) else "")) for i in range(0, len(level), 2)]
        tree.append(level)
    return tree

replica_a = ["k1=a", "k2=b", "k3=c", "k4=d", "k5=e", "k6=f", "k7=g", "k8=h"]
replica_b = ["k1=a", "k2=b", "k3=c", "k4=d", "k5=e", "k6=STALE", "k7=g", "k8=h"]
ta, tb = merkle(replica_a), merkle(replica_b)
print("roots equal?", ta[-1] == tb[-1])

# Walk down from the root, only into children that differ
diff = [0]
for depth in range(len(ta) - 2, -1, -1):
    diff = [c for p in diff for c in (2 * p, 2 * p + 1) if c < len(ta[depth]) and ta[depth][c] != tb[depth][c]]
    print(f"level {depth}: differing nodes {diff}")
print("keys to sync:", [replica_a[i].split("=")[0] for i in diff])
roots equal? False
level 2: differing nodes [1]
level 1: differing nodes [2]
level 0: differing nodes [5]
keys to sync: ['k6']

Each level only compared the two children of a differing node, so finding the one stale key among eight took a handful of hash comparisons instead of exchanging all eight values; with millions of keys the saving is enormous.

Trade-offs

Choice This design Alternative
CAP AP with tunable quorums CP with Raft per shard (etcd, TiKV, DynamoDB's strongly consistent reads)
Conflict handling Vector clocks + app merge Last-write-wins (simpler, can lose updates), CRDTs
Storage engine LSM tree (fast writes) B-tree (faster reads, slower writes)
Membership Gossip, decentralised A coordination service (ZooKeeper)

Test yourself

What does hinted handoff do?

  1. Deletes stale replicas
  2. Lets another node temporarily store a write for a down replica and deliver it when it recovers
  3. Elects a leader
  4. Compresses data

Two vector clocks are {n1: 2, n2: 1} and {n1: 2, n3: 1}. What is their relationship?

  1. The first is newer
  2. The second is newer
  3. They are concurrent: a conflict
  4. They are equal

Why do replicas compare Merkle trees during anti-entropy?

  1. To encrypt data
  2. To find differing key ranges by exchanging only a few hashes
  3. To elect a coordinator
  4. To balance load