Here is a request to design a consistent hashing library.
The key features required are:
1. Consistent Hashing: The core distribution mechanism.
2. Rebalancing: Adding/removing nodes and handling data movement.
3. Hot Key Detection: Identifying keys that are accessed disproportionately often.
**Step 1: Core Components**
* **Hash Function:** Needs to be fast and distribute well. (e.g., MD5, SHA-1, or MurmurHash). Let's use a template or interface for flexibility.
* **Hash Ring:** A circular space (usually $0$ to $2^{32}-1$ or $2^{64}-1$).
* **Virtual Nodes (VNodes):** Crucial for load balancing. A physical server maps to multiple points on the ring.
**Step 2: Rebalancing Strategy**
* *Scenario:* Node joins or leaves.
* *Impact:* Only a subset of keys should move. In standard consistent hashing, a new node takes over the range from its predecessor.
* *Movement:* The library needs to identify which keys move where.
* *Library vs. Service:* As a *library*, I shouldn't necessarily handle the network transfer of data myself (too specific), but I should provide the *instructions* on what needs to move. I will provide a "diff" or "migration plan" interface.
**Step 3: Hot Key Detection**
* *Mechanism:* We need to track access frequency.
* *Placement:* It can be done at the client side (if the library is a client) or server side.
* *Techniques:*
* *Count Min Sketch (CMS):* Good for heavy hitters, memory efficient, probabilistic.
* *Sliding Window:* To detect recent spikes (e.g., last 10 seconds).
* *Top-K:* A min-heap to keep track of the current hottest keys.
* *Thread Safety:* If this is a library, counters need to be atomic or use lock-free structures to avoid performance bottlenecks.
**Step 4: API Design (C++ or Java style?)**
Let's go with a generic pseudo-code/Python-like or C++ structure for clarity and performance implications. I will choose Python for readability but discuss concurrency.
* `add_node(node_id)`
* `remove_node(node_id)`
* `get_node(key)` -> This triggers the hot key counter.
* `get_hot_keys(threshold)` -> Returns list of hot keys.
**Step 5: Refinement & Advanced Features**
* *Consistent Hashing with Bounded Loads:* A Google paper improvement. It ensures that no node gets overloaded even if the hash function isn't perfect. This is a great addition for "Rebalancing".
* *Concurrency:* The ring needs read/write locks.
* *Hot Key mitigation:* The library detects, but what does the user do? Maybe the library can suggest "replication" or "caching"? I'll stick to detection as requested, but mention mitigation.
**Step 6: Structuring the Response**
1. **High-Level Architecture:** Explain the ring, vnodes, and the monitoring component.
2. **Data Structures:**
* Sorted Map / BST for the Ring.
* Atomic counters or Sketches for Hot Keys.
3. **Detailed Implementation:**
* The Ring (with Virtual Nodes).
* The Hot Key Tracker (using Sliding Window + Top-K).
4. **Rebalancing Logic:** How to calculate the diff.
5. **Code Example (Python):** A working prototype skeleton.
6. **Scaling & Optimization:** Thread safety, network considerations.
*Self-Correction during thought process:*
*Initial thought:* Just use a `Counter` dictionary for hot keys.
*Correction:* `Counter` grows infinitely. Use Count-Min Sketch or a Top-K structure (Space-Saving algorithm) to bound memory.
*Refinement on Rebalancing:* Standard consistent hashing might still lead to slight imbalance. I should mention "Virtual Nodes" heavily as the solution to this.
**Drafting the Code Structure:**
* Class `ConsistentHash`
* Method `add_node(id, weight)`
* Method `get_node(key)` -> updates metrics.
* Class `HotKeyDetector`
* Uses `collections.deque` for sliding window or `heapq` for Top K.
Let's refine the "Rebalancing" part. The prompt asks for a library *with* rebalancing.
Does it mean the library *moves* the data?
Usually, a hashing library provides the map. The "Rebalancing" feature usually means:
1. Updating the topology (adding nodes).
2. Exposing the changes in ownership (so the caller can move data).
I will implement a method `compute_migration_plan(old_ring, new_ring)`.
Let's write the solution.</think>
This design outlines a production-grade Consistent Hashing Library written in Python (as a readable pseudo-code implementation). It addresses three core requirements:
- Elastic Scalability: Adding/removing nodes with minimal data movement.
- Rebalancing: Efficient calculation of data migration paths.
- Observability: Real-time detection of "Hot Keys" (skewed access patterns).
1. Architecture Overview
The library consists of three interacting layers:
- The Hash Ring (Core): Implements the Consistent Hashing algorithm with Virtual Nodes (VNodes) to ensure even distribution of keys.
- The Migration Planner (Rebalancing): Compares ring states to generate efficient data movement instructions.
- The Tracker (Hot Key Detection): A probabilistic data structure layer (using Sliding Window Counters) to identify high-traffic keys without consuming excessive memory.
2. Data Structures
A. Hash Ring with VNodes
To prevent data skew (where one server gets 80% of the data), we use Virtual Nodes. One physical server maps to multiple points on the ring.
- Structure: A Sorted List (or Binary Search Tree) of hash values.
- VNode Count: Typically 100-200 per physical node.
B. Hot Key Tracker
We cannot store a counter for every key (memory explosion). We will use a Sliding Window Top-K approach using a CountMinSketch-like structure or a simple LFU cache with a decay mechanism. For this design, we will use a Decaying Counter Map.
3. Implementation
import hashlib
import bisect
import time
from collections import defaultdict, deque
import threading
class ConsistentHashRing:
def __init__(self, replicas=100):
"""
:param replicas: Number of virtual nodes per physical node
"""
self.replicas = replicas
self.ring = dict() # Maps hash_value -> Node ID
self.sorted_keys = [] # Sorted list of hash values for binary search
self.nodes = set() # Registered physical nodes
# Hot Key Detection State
self.hot_key_window = defaultdict(int) # Counter for current window
self.hot_key_history = deque(maxlen=10) # History of hot keys
self.hot_threshold = 100 # Accesses per second to qualify as 'hot'
self.window_start_time = time.time()
self.window_size_sec = 5
self.lock = threading.RLock()
# --- 1. Hashing Logic ---
def _hash(self, key):
"""Generates an integer hash for a given key/string."""
return int(hashlib.md5(key.encode()).hexdigest(), 16)
def _get_node_position(self, node_id, replica_idx):
"""Generates a unique point on the ring for a virtual node."""
return self._hash(f"{node_id}:{replica_idx}")
# --- 2. Node Management (Rebalancing) ---
def add_node(self, node_id):
"""Adds a physical node and its virtual nodes to the ring."""
with self.lock:
if node_id in self.nodes:
return
self.nodes.add(node_id)
for i in range(self.replicas):
pos = self._get_node_position(node_id, i)
self.ring[pos] = node_id
bisect.insort(self.sorted_keys, pos)
def remove_node(self, node_id):
"""Removes a physical node from the ring."""
with self.lock:
if node_id not in self.nodes:
return
self.nodes.remove(node_id)
for i in range(self.replicas):
pos = self._get_node_position(node_id, i)
del self.ring[pos]
self.sorted_keys.remove(pos)
# --- 3. Key Lookup & Hot Key Tracking ---
def get_node(self, key):
"""
Returns the node responsible for the key.
Also updates metrics for Hot Key detection.
"""
if not self.ring:
return None
# 1. Calculate Key Position
pos = self._hash(key)
# 2. Binary Search for the nearest node clockwise
idx = bisect.bisect_right(self.sorted_keys, pos)
# Wrap around to the first node if past the end
if idx >= len(self.sorted_keys):
idx = 0
target_node = self.ring[self.sorted_keys[idx]]
# 3. Update Hot Key Stats (Asynchronous/Fire-and-forget logic recommended in prod)
self._record_access(key)
return target_node
# --- 4. Hot Key Detection Logic ---
def _record_access(self, key):
"""
Tracks key access frequency using a Sliding Window.
"""
current_time = time.time()
# Check if we need to rotate the window
if current_time - self.window_start_time > self.window_size_sec:
# Identify hot keys from the expiring window
self._process_hot_keys()
# Reset window
self.hot_key_window.clear()
self.window_start_time = current_time
# Increment counter
self.hot_key_window[key] += 1
def _process_hot_keys(self):
"""Scans the current window for keys exceeding the threshold."""
hot_keys_found = []
for key, count in self.hot_key_window.items():
# Normalize count to requests per second
rps = count / self.window_size_sec
if rps > self.hot_threshold:
hot_keys_found.append((key, rps))
if hot_keys_found:
# Store in history or trigger alert
self.hot_key_history.append(hot_keys_found)
# In a real system, emit an event here:
# EventBus.emit("HOT_KEY_DETECTED", hot_keys_found)
def get_hot_keys(self):
"""Returns the list of recently detected hot keys."""
return list(self.hot_key_history)
# --- 5. Rebalancing / Migration Plan ---
def get_migration_plan(self, new_node_id):
"""
Calculates which keys need to move if we were to add 'new_node_id'.
Returns a dictionary: { source_node: [list of key_ranges] }
"""
# This is a simulation. In a real DB, you would iterate actual keys.
# Here we determine which VNodes (ranges) are stolen.
plan = defaultdict(list)
for i in range(self.replicas):
new_pos = self._get_node_position(new_node_id, i)
# Find who owns this position currently
idx = bisect.bisect_right(self.sorted_keys, new_pos)
if idx >= len(self.sorted_keys): idx = 0
current_owner = self.ring[self.sorted_keys[idx]]
# The new node will "steal" this range from current_owner
# We define the range start (previous position in ring)
prev_idx = idx - 1
if prev_idx < 0: prev_idx = len(self.sorted_keys) - 1
range_start = self.sorted_keys[prev_idx]
plan[current_owner].append((range_start, new_pos))
return plan
4. Detailed Design Logic
A. Rebalancing Strategy
When a new node joins a cluster, standard hashing requires remapping N/M keys (where N is total keys, M is nodes). Consistent hashing reduces this to K/N (where K is keys, is nodes).
In the implementation above:
- Virtual Nodes: The ring is divided into segments. When
Node C joins, it sprinkles 150 points onto the ring.
- Stealing:
Node C only takes the keys that fall between its position and the previous neighbor's position.
- The Migration Plan: The
get_migration_plan method is crucial for operational safety. It tells you exactly which segments of the hash space need to be copied from existing nodes to the new node, allowing for a graceful "hand-off" where the old node serves traffic while the new node loads data.
B. Hot Key Detection Strategy
Detecting hot keys is difficult because tracking every key consumes too much RAM.
- Sliding Window: We divide time into fixed windows (e.g., 5 seconds). We accumulate counts in a dictionary.
- Decay/Reset: At the end of the window, we check for keys exceeding the
hot_threshold (e.g., > 1000 requests/sec). We then clear the map. This ensures we detect current hot spots, not historical averages.
- Actions: When a hot key is detected, the library consumer (the application) can take action:
- Caching: Aggressively cache the value at the edge.
- Replication: Dynamically assign more replicas (vnodes) to that specific key range to spread the read load (advanced feature).
- Rate Limiting: Throttle that specific key.
5. Usage Example
# Initialize
hash_lib = ConsistentHashRing(replicas=150)
# Cluster Setup
hash_lib.add_node("Cache-Server-A")
hash_lib.add_node("Cache-Server-B")
# Standard Request
node = hash_lib.get_node("user:1234:profile")
print(f"Key 'user:1234:profile' is on {node}")
# --- Rebalancing Simulation ---
print("\n--- Adding New Node ---")
migration_plan = hash_lib.get_migration_plan("Cache-Server-C")
for source_node, ranges in migration_plan.items():
print(f"To add 'Cache-Server-C', move {len(ranges)} segments from {source_node}")
# Apply the change
hash_lib.add_node("Cache-Server-C")
# --- Hot Key Simulation ---
# Simulate heavy load on one key
for _ in range(15000):
hash_lib.get_node("trending_article_55")
print("\n--- Hot Key Report ---")
print(hash_lib.get_hot_keys())