Skip to solution
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.

Nudge consolestandby

Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.

03

Study the solution

Step 1: Outline use cases and constraints

Gather requirements and scope the problem. Ask questions to clarify use cases and constraints. Discuss assumptions.

Use cases

We'll scope the problem to handle only the following use cases

  • User performs core action described in How would you design a dis

Solution ready — 2 min read

Classified // press E to declassify

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.

Transmission complete // awaiting log

KEEP THE
STREAK ALIVE.

Dossier 79 of 99 decoded in the System Design track. One more won't hurt.

Back to track