Sub topic 8
Virtual nodes for smoother balance
This chapter assumes you know how the hash ring and the clockwise-successor lookup work, and that you can read Python and follow a binary search. It fixes the load imbalance from the previous chapter by giving each physical node many positions on the ring.
The problem in one picture
With one position per node, each node owns the arc that ends at its position. The arc lengths come from random hash values, so they differ a lot. When you place N random points on a ring, the arc lengths are roughly exponentially distributed. The standard deviation of an arc is about as large as its mean. The longest arc is about ln N times the average.
In practice, one node can hold several times its fair share of keys while another holds almost none. The node with the biggest arc also gets the most traffic, so it fails first.
The idea
A virtual node (vnode) is a position on the ring that stands for a physical node. Instead of hashing a node name once, you hash it many times with a suffix:
a#0, a#1, a#2, ... a#99Each of these hashes lands at a different place on the ring. A key is still routed to the first position clockwise from its hash. You then look up which physical node owns that position. The physical node's total share is the sum of many small arcs.
The ring holds the same kind of data as before: a sorted list of hash positions and a map from position to owner. The only change is that there are N × V entries instead of N.
Why more virtual nodes help
A node's share is the sum of V random arcs. By the usual averaging argument, the relative standard deviation of that sum shrinks like 1/√V. This is an approximation, not an exact law, but it matches what you see in practice.
| Virtual nodes per node | Approximate relative standard deviation of load |
|---|---|
| 1 | about 100% |
| 10 | about 32% |
| 100 | about 10% |
| 1000 | about 3% |
Each tenfold increase in V cuts the spread by about a factor of three. Returns diminish quickly. Going from 100 to 1000 costs ten times the memory for a gain of seven percentage points.
Measuring it yourself
The class below is the same ring as before, so this script runs on its own. It places 100,000 keys on 10 nodes and reports the lightest and heaviest node as a multiple of the ideal share (1.0 means a perfectly even split).
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 remove_node(self, node):
for i in range(self.vnodes):
h = _hash(f"{node}#{i}")
self._hashes.remove(h)
del self._owners[h]
def get_node(self, key):
if not self._hashes:
raise LookupError("ring is empty")
idx = bisect.bisect_right(self._hashes, _hash(key)) % len(self._hashes)
return self._owners[self._hashes[idx]]
def load_range(vnodes, node_count=10, key_count=100_000):
names = [f"node{i}" for i in range(node_count)]
ring = HashRing(names, vnodes=vnodes)
counts = Counter(ring.get_node(f"key{i}") for i in range(key_count))
mean = key_count / node_count
loads = [counts.get(name, 0) / mean for name in names]
return min(loads), max(loads)
for v in (1, 10, 100, 1000):
low, high = load_range(v)
print(f"vnodes={v:5d} lightest={low:.2f}x heaviest={high:.2f}x")Expect the gap between lightest and heaviest to narrow as vnodes grows. With 1 vnode, some node will usually be far above or below 1.0. With 1000 vnodes, both values should sit within a few percent of 1.0. The exact numbers depend on the hash values, so yours may differ from another run with different key names.
What virtual nodes do to node changes
Virtual nodes also change what happens when a node joins or leaves.
- Removing a node. Its V positions disappear. Each arc it owned is absorbed by the next position clockwise, which usually belongs to a different node each time. The departing node's keys are spread across many survivors instead of landing on a single neighbor.
- Adding a node. Its V positions are inserted at scattered points. Each one takes a small slice from whichever node owned that spot. The new node pulls a little load from many existing nodes instead of a lot from one.
This matters during failures. Without vnodes, when a node dies its successor suddenly takes on double load and may fail too, which starts a cascade. With vnodes, the extra load is shared among many nodes, so each one absorbs only a small increase.
The fraction of keys that move is still about 1/(N+1) when you add the (N+1)th node, and about 1/N when you remove one of N. Virtual nodes do not change the total amount that moves. They change who sends and who receives.
Trade-offs and costs
More virtual nodes give better balance but cost more in several places.
| Cost | Effect |
|---|---|
| Memory | The ring stores N × V positions and owners. 1,000 nodes at 200 vnodes is 200,000 entries. |
| Lookup time | Still O(log(N × V)). Going from 100 to 1000 vnodes adds about 3 comparisons. |
| Membership change time | `bisect.insort` and `list.remove` each shift list elements, so one insert or remove is O(N × V). Adding a node with V vnodes costs O(V × N × V) in total. |
| Metadata and coordination | Every client or router needs the same ring. A bigger ring means more to ship and keep in sync. |
| Replication | Replica choice must skip positions of nodes already chosen, which can mean walking further around the ring. |
For a few dozen nodes, 100 to 200 vnodes is a common starting range. Larger fleets sometimes use fewer vnodes per node, because the total ring size is already large, and a single node's share is the sum of many arcs either way. Measure the spread for your own node count rather than copying a number.
Edge cases
- Position collisions. Two vnodes could hash to the same position. With a 128-bit hash this is practically impossible, but in the code above a collision would overwrite an entry in
_ownerswhile the position appears twice in_hashes. If you truncate hashes to 32 bits for a smaller ring, check for collisions when adding a node. - Few keys. Smooth arcs do not guarantee smooth load when you have very few keys. With 1,000 keys on 10 nodes, random variation in the keys themselves dominates. Balance claims assume many keys.
- Hot keys. Virtual nodes spread keys evenly, not requests. A single very popular key still lands on one node. Fixing that needs replication or key splitting, not more vnodes.
- Uneven hardware. Equal vnode counts assume equal nodes. The weighted nodes chapter shows how to vary the count per node.
- Warm-up. A new node's V positions take over keys immediately. If it is a cache, those keys miss until the node warms up. Some systems add vnodes in batches to spread this cost over time.
Choosing V
- Decide how much imbalance you can tolerate. A target of about 10% needs roughly 100 vnodes by the 1/√V estimate.
- Check that N × V positions fit comfortably in memory on every client.
- Run the measurement script with your real node count and a sample of real keys.
- Pick the smallest V that meets the target. Raise it only if you see a measured problem.
Exercise
A ring has 20 physical nodes with 150 virtual nodes each. How many entries does the sorted list hold, and roughly how many comparisons does one binary search need? Then explain why a lookup under this ring is no more complex than a lookup under a ring with 1 vnode per node.
Show answer
The list holds 20 × 150 = 3,000 positions. Binary search needs about log2(3000), which is about 12 comparisons. A ring with 1 vnode per node has 20 positions and needs about 4 to 5 comparisons. The lookup steps are identical in both cases: hash the key, binary search for the first position greater than the hash, wrap around at the end, and read the owner from the map. Only the list size differs, so the cost grows logarithmically with it.
Exercise
Node "c" is removed from a ring with 4 nodes and 100 vnodes each. Without vnodes, all of c's keys would go to one successor. Where do c's keys go with vnodes, and about what fraction of all keys move?
Show answer
Each of c's 100 positions hands its arc to whichever position follows it clockwise. Those followers belong to a, b, and d in roughly equal measure, so c's keys are spread over all three survivors. About one quarter of all keys move (c's share, 1/4). Because the load is split across three nodes, each survivor gains about one third of c's load instead of one node gaining all of it.
Exercise
You raise the vnode count from 100 to 1000 and the spread of load drops, but cluster startup time gets much worse in the Python ring above. Why?
Show answer
Each add_node call does V bisect.insort operations. Each insort shifts list elements, so it costs O(list size). With 10 times more vnodes, there are 10 times more inserts into a list that is also up to 10 times longer, so building the ring costs on the order of 100 times more. A faster approach is to collect all hashes first, sort once, and build the owner map in a single pass.