This article delves into consistent hashing, a fundamental technique for distributing data across a dynamic set of servers in distributed systems. It explains the concept of a hash ring and virtual nodes to achieve data balance and discusses the often-overlooked challenge of traffic imbalance caused by hot keys, offering practical mitigation strategies.
Read original on Dev.to #systemdesignDistributing keys across a cluster using simple `hash(key) % N` is straightforward initially. However, this approach becomes problematic in dynamic environments where servers are frequently added or removed. When `N` (the number of servers) changes, almost all keys remap to new servers. This can lead to a massive cache stampede, where a significant portion of cached data becomes invalid, overwhelming the underlying database with requests that the cache was intended to absorb.
Consistent hashing addresses the remapping problem by mapping both servers and keys onto a conceptual "hash ring" (a circular hash space, typically 0 to 2 ³²−1). Each key is assigned to the first server encountered by walking clockwise from the key's position on the ring. This design significantly reduces key remapping:
Roughly `K/N` keys (where K is total keys, N is total servers) move per server change, a substantial improvement over the entire dataset remapping.
While a hash ring reduces remapping, a small number of physical servers can still result in uneven distribution of keys (data imbalance) due to random placement on the ring. Virtual nodes solve this by mapping each physical server to multiple (e.g., 100-200) distinct points on the hash ring. This increases the number of server positions, allowing the law of large numbers to distribute keys more evenly, typically resulting in less than 5% load variance between machines.
Virtual Nodes: Data vs. Traffic Balance
Virtual nodes primarily ensure data balance, meaning each server holds roughly the same number of keys. They do not inherently solve issues related to traffic balance.
Even with perfect data balance from virtual nodes, a single "hot key" (e.g., a viral celebrity profile) can direct all its traffic to one server, creating a traffic imbalance. This server becomes a bottleneck despite holding an average number of keys. Common mitigations include:
Real-World Applications
Consistent hashing is widely used in production systems like DynamoDB (partition key routing), Cassandra (token-ring based partitioning), Redis Cluster (hash slots), and CDNs (edge node routing).