Consistent Hashing — algorithm для distributing keys across nodes, где adding/removing node moves только ~1/N keys (не all). Базис distributed caches (Memcached, Redis Cluster), CDN (Akamai routing), DB sharding. Key insight: hash nodes и keys на circle (ring), key goes to closest node clockwise. Virtual nodes (vnodes) balance load.
Ниже: подробности, пример, смежные термины, FAQ.
Бесплатный онлайн-инструмент — проверка HTTP-заголовков: результат мгновенно, без регистрации.
// Pseudocode
function nodeForKey(key, ring):
h = hash(key)
for node in ring sorted by hash:
if hash(node) >= h: return node
return ring[0] // wrap aroundConsistent Hashing offers several advantages over traditional hashing methods:
These advantages make consistent hashing a popular choice for distributed systems that require high availability and scalability.
Implementing consistent hashing involves several steps:
Here is a simple example of how to implement consistent hashing in Python:
python
def consistent_hashing(keys, nodes):
# Define the hash function
def hash_function(key):
return hash(key) % len(nodes)
# Create a list of virtual nodes
virtual_nodes = [node for node in nodes for _ in range(10)]
# Distribute the keys
key_to_node = {key: virtual_nodes[hash_function(key)] for key in keys}
return key_to_nodeConsistent hashing is just one of many load balancing techniques used in distributed systems. Here are some other popular techniques and how they compare to consistent hashing:
Consistent hashing is particularly useful in scenarios where the system needs to be highly available and scalable, such as in distributed caches, CDNs, and database sharding.
Redis Cluster (16384 slots), Memcached client-side sharding, DynamoDB partitioning, Cassandra, Akamai CDN, любые distributed caches.
Range — сортируется, easy range queries. Consistent — лучше balance, auto-reshuffle. Для large-scale — consistent.
Rendezvous simpler, O(n) per lookup vs O(log n). Для small N — comparable. Для huge clusters — consistent hashing win.
Бесплатный тариф — 10 мониторов, проверки каждые 5 мин, без карты. Платные тарифы — интервал от 1 минуты и проверки из нескольких регионов.