Neural Mastery
← Practice
Consistent Hash Ring Lookupeasy

Consistent Hash Ring Lookup

easy ML Systems & MLOps 15–20 min

NumPy allowed · plain Python earns 10 bonus points

Implement consistent hash ring lookup, the core operation behind distributed caching and load balancing.

Task

Hash key using hash(key) % 360 and find the first node at or after that position in the sorted ring list. Wrap around if needed. Raise ValueError if empty.

Function Signature

consistent_hash_lookup(key: str, ring: list[tuple[int, str]]) -> str

Examples

Example 1: Test 1
Input: key = 'user:123' ring = [[10, 'node_a'], [100, 'node_b'], [200, 'node_c']]
Output: 'node_a'
Example 2: Test 2
Input: key = 'user:999' ring = [[10, 'node_a'], [100, 'node_b']]
Output: 'node_a'
Example 3: Test 3
Input: key = 'test' ring = []
Output: Raises ValueError

Constraints

  • Ring is sorted
  • Wrap around
  • Raise ValueError
Python3Saved ✓
def consistent_hash_lookup(key: str, ring: list[tuple[int, str]]) -> str:
pass

Case 1: Test 1
Input: key = 'user:123' ring = [[10, 'node_a'], [100, 'node_b'], [200, 'node_c']]
Expected: 'node_a'
Case 2: Test 2
Input: key = 'user:999' ring = [[10, 'node_a'], [100, 'node_b']]
Expected: 'node_a'
Case 3: Test 3
Input: key = 'test' ring = []
Expected: Raises ValueError