Fix a Rotating Server Picker, Then Build a Hash Ring
Data Structure DesignModel answerLast updated
Find and fix the bugs in a round-robin server selector that handles pool changes and threads, then build a consistent-hash ring with virtual nodes that keeps key movement minimal.
A traffic router sends each incoming request to one server in a pool. Servers are identified by unique strings, and the pool can grow or shrink while the system is running. A single selector object is shared by every worker thread in the process.
Part 1: Repair the rotating selector
The class below should return servers in strict rotation (A, B, C, A, B, C, ...) and keep rotating sensibly when servers join or leave.
class RoundRobinBalancer:
def __init__(self, servers):
self.servers = servers
self.index = 0
def add_server(self, server):
self.servers.append(server)
def remove_server(self, server):
self.servers.remove(server)
def next_server(self):
server = self.servers[self.index]
self.index = self.index + 1
if self.index > len(self.servers):
self.index = 0
return server
Find as many defects as you can. For each, give a short call sequence that triggers it and name the root cause. Then write a corrected class. Your answer should also say what happens with an empty pool, what happens when many threads call it at once, and which server follows a removal that happens mid-rotation.
Part 2: Build a consistent-hash ring
Rotation ignores what the request is about, so the same user can hit a different server every time, which defeats per-server caches and session state. Implement a ring where a given key always resolves to the same server while the pool is unchanged. Adding or removing one server should move only about that server's share of keys, rather than reshuffling nearly everything as hash(key) % server_count does.
class ConsistentHashRing:
def add_server(self, server: str) -> None: ...
def remove_server(self, server: str) -> None: ...
def get_server(self, key: str) -> str: ...
Explain and justify:
- The data structure, and the cost of lookups and membership changes.
- Your hash function, including whether the mapping must agree across processes and restarts.
- How you keep load even across servers, and how you would give bigger servers more traffic.
- Which keys move, and where they go, when a server joins or leaves.
- How you would test both parts.
Hints
Hint 1
Trace the index by hand with a three-server pool. Check what happens when it reaches the end of the list, and what happens when you remove a server that sits before, at, or after the index.
Hint 2
Several bugs are not about the index at all: think about who owns the list passed to the constructor, what happens on an empty pool, and what two threads can do between reading and updating the index.
Hint 3
For the ring, hash each server to many points on a circle (virtual nodes), keep the points sorted, and find a key's owner with a binary search for the first point at or after the key's hash, wrapping around at the end. Avoid Python's built-in hash() for strings.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Bugs in the round-robin selector
1. Off-by-one in the wrap check (> should be >=).
With ["A","B"]: calls return A, B, and the third call raises IndexError. After serving B the index becomes 2, which equals len but is not greater than it, so no wrap happens. Root cause: valid indexes run from 0 to len - 1. Using modulo avoids this class of bug.
2. Removal does not adjust the cursor.
- Skipped server: with
[A,B,C], callnext(A, index is now 1), then remove A. The list is[B,C]and index 1 points at C, so B is skipped. When the removed element is before the cursor, the cursor must shift left by one. - Out of range: with
[A,B,C], callnexttwice (index 2), then remove C. The list has length 2 and the next call raisesIndexError. When the cursor ends up past the end, it must wrap to 0.
If the removed server is exactly at the cursor, the successor slides into that slot and is served next, which is the natural answer to "who comes next".
3. Aliasing the caller's list.
The constructor keeps a reference to the caller's list. Later add_server or remove_server calls mutate the caller's data, and outside mutations corrupt the balancer's invariants. Copy the list.
4. Empty pool.
Constructing with [] or removing the last server makes next_server raise a confusing IndexError. Decide on a contract (raise a clear error, or return None) and document it.
5. Membership edge cases.
remove_server raises ValueError for an unknown server, and add_server allows duplicates, so one server gets double weight and a single remove leaves a ghost entry. Pick a policy: here, duplicate add and unknown remove are no-ops.
6. Not thread-safe.
next_server is a read-modify-write. Two threads can both read index 1 and both return B, or both increment and skip a server. A concurrent remove between the read and the wrap check can cause an out-of-range read. All state access needs a lock.
Corrected class
import threading
class RoundRobinBalancer:
def __init__(self, servers=()):
self._servers = []
for s in servers:
if s not in self._servers:
self._servers.append(s)
self._index = 0
self._lock = threading.Lock()
def add_server(self, server):
with self._lock:
if server not in self._servers:
self._servers.append(server) # joins at the end of the rotation
def remove_server(self, server):
with self._lock:
try:
i = self._servers.index(server)
except ValueError:
return # no-op for unknown server
del self._servers[i]
if i < self._index:
self._index -= 1 # keep pointing at the same next server
if self._index >= len(self._servers):
self._index = 0 # wrap (also handles empty pool)
def next_server(self):
with self._lock:
if not self._servers:
raise LookupError("no servers available")
server = self._servers[self._index]
self._index = (self._index + 1) % len(self._servers)
return server
Costs: next_server is O(1); add and remove are O(n) because of the membership scan, which is fine for pools of tens or hundreds. For very large pools, keep a set alongside the list. Regression tests: wrap-around, remove before/at/after the cursor, remove last, empty pool, duplicate add, and a multi-threaded test checking that N calls over k servers produce exactly N/k picks each.
Part 2: Consistent-hash ring
Idea. Place hashed points on a circle. A key is hashed onto the same circle and belongs to the first server point at or after it, wrapping around. Because a server owns only the arcs just before its points, membership changes affect only neighbouring arcs.
Virtual nodes. With one point per server, arc sizes vary wildly. Give each server V points (for example 100 to 200, hashed from "server#i"). A server's share then has a relative standard deviation of roughly 1/sqrt(V), so about 7-10% at V=100-200. For heterogeneous capacity, scale V by weight (a server with twice the capacity gets twice the points).
Hash function. Do not use Python's built-in hash() on strings: it is salted per process, so different load balancers or restarts would route the same key differently. Use a stable, well-mixed hash such as MD5 (fine here, no security role) or MurmurHash, taking 64 bits.
import bisect, hashlib, threading
def _h(s: str) -> int:
return int.from_bytes(hashlib.md5(s.encode()).digest()[:8], "big")
class ConsistentHashRing:
def __init__(self, vnodes: int = 150):
self._vnodes = vnodes
self._points = [] # sorted hash values
self._owner = {} # hash value -> server
self._servers = set()
self._lock = threading.Lock()
def add_server(self, server: str) -> None:
with self._lock:
if server in self._servers:
return
self._servers.add(server)
for i in range(self._vnodes):
p = _h(f"{server}#{i}")
self._owner[p] = server # 64-bit collisions are negligible
self._points = sorted(self._owner)
def remove_server(self, server: str) -> None:
with self._lock:
if server not in self._servers:
return
self._servers.discard(server)
self._owner = {p: s for p, s in self._owner.items() if s != server}
self._points = sorted(self._owner)
def get_server(self, key: str) -> str:
with self._lock:
if not self._points:
raise LookupError("no servers available")
i = bisect.bisect_right(self._points, _h(key))
if i == len(self._points):
i = 0 # wrap around the circle
return self._owner[self._points[i]]
Complexity. Lookup is O(log(N·V)) with a binary search. Add and remove cost O(N·V log(N·V)) as written; inserting only the new points with insort gives O(V·N·V) worst case for list shifts but is cheap in practice. Memory is N·V entries, for example 100 servers × 150 = 15,000 points.
What moves.
- Adding a server takes over only arcs just before its new points, so about 1/(N+1) of keys move, and they move only to the new server. No key moves between existing servers.
- Removing a server sends its keys to the next points clockwise, spread across many surviving servers thanks to virtual nodes. All other keys stay.
- Modulo hashing, by contrast, remaps roughly N/(N+1) of keys when N changes.
Concurrency. Reads dominate, so a production version would use a read-write lock or copy-on-write: build a new immutable points array on membership change and swap the reference atomically.
Cross-process agreement. Because the hash is deterministic and points depend only on server name and index, any instance with the same server set and V routes identically. Ordering of adds does not matter except in the astronomically rare collision case.
Tests. Same key returns the same server when the pool is unchanged. With 10 servers and 100k keys, adding an 11th moves about 9% of keys, all to the new server. Per-server load stays within about 20% of the mean. Removing a server relocates only its own keys.
Common mistakes. Using a salted or weak hash, skipping virtual nodes, forgetting wraparound past the last point, using bisect_left inconsistently, and not handling an empty ring.
When to use which. Round robin suits stateless, uniform requests where even spread matters most. Consistent hashing suits cache or session affinity, where stable key placement and low churn on membership changes matter more than perfect evenness.