import bisect
import hashlib
import struct
from collections import Counter, defaultdict
from typing import List, Optional, Dict, Any, Set
class ConsistentHashRing:
"""
A consistent hashing library with virtual nodes (replicas), automatic ring updates (rebalancing on add/remove),
dynamic rebalancing based on node access loads, and hot key detection via access counters.
Key Features:
- Consistent hashing using MD5-derived 64-bit positions on a ring (0 to 2**64-1).
- Virtual nodes (replicas per physical node) for load distribution.
- Add/remove nodes triggers immediate ring rebalance (minimal key remapping).
- get_node(key) maps key to node, tracks per-key and per-node access stats.
- rebalance() dynamically adjusts virtual nodes per physical node based on access load.
- Hot key detection: get_hot_keys() returns top-k or threshold-based hot keys.
Usage Example:
ring = ConsistentHashRing(replicas=100)
ring.add_node("node1")
ring.add_node("node2")
ring.get_node("mykey") # Returns e.g. "node1", increments stats
ring.get_hot_keys(top_k=5)
ring.rebalance() # Adjust vnodes based on loads
"""
def __init__(self, replicas: int = 100):
"""
:param replicas: Initial number of virtual nodes (replicas) per physical node.
"""
self.replicas = replicas
self.ring: List[tuple[int, str]] = [] # Sorted: (hash_pos, node_id)
self.nodes: Set[str] = set()
self.node_replicas: Dict[str, List[int]] = {} # node -> its replica positions
self.key_accesses: Counter[str, int] = Counter()
self.node_accesses: Counter[str, int] = Counter()
def _hash(self, bkey: bytes) -> int:
"""64-bit hash using MD5 digest."""
h = hashlib.md5(bkey).digest()
return struct.unpack('<Q', h)[0]
def _make_key(self, node: str, replica_id: int) -> bytes:
"""Key for hashing a virtual node."""
return f"{node}:{replica_id}".encode('utf-8')
def add_node(self, node: str) -> None:
"""Add a node and its virtual replicas to the ring (rebalances automatically)."""
if node in self.nodes:
return
self.nodes.add(node)
replicas = []
for i in range(self.replicas):
bkey = self._make_key(node, i)
pos = self._hash(bkey)
bisect.insort(self.ring, (pos, node))
replicas.append(pos)
self.node_replicas[node] = replicas
def remove_node(self, node: str) -> None:
"""Remove a node and its virtual replicas from the ring (rebalances automatically)."""
if node not in self.nodes:
return
self.nodes.remove(node)
replicas = self.node_replicas.pop(node, [])
for pos in replicas:
idx = bisect.bisect_left(self.ring, (pos, node))
if idx < len(self.ring) and self.ring[idx] == (pos, node):
del self.ring[idx]
def get_node(self, key: str) -> str:
"""
Map key to the successor node on the ring.
Increments access stats for the key and node.
"""
if not self.ring:
raise ValueError("No nodes in the ring")
pos = self._hash(key.encode('utf-8'))
# Find first position strictly greater than pos (successor), wrap around if needed
idx = bisect.bisect_right(self.ring, (pos, chr(255)))
if idx == len(self.ring):
idx = 0
node = self.ring[idx][1]
self.key_accesses[key] += 1
self.node_accesses[node] += 1
return node
def rebalance(self, target_replicas: Optional[int] = None, min_replicas: int = 10, max_replicas: int = 200) -> None:
"""
Dynamic rebalancing: Adjust virtual replicas per node based on access load.
- Computes ideal replicas proportional to node's access fraction.
- Clamped between min_replicas and max_replicas.
:param target_replicas: Total replicas per node if uniform (default: self.replicas).
:param min_replicas: Minimum replicas per node.
:param max_replicas: Maximum replicas per node.
"""
if target_replicas is None:
target_replicas = self.replicas
total_access = sum(self.node_accesses.values())
if total_access == 0 or len(self.nodes) == 0:
return
total_target_vnodes = len(self.nodes) * target_replicas
new_node_replicas: Dict[str, List[int]] = {}
for node in list(self.nodes):
node_access = self.node_accesses[node]
fraction = node_access / total_access
ideal_replicas = max(1, int(fraction * total_target_vnodes))
new_replicas = max(min_replicas, min(max_replicas, ideal_replicas))
# Remove old replicas
old_replicas = self.node_replicas.get(node, [])
for pos in old_replicas:
idx = bisect.bisect_left(self.ring, (pos, node))
if idx < len(self.ring) and self.ring[idx] == (pos, node):
del self.ring[idx]
# Add new replicas
replicas = []
for i in range(new_replicas):
bkey = self._make_key(node, i)
pos = self._hash(bkey)
bisect.insort(self.ring, (pos, node))
replicas.append(pos)
new_node_replicas[node] = replicas
self.node_replicas = new_node_replicas
def get_hot_keys(self, top_k: Optional[int] = 10, threshold: Optional[int] = None) -> List[str]:
"""
Detect hot keys.
:param top_k: Return top-k most accessed keys (if threshold is None).
:param threshold: Return keys with accesses >= threshold (ignores top_k).
:return: List of hot keys (sorted by access desc if top_k).
"""
if threshold is not None:
return [k for k, count in self.key_accesses.items() if count >= threshold]
return [k for k, _ in self.key_accesses.most_common(top_k)]
def get_node_loads(self) -> Dict[str, int]:
"""Get current access counts per node."""
return dict(self.node_accesses)
def get_replicas_per_node(self) -> Dict[str, int]:
"""Get current number of virtual replicas per node."""
return {node: len(repls) for node, repls in self.node_replicas.items()}
def reset_stats(self) -> None:
"""Reset access statistics."""
self.key_accesses.clear()
self.node_accesses.clear()
def get_stats(self) -> Dict[str, Any]:
"""Full stats snapshot."""
return {
'nodes': list(self.nodes),
'total_keys_accessed': len(self.key_accesses),
'total_node_accesses': sum(self.node_accesses.values()),
'node_loads': dict(self.node_accesses),
'replicas_per_node': self.get_replicas_per_node(),
}
Design Overview
Consistent Hashing Core: Keys and virtual nodes are hashed to 64-bit positions on a circle. get_node(key) uses binary search (bisect) for O(log N) lookup (N = total vnodes). Adding/removing nodes updates the sorted ring efficiently.
Virtual Nodes (Replicas): Each physical node gets multiple points on the ring for even distribution (~1/max(load skew)).
Rebalancing:
Static: Automatic on add_node/remove_node (only affected keys remap).
Dynamic: rebalance() adjusts vnodes proportional to node access load (e.g., hot nodes get more vnodes to spread load). Call periodically (e.g., every 5-10min in production).
Hot Key Detection: get_node tracks accesses with Counter. get_hot_keys supports top-k or absolute threshold. Memory scales with unique keys (use sampling/LFU cache in prod for millions).
Performance: O(log V) per lookup (V = total vnodes, e.g., 100 nodes * 100 = 10k → log2(10k)~14). Ring ops amortized O(R log V) (R=replicas).
Extensions: Integrate with actual storage (e.g., migrate keys on remap). For prod, add persistence, gossip for multi-instance rings, or Count-Min Sketch for scalable hot keys.
Example Usage
python
ring = ConsistentHashRing(replicas=50)
ring.add_node("server-1")
ring.add_node("server-2")
ring.add_node("server-3")
# Simulate accesses
for key in ["user:1", "user:1", "user:2", "hot:key", "hot:key", "hot:key", "user:1"]:
node = ring.get_node(key)
print(f"{key} -> {node}")
print("Hot keys (top 3):", ring.get_hot_keys(top_k=3))
print("Node loads:", ring.get_node_loads())
print("Replicas per node:", ring.get_replicas_per_node())
ring.rebalance() # Adjust based on loads
print("After rebalance:", ring.get_replicas_per_node())
print("Full stats:", ring.get_stats())