Consistent Hash Ring With Virtual Nodes
Build a consistent hash ring with virtual nodes for distributed cache routing.
Code
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
SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Webhook HMAC Signature VerifierVerify and generate HMAC-SHA256 webhook signatures for Stripe, GitHub, and raw hex headers locally using Web Crypto and constant-time comparison.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.