Skip to main content
🔒 Preview mode. The first 15 Foundations lessons are free; this one is Pro. Start a 7-day trial to unlock the editor, AI hints and the rest of the curriculum. Card required, cancel any time in Dashboard.Start 7-day trial →
← CoursesSystem Design for Python JuniorsModule 2 · Scalability & CachingConsistent hashingpredict17 / 105
+100 XP
Task
📝 **Question:** Predict the exact line the script prints — `<naive_moved> <consistent_moved>` — when 10 000 keys are remapped from 8 nodes to 9. 📋 Pick the right answer. 💡 **Hint:** Re-read the theory above if unsure.
Predict the output

Read the code carefully

import hashlib

KEYS = [f"key:{i}" for i in range(10_000)]

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

def naive_assign(keys, n):
    return {k: h(k) % n for k in keys}

# Ring with VNODES virtual nodes per server keeps the distribution even.
VNODES = 150

def ring(nodes):
    points = []
    for n in nodes:
        for v in range(VNODES):
            points.append((h(f"{n}#{v}"), n))
    points.sort()
    return points

def consistent_assign(keys, nodes):
    points = ring(nodes)
    out = {}
    for k in keys:
        hk = h(k)
        # walk clockwise to the first ring point >= hk; wrap to points[0] otherwise
        lo, hi = 0, len(points)
        while lo < hi:
            mid = (lo + hi) // 2
            if points[mid][0] < hk: lo = mid + 1
            else: hi = mid
        out[k] = points[lo % len(points)][1]
    return out

before_nodes = [f"s{i}" for i in range(8)]
after_nodes  = [f"s{i}" for i in range(9)]

n_before = naive_assign(KEYS, 8)
n_after  = naive_assign(KEYS, 9)
c_before = consistent_assign(KEYS, before_nodes)
c_after  = consistent_assign(KEYS, after_nodes)

naive_moved      = sum(1 for k in KEYS if n_before[k] != n_after[k])
consistent_moved = sum(1 for k in KEYS if c_before[k] != c_after[k])
print(naive_moved, consistent_moved)

What will the program print? Write here:

💬 Discussion

Be the first to ask a question or share a tip.
Sign in to join the discussion. Reading is free.
Loading discussion…