Sub topic 8
Virtual nodes for smoother balance
This chapter assumes you have read the earlier chapters on the hash ring and on lookup by clockwise successor. You should be comfortable with bisect and with the idea that a node owns the arc of the ring that ends at its position.
The problem to fix
With one position per node, each node owns the arc between its predecessor and itself. Positions come from a hash, so they land at random. Random points on a circle make arcs of very different lengths. With 5 nodes, one node can easily own 35% of the ring while another owns 8%.
A second problem appears when a node leaves. All of its keys go to a single neighbor, the next node clockwise. That neighbor's load jumps, and it may fail under the extra traffic.
The idea
A virtual node (vnode) is one of many ring positions that belong to the same physical node. Instead of hashing "a" once, you hash "a#0", "a#1", up to "a#99". Each hash is a separate position, and all of them map back to node a.
Each node now owns many small arcs scattered around the ring. The total length of its arcs is the sum of many random pieces, and sums of many random pieces cluster near their average. The relative spread of a node's share shrinks roughly as 1 / sqrt(v), where v is the number of vnodes per node. Going from 1 to 100 vnodes cuts the spread by about a factor of 10.
Removal also improves. A departing node's many arcs are each followed by a different neighbor, so its keys spread over most of the remaining nodes instead of landing on one.
Measuring it
The script below uses a trimmed version of the ring from the implementation chapter. It reports the busiest node's load divided by the ideal even share. A value of 1.0 is perfect balance.
import bisect
import hashlib
from collections import Counter
def _hash(value):
return int(hashlib.md5(value.encode()).hexdigest(), 16)
class HashRing:
def __init__(self, nodes=(), vnodes=100):
self.vnodes = vnodes
self._hashes = []
self._owners = {}
for node in nodes:
self.add_node(node)
def add_node(self, node):
for i in range(self.vnodes):
h = _hash(f"{node}#{i}")
bisect.insort(self._hashes, h)
self._owners[h] = node
def get_node(self, key):
idx = bisect.bisect_right(self._hashes, _hash(key)) % len(self._hashes)
return self._owners[self._hashes[idx]]
def peak_load(vnodes, total_keys=20000):
nodes = ["a", "b", "c", "d", "e"]
ring = HashRing(nodes, vnodes)
counts = Counter(ring.get_node(f"key{i}") for i in range(total_keys))
return max(counts.values()) / (total_keys / len(nodes))
for v in (1, 10, 100, 1000):
print(v, round(peak_load(v), 2))With 1 vnode per node, the busiest node typically carries well above its share. By 100 vnodes the peak is usually within a few percent of 1.0. The exact numbers depend on the hash values, but the trend holds.
Trade-offs
More vnodes give better balance, and they cost memory and work elsewhere.
| Vnodes per node | Balance | Ring size (5 nodes) | Cost of adding a node |
|---|---|---|---|
| 1 | Poor | 5 entries | Cheap |
| 100 | Good | 500 entries | Moderate |
| 1000 | Very good | 5,000 entries | Higher |
- Lookup stays O(log n) in the number of ring entries, so lookup speed barely changes.
bisect.insortinto a Python list is O(n) per insert, so adding a node with many vnodes is slower. You can fix this by collecting all new hashes and sorting once.- Routing tables and membership gossip grow with the number of entries.
- Replica selection must skip vnodes of a physical node already chosen, as the replication chapter shows.
Common mistakes
- Hashing
f"{node}{i}"without a separator. Then"a1"plus"1"collides with"a"plus"11". Use#or similar. - Using the vnode count as a fixed constant everywhere. If clients and servers disagree on it, they build different rings and route the same key differently.
- Forgetting that two vnodes can share a hash value. It is very unlikely with MD5, but the
_ownersdict would silently overwrite one owner.
Exercise
A ring has 4 physical nodes with 50 vnodes each. How many entries does the sorted list hold? If node "d" is removed, roughly what share of all keys is reassigned, and how many different nodes receive them?
Show answer
The list holds 4 × 50 = 200 entries. Node "d" owned about 1/4 of the keys, so about 25% are reassigned. Because its 50 arcs are each followed by different neighbors, those keys go to all three remaining nodes, roughly a third of them each, instead of landing on a single neighbor.