Build a Weighted Hash Ring for Sharding Keys Across Servers
Data Structure DesignModel answerLast updated
Design a hash ring with weighted virtual nodes that assigns keys to servers, supports adding and removing servers with little key movement, and handles collisions and concurrency.
Weighted Hash Ring
You are building the routing layer of a sharded storage service. Design a class that decides which backend server owns each key, so that when servers join or leave, as few keys as possible change owners.
Operations
add_node(node_id, weight)registers a physical server. Itsweightcontrols how many virtual nodes (points on the ring) it receives, so a heavier server owns a larger share of the key space.remove_node(node_id)deletes a server together with every virtual node it contributed.get_node(key)returns thenode_idresponsible forkey.
Requirements
- Map both servers and keys into a fixed integer space such as
0 .. 2^32 - 1using a hash that gives the same result in every process and across restarts. get_nodemust run in O(log V) time, where V is the total number of virtual nodes.- Every virtual node must be traceable back to the physical server that owns it.
Example
ring = ConsistentHashRing()
ring.add_node("Server_A", weight=2)
# Server_A might occupy positions such as [100, 500] on the ring
ring.get_node("order_123") # -> "Server_A"
Edge cases you must address
- Two virtual nodes hash to the same position. Define a deterministic tie-break.
- The ring contains no servers.
- Many threads call
get_nodewhile others add or remove servers.
What to deliver
Explain your data structure and ownership rule, then give working code. State the complexity of each operation, justify why few keys move on membership changes, and describe how you handle the edge cases above. Be ready to discuss how you would extend the design to support replication and to react to overloaded servers.
Hints
Hint 1
Picture the hash space as a circle. A key belongs to the first virtual node found at or after its hash when moving clockwise, and if none exists you wrap to the smallest position.
Hint 2
Keep one sorted list of (position, node_id, replica_index) entries. Storing the physical node_id inside each entry removes the need for a second lookup table, and tuple ordering gives you a deterministic tie-break for equal positions.
Hint 3
Avoid Python's built-in hash() because it is randomized per process. For concurrency, think copy-on-write: writers hold a lock and publish a freshly built list, while readers take one reference to the current list and never lock.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
Treat the hash space [0, 2^32 - 1] as a circle. Each physical server is placed at many points (virtual nodes). A key is hashed onto the same circle and is owned by its successor: the first virtual node at or clockwise after the key's position. If the key hashes beyond the last virtual node, it wraps to the first entry.
Compared with hash(key) % N, this means a membership change only affects the arcs next to the added or removed points, so roughly K/N of K keys move instead of nearly all of them.
Design choices
- Sorted list of tuples
(position, node_id, replica_index). A binary search finds the successor in O(log V). - Owner embedded in each entry. The virtual-to-physical mapping is the tuple itself, so there is no separate table that can drift out of sync.
- Weights. A server of weight
wreceivesw * vnodes_per_weightvirtual nodes, each hashed from a label like"Server_A#3". In practice 100-200 vnodes per unit of weight smooth out the arc sizes; with only a few points per server the load is visibly uneven. - Stable hash. MD5 truncated to 32 bits is deterministic everywhere. Python's
hash()is salted per process, so two routers would disagree on ownership.
Why it is correct
- Determinism. Same hash and same membership means the same sorted list, so every process computes the same owner.
- Collisions. Both colliding entries stay in the list. Tuple ordering sorts them by
(position, node_id, replica_index), so the lexicographically smallestnode_idwins at that point. The result does not depend on insertion order, and removing one of the colliding servers hands the point to the other with no probing state to undo. - Lookup trick.
bisect_left(ring, (h,))works because a one-element tuple sorts before any(h, id, i). It returns the first entry with position>= h, which is exactly the successor. A key landing exactly on a virtual node belongs to that node.
Thread safety
Reads dominate writes, so use copy-on-write:
- Writers acquire a lock, build a new sorted list, and publish it with a single reference assignment.
- Readers read
self._ringonce and operate on that immutable snapshot without any lock.
A reader therefore sees either the complete old ring or the complete new one, never a partial update. Reads never block, and writers are serialized.
Complexity
| Operation | Time | Notes |
|---|---|---|
get_node | O(log V) plus hashing the key | binary search |
add_node | O(V log V) | rebuild and sort (near-linear on mostly sorted data) |
remove_node | O(V) | filter |
| Space | O(V) |
Rebuilding on write is fine because membership changes are rare. If they were frequent, a balanced tree or SortedList would give O(w log V) writes, at the price of readers needing a lock.
Code
import bisect
import hashlib
import threading
from typing import Dict, List, Optional, Tuple
Entry = Tuple[int, str, int] # (position, physical node_id, replica index)
def _hash(s: str) -> int:
return int.from_bytes(hashlib.md5(s.encode("utf-8")).digest()[:4], "big")
class ConsistentHashRing:
def __init__(self, vnodes_per_weight: int = 1):
if vnodes_per_weight < 1:
raise ValueError("vnodes_per_weight must be >= 1")
self._vpw = vnodes_per_weight
self._ring: List[Entry] = [] # immutable snapshot
self._weights: Dict[str, int] = {}
self._lock = threading.Lock()
def add_node(self, node_id: str, weight: int = 1) -> None:
if weight < 1:
raise ValueError("weight must be >= 1")
with self._lock:
kept = [e for e in self._ring if e[1] != node_id] # re-add = update
new = [(_hash(f"{node_id}#{i}"), node_id, i)
for i in range(weight * self._vpw)]
self._ring = sorted(kept + new) # atomic publish
self._weights[node_id] = weight
def remove_node(self, node_id: str) -> bool:
with self._lock:
if node_id not in self._weights:
return False
self._ring = [e for e in self._ring if e[1] != node_id]
del self._weights[node_id]
return True
def get_node(self, key: str) -> Optional[str]:
ring = self._ring # single snapshot read
if not ring:
return None
idx = bisect.bisect_left(ring, (_hash(key),))
if idx == len(ring):
idx = 0 # wrap around
return ring[idx][1]
def get_nodes(self, key: str, n: int) -> List[str]:
ring = self._ring
if not ring or n < 1:
return []
start = bisect.bisect_left(ring, (_hash(key),))
out: List[str] = []
for step in range(len(ring)):
node = ring[(start + step) % len(ring)][1]
if node not in out:
out.append(node)
if len(out) == n:
break
return out
Edge-case behavior
- Empty ring:
get_nodereturnsNone. - Wraparound: a hash past the last entry maps to
ring[0]. - Re-adding a node: treated as a weight change; old virtual nodes are replaced, never duplicated.
- Removing an unknown node: no-op returning
False. - Weight below 1: raises
ValueError.
Follow-ups
Replication. Walk clockwise from the key's successor and collect the first N distinct physical servers, skipping virtual nodes of hosts already chosen (get_nodes). Without the skip, two replicas could sit on one machine. Production systems also avoid placing replicas in the same rack or zone.
Rebalancing a hot server. Weight is the control knob: lower the hot server's weight so its arcs pass to successors, and raise weights on underused servers. Avoid oscillation by changing weights in small steps, using smoothed load metrics, and rate-limiting adjustments. If the load comes from a single hot key rather than a hot arc, weights will not help; use key-level replication or caching instead.
Common mistakes
- Using a per-process salted hash, so nodes disagree on placement.
- Too few virtual nodes, which produces skewed load.
- Forgetting wraparound or the empty-ring case.
- Resolving collisions by insertion order, which makes ownership nondeterministic.
- Letting readers see a half-built ring by mutating the list in place.