Consistent Hash Ring With Virtual Nodes

Build a consistent hash ring with virtual nodes for distributed cache routing.

PythonData Fetching

Code

pythonsnippet
20 lines
import hashlib

class ConsistentHashRing:
    def __init__(self, nodes, replicas=150):
        self.ring = {}
        for node in nodes:
            for i in range(replicas):
                key = self._hash(f'{node}:{i}')
                self.ring[key] = node
        self.sorted_keys = sorted(self.ring.keys())
    def _hash(self, s):
        return int(hashlib.md5(s.encode()).hexdigest(), 16)
    def get(self, key):
        if not self.sorted_keys:
            return None
        h = self._hash(str(key))
        for slot in self.sorted_keys:
            if slot >= h:
                return self.ring[slot]
        return self.ring[self.sorted_keys[0]]

What the code does

Consistent Hash Ring With Virtual Nodes keeps everything in the class ConsistentHashRing and the functions __init__, _hash and get.

Iteration happens inside for node in nodes — everything outside it runs once.

Using it

The main signature reads def get(self, key)

Import get from the file and call it — the rest of the code is implementation detail.

Key statements

def __init__(self, nodes, replicas=150):
    self.ring = {}
    for node in nodes:
        for i in range(replicas):
            key = self._hash(f'{node}:{i}')
            self.ring[key] = node
    self.sorted_keys = sorted(self.ring.keys())
def _hash(self, s):
    return int(hashlib.md5(s.encode()).hexdigest(), 16)
def get(self, key):
    if not self.sorted_keys:
        return None
    h = self._hash(str(key))
    for slot in self.sorted_keys:
        if slot >= h:
            return self.ring[slot]
    return self.ring[self.sorted_keys[0]]

Interactive Tools for This Topic

FAQ

Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. The file defines `__init__`, `_hash`, `get` at load time.