805. Route requests to replicas with a consistent hash ring
Why it matters Prefix-aware LLM routers and distributed KV caches use consistent hashing so scaling a fleet does not cold-start every cache.
When a model server is added or removed, plain hash(key) % n remaps almost every key, which wipes out every replica's prompt cache. A consistent hash ring moves only about 1/n of the keys.
Write ring_route(nodes, keys, vnodes). Hash a string with h(s) = int(hashlib.md5(s.encode()).hexdigest(), 16). Put vnodes points on the ring for each node at h(f"{node}#{v}") for v = 0..vnodes-1. A key goes to the node owning the first point with hash >= h(key), wrapping around to the smallest point if none. Ties between points cannot happen with md5 for these inputs.
Return a dict key -> node.
def ring_route(nodes, keys, vnodes)Example 1
Input: ring_route(['A', 'B'], ['x', 'y', 'z'], 3)
Output: {'x': 'B', 'y': 'B', 'z': 'B'}
Example 2
Input: nodes = ['gpu0'], keys = ['a', 'b'], vnodes = 1
Output: {'a': 'gpu0', 'b': 'gpu0'}
Constraints
- Python 3 standard library. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Build a sorted list of (hash, node) for all virtual nodes.
Hint 2
Use bisect to find the first point at or after the key's hash.
Hint 3
Wrap with modulo when the key hashes past the last point.
Common mistakes
- Using
hash(key)% n, which remaps most keys when n changes. - Forgetting the wrap-around, which raises an IndexError.
Understand the idea
Nodes and keys are hashed onto the same circle. A key belongs to the next node point clockwise. Adding a node only steals keys that land just before its points; every other key keeps its owner. Virtual nodes spread each server over many points so load evens out.
with a single node every key maps to it.
sort node points; owner = first point >= h(key), wrapping to index 0