Build a Weighted Consistent Hash Ring
Data Structure DesignModel answerLast updated
Design and code a hash ring that maps keys to servers with virtual nodes, supporting weighted capacity and minimal key movement on topology changes.
You're building a distributed cache router. Design a consistent hash ring that assigns keys to servers while minimizing how many keys get reassigned when servers are added or removed.
Implement a ConsistentHashRing class with these methods:
add_node(node_id, weight=1.0)— register a server with the given capacity weightremove_node(node_id)— unregister a server; returnTrueif it existed,Falseotherwiseget_node(key)— return which server owns this key, orNoneif the ring is empty
Requirements:
- Use virtual nodes (vnodes) to distribute load evenly. A server with weight
wshould receive roughlyw / total_weightof all keys. - When a server joins or leaves, only keys directly affected by that change should move—keys should not shift between unchanged servers.
- Handle hash collisions deterministically so all clients agree on ownership.
- Support re-weighting: calling
add_nodeon an existing server updates its weight.
Explain your design choices:
- Which hash function and why
- How you handle collisions
- How you choose the number of virtual nodes
- Time and space complexity
- How this compares to simple modulo hashing (
key % num_servers)
Hints
Hint 1
Think about representing the ring as a sorted structure where both keys and servers live in the same hash space.
Hint 2
Virtual nodes are copies of the same physical server placed at different hash positions—more copies mean smoother distribution.
Hint 3
A deterministic tie-breaker (like including the node ID in the sort key) ensures all clients see the same ring even if hash values collide.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core idea: map both keys and servers onto a shared circular space using the same hash function. To find a key's owner, hash the key and walk clockwise to the first server you encounter, wrapping around if needed.
Virtual nodes solve the imbalance problem. A single hash point per server creates wildly uneven arc lengths. Instead, each physical server gets many virtual replicas—say 160—each placed at hash(node_id + "#" + replica_number). A server with weight 2.0 gets twice as many replicas, so it captures twice as many keys on average.
Data structure: maintain a sorted list of (hash_value, node_id, replica_index) tuples. Lookup becomes:
- Hash the key to a 64-bit integer.
- Binary search for the first tuple whose hash is ≥ the key's hash.
- If no such tuple exists (key hash is larger than all server hashes), wrap to index 0.
Return the node_id from that tuple.
Design Decisions
Hash Function
Use a stable, non-cryptographic, well-distributed hash that produces the same output across processes and languages. Python's built-in hash() is seeded randomly per interpreter, so two clients would build incompatible rings.
Good choices:
- BLAKE2b truncated to 64 bits (fast, uniformly distributed, in stdlib)
- xxHash or MurmurHash3 (even faster, excellent distribution)
- MD5 (legacy but deterministic; overkill but acceptable)
64 bits makes accidental collisions negligible: with 100,000 vnodes, collision probability is around 10^10 / 2^64 ≈ 5 × 10^-10.
Collision Handling
Store each ring entry as a tuple (hash, node_id, replica_index), not as a dictionary keyed by hash alone. When two vnodes produce the same hash:
- Both stay on the ring.
- Python's tuple comparison breaks ties lexicographically by
node_id, thenreplica_index. - This is deterministic and independent of insertion order, so all clients agree.
Alternative approaches like linear probing with a salt work but create subtle disagreements if clients add nodes in different orders.
Number of Virtual Nodes
With V vnodes per physical node, load imbalance (relative standard deviation) is approximately 1 / sqrt(V):
V = 100: ~10% imbalanceV = 160: ~8% imbalanceV = 1000: ~3% imbalance
For a 1,000-node cluster with 160 vnodes each, the ring holds 160,000 points—a few MB of memory, which is trivial. Choose V based on how much imbalance you can tolerate. Scale by weight: a node with weight 2.5 gets round(160 × 2.5) = 400 vnodes.
Minimal Remapping
Adding a node: its vnodes insert into existing arcs. Only keys whose hash now falls between a new vnode and the previous vnode in that arc move—and they move to the new node. On average, 1/(N+1) of keys shift.
Removing a node: only keys owned by the removed node move, each to the next vnode clockwise. Again, roughly 1/N of keys.
Contrast with modulo hashing (hash(key) % N):
| Property | Modulo | Consistent Hashing |
|---|---|---|
| Lookup | O(1), no state | O(log M), needs ring |
| Keys moved when N→N+1 | ~N/(N+1) (almost all) | ~1/(N+1) |
| Use case | Static clusters | Dynamic clusters, caches |
Modulo hashing is simpler but causes cache stampedes and massive data migration on topology changes.
Complexity
Let N = number of physical nodes, V = vnodes per node, M = N × V = total ring size.
| Operation | Time | Space |
|---|---|---|
get_node(key) | O(log M) | O(1) |
add_node(node_id, w) | O(M + V log V) | O(M) |
remove_node(node_id) | O(M) | O(M) |
For high-frequency membership changes, use a balanced tree (e.g., sortedcontainers.SortedList) to bring add/remove to O(V log M). In practice, membership changes are rare compared to lookups, so rebuilding the list is fine.
Edge Cases
- Empty ring: return
None. - Wrap-around: if the key's hash exceeds all vnode hashes, return the node at index 0.
- Zero or negative weight: raise an error.
- Re-weighting: treat
add_nodeon an existing node as remove-then-add. Keys shift only by the weight delta. - Removing nonexistent node: return
False, leave ring unchanged. - Non-string keys/IDs: convert with
str()before hashing so clients hash identical bytes.
Implementation
import bisect
import hashlib
import heapq
from typing import Dict, List, Optional, Tuple
class ConsistentHashRing:
def __init__(self, base_vnodes: int = 160):
if base_vnodes < 1:
raise ValueError("base_vnodes must be >= 1")
self._base = base_vnodes
self._ring: List[Tuple[int, str, int]] = []
self._weights: Dict[str, float] = {}
@staticmethod
def _hash(value: str) -> int:
digest = hashlib.blake2b(value.encode("utf-8"), digest_size=8).digest()
return int.from_bytes(digest, "big")
def _vnode_count(self, weight: float) -> int:
return max(1, round(self._base * weight))
def add_node(self, node_id: str, weight: float = 1.0) -> None:
if weight <= 0:
raise ValueError("weight must be positive")
node_id = str(node_id)
if node_id in self._weights:
self.remove_node(node_id)
count = self._vnode_count(weight)
new_points = sorted(
(self._hash(f"{node_id}#{i}"), node_id, i) for i in range(count)
)
self._ring = list(heapq.merge(self._ring, new_points))
self._weights[node_id] = weight
def remove_node(self, node_id: str) -> bool:
node_id = str(node_id)
if node_id not in self._weights:
return False
self._ring = [p for p in self._ring if p[1] != node_id]
del self._weights[node_id]
return True
def get_node(self, key) -> Optional[str]:
if not self._ring:
return None
h = self._hash(str(key))
# bisect_left with (h,) finds first tuple >= (h, ...)
idx = bisect.bisect_left(self._ring, (h,))
if idx == len(self._ring):
idx = 0 # wrap around
return self._ring[idx][1]
Common Mistakes
- Using Python's
hash()built-in — it's randomized per process, breaking cross-client agreement. - Storing vnodes in a dict keyed by hash — loses collision information; two vnodes with the same hash overwrite each other.
- Not wrapping around — forgetting that keys hashing beyond the last vnode must map to the first.
- Ignoring weights — treating all nodes equally when hardware capacity varies.
- Off-by-one in binary search — using
bisect_rightinstead ofbisect_left, or not handling the wrap case.
A strong answer walks through the circular lookup logic, justifies the vnode count with a concrete number, and contrasts the remapping behavior with modulo hashing using a small example (e.g., "with 3 nodes and 1,000 keys, adding a 4th node moves ~250 keys, not ~750").