TExcelTAD
Home › System Design › Consistent Hashing

Consistent Hashing

Consistent hashing maps keys to nodes so that adding or removing a node moves only a small share of the keys, about 1/N, instead of nearly all of them as with hash % N. It's the placement scheme behind Amazon's Dynamo, Cassandra, Riak, many CDN and cache clusters, and load balancers that need session affinity.

The ring

Imagine the output range of a hash function bent into a circle (for example 0 to 2^32 - 1). Each node is hashed to a point on the ring. Each key is hashed too, and belongs to the first node found clockwise from it.

text
                 0
           .-----+-----.
      node C           node A        key k1 -> walk clockwise -> node A
        |                 |          key k2 -> walk clockwise -> node B
      key k3            key k1
        |                 |
      node B -----+---- key k2
               2^31

When a node joins, it takes over only the keys between its predecessor and itself. When a node leaves, only its keys move, to its successor. Everyone else stays put.

A basic ring

python · try it yourself
import bisect
import hashlib

def h(value):
    return int(hashlib.md5(value.encode()).hexdigest(), 16) % 2**32

class Ring:
    def __init__(self, nodes):
        self.points = sorted((h(n), n) for n in nodes)

    def node_for(self, key):
        hashes = [p for p, _ in self.points]
        i = bisect.bisect_right(hashes, h(key)) % len(self.points)   # wrap around
        return self.points[i][1]

ring = Ring(["cache-a", "cache-b", "cache-c"])
for point, node in ring.points:
    print(f"{node} at {point:>10}")
for key in ["user:1", "user:2", "session:9", "cart:77"]:
    print(f"{key:<10} hash {h(key):>10} -> {ring.node_for(key)}")
cache-a at 2210605878
cache-c at 3459865858
cache-b at 4013778964
user:1     hash 3519597778 -> cache-b
user:2     hash 4009813293 -> cache-b
session:9  hash  129521112 -> cache-a
cart:77    hash  596722091 -> cache-a

Measuring how many keys move

Now compare hash % N with the ring when a fourth node is added:

python · try it yourself
import bisect
import hashlib

def h(value):
    return int(hashlib.md5(value.encode()).hexdigest(), 16) % 2**32

class Ring:
    def __init__(self, nodes, vnodes=1):
        self.points = sorted((h(f"{n}#{i}"), n) for n in nodes for i in range(vnodes))
        self.hashes = [p for p, _ in self.points]

    def node_for(self, key):
        i = bisect.bisect_right(self.hashes, h(key)) % len(self.points)
        return self.points[i][1]

keys = [f"user:{i}" for i in range(20_000)]
old_nodes = ["n1", "n2", "n3"]
new_nodes = old_nodes + ["n4"]

mod_moved = sum(h(k) % 3 != h(k) % 4 for k in keys)
print(f"hash % N           : {mod_moved / len(keys):5.1%} of keys moved")

for vnodes in [1, 100]:
    old_ring, new_ring = Ring(old_nodes, vnodes), Ring(new_nodes, vnodes)
    moved = [k for k in keys if old_ring.node_for(k) != new_ring.node_for(k)]
    to_n4 = all(new_ring.node_for(k) == "n4" for k in moved)
    print(f"ring, {vnodes:3} point(s) : {len(moved) / len(keys):5.1%} of keys moved, all to n4: {to_n4}")
print(f"ideal              : {1 / 4:5.1%}")
hash % N           : 74.9% of keys moved
ring,   1 point(s) : 11.4% of keys moved, all to n4: True
ring, 100 point(s) : 23.5% of keys moved, all to n4: True
ideal              : 25.0%

Both ring variants only move keys to the new node; nothing is shuffled between the old nodes. But with a single point per node, n4 happened to land on a small arc and took only about 11% of the keys instead of 25%, so it is underused. With 100 points per node it takes close to its fair quarter. That unevenness is the next problem to solve.

Virtual nodes

With only a few points on the ring, the arcs between them are very uneven, so some nodes own far more keys than others. The fix is virtual nodes: each physical node is placed on the ring many times (n1#0, n1#1, …). More points means arcs average out, and a node's load is spread over many small arcs. Virtual nodes also make weighting easy: a machine twice as big gets twice as many points.

python · try it yourself
import bisect
import hashlib
from collections import Counter

def h(value):
    return int(hashlib.md5(value.encode()).hexdigest(), 16) % 2**32

class Ring:
    def __init__(self, nodes, vnodes):
        self.points = sorted((h(f"{n}#{i}"), n) for n in nodes for i in range(vnodes))
        self.hashes = [p for p, _ in self.points]

    def node_for(self, key):
        i = bisect.bisect_right(self.hashes, h(key)) % len(self.points)
        return self.points[i][1]

nodes = ["n1", "n2", "n3", "n4", "n5"]
keys = [f"item:{i}" for i in range(20_000)]
ideal = len(keys) / len(nodes)

for vnodes in [1, 10, 100, 500]:
    ring = Ring(nodes, vnodes)
    load = Counter(ring.node_for(k) for k in keys)
    worst = max(load.values()) / ideal
    print(f"{vnodes:3} vnodes/node: keys per node {[load[n] for n in nodes]}  max/ideal {worst:.2f}")
  1 vnodes/node: keys per node [1977, 5918, 69, 2445, 9591]  max/ideal 2.40
 10 vnodes/node: keys per node [3982, 4174, 3727, 4279, 3838]  max/ideal 1.07
100 vnodes/node: keys per node [4047, 4065, 4321, 3831, 3736]  max/ideal 1.08
500 vnodes/node: keys per node [3922, 3958, 4064, 3917, 4139]  max/ideal 1.03

With one point per node the busiest node holds far more than its fair share; with a few hundred virtual nodes each node is close to the ideal 4,000 keys.

Replication on the ring

To store N copies, walk clockwise from the key and take the first N distinct physical nodes (skipping further virtual nodes of a node already chosen). This list is called the key's preference list:

python · try it yourself
import bisect
import hashlib

def h(value):
    return int(hashlib.md5(value.encode()).hexdigest(), 16) % 2**32

nodes, VNODES = ["n1", "n2", "n3", "n4"], 8
points = sorted((h(f"{n}#{i}"), n) for n in nodes for i in range(VNODES))
hashes = [p for p, _ in points]

def preference_list(key, n_copies=3):
    i = bisect.bisect_right(hashes, h(key))
    chosen = []
    while len(chosen) < n_copies:
        node = points[i % len(points)][1]
        if node not in chosen:
            chosen.append(node)
        i += 1
    return chosen

for key in ["cart:0", "cart:4", "cart:5", "cart:11"]:
    print(key, "->", preference_list(key))
cart:0 -> ['n3', 'n2', 'n1']
cart:4 -> ['n2', 'n3', 'n4']
cart:5 -> ['n1', 'n4', 'n2']
cart:11 -> ['n4', 'n2', 'n1']

The first node is the key's coordinator; the others are its replicas. If a replica is down, the next node clockwise can temporarily accept the write (a hinted handoff) and pass it on when the owner comes back.

Alternatives

Scheme Idea Used by
Ring + virtual nodes Described above Cassandra, Dynamo, Riak
Rendezvous (HRW) hashing For each key, score every node with hash(key, node); pick the highest Some CDNs, load balancers
Jump consistent hash Tiny, fast formula for numbered buckets; no ring memory Storage systems with numbered shards
Fixed partitions hash % P with a partition-to-node table Kafka, Elasticsearch, Redis Cluster (16,384 slots)

Tip: Hash with a stable function such as MD5, xxHash or MurmurHash. Python's built-in hash() for strings is randomised per process, so two servers would disagree about where a key lives.

Test yourself

On a hash ring, which node owns a key?

  1. The node with the closest hash in either direction
  2. The first node clockwise from the key's hash
  3. The node with the smallest hash
  4. A random node

Why use virtual nodes?

  1. To encrypt keys
  2. To even out the key distribution and allow weighting nodes by capacity
  3. To avoid hashing
  4. To reduce the number of physical nodes

Adding a 4th node to a 3-node consistent hashing ring ideally moves about what share of keys?

  1. 0%
  2. 25%
  3. 75%
  4. 100%