hardSystem Design

How would you design a distributed key-value store?

219 views
01

Understand the problem

Outline a KV store.

key-value-store
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

Pick N replica nodes for a key
Run Playground
import hashlib, bisect

class Ring:                          # consistent hashing (see that question)
    def __init__(self, nodes, vnodes=50):
        self.ring, self.points = {}, []
        for n in nodes:
            for i in range(vnodes):
                h = int(hashlib.md5((n + str(i)).encode()).hexdigest(), 16)
                self.ring[h] = n
                bisect.insort(self.points, h)

    def nodes_for(self, key, n):     # key's node + next distinct ones = N replicas
        h = int(hashlib.md5(key.encode()).hexdigest(), 16)
        i = bisect.bisect(self.points, h) % len(self.points)
        out, seen = [], set()
        while len(out) < n:
            node = self.ring[self.points[i % len(self.points)]]
            if node not in seen:
                seen.add(node)
                out.append(node)
            i += 1
        return out

ring = Ring(["A", "B", "C", "D"])
print("user:1 ->", ring.nodes_for("user:1", n=3))   # 3 replicas
print("cart:9 ->", ring.nodes_for("cart:9", n=3))
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.