Sub topic 5
Virtual Nodes and Balanced Load
This chapter assumes you have read the previous chapter on consistent hashing and the hash ring. You should be comfortable reading short Python snippets and know that a key is stored on the first node clockwise from its hash. Here we look at why a plain ring balances load poorly and how virtual nodes fix that.
The problem with one point per node
In a basic consistent-hash ring, each physical node gets one position, found by hashing its name. A node owns the arc of the ring between the previous node's position and its own.
Hash outputs are random, so positions are not evenly spaced. With a small number of nodes, some arcs are much longer than others. Three problems follow:
- Uneven data. A node with a long arc stores more keys than its peers.
- Uneven traffic. More keys usually means more requests, so one node runs hot while others idle.
- Lopsided failure handling. When a node leaves, its whole arc goes to a single neighbor, the next node clockwise. That neighbor suddenly carries its own load plus the departed node's load. This can push it over capacity and cause a cascade of failures.
Adding a node has a related issue. The new node splits only one existing arc, so it takes load from only one neighbor. The other nodes gain nothing.
The idea: many ring positions per node
A virtual node (vnode) is a position on the ring that belongs to a physical node. Instead of hashing the node name once, you hash it many times, for example node-a#0, node-a#1, and so on up to node-a#63. Each hash becomes a separate point on the ring, and every point maps back to the same physical node.
A physical node now owns many small arcs scattered around the ring. A key is still routed by finding the first point clockwise from its hash. You then look up which physical node owns that point.
Because each node owns many small arcs, the sum of those arcs concentrates around the average. This is the law of large numbers at work: the more random samples you add, the closer the total gets to the expected value.
Benefits
- Better balance. Total ownership per node converges toward an even share as the vnode count grows.
- Spread-out failure load. When a node leaves, each of its small arcs moves to a different successor, so the load is shared among many survivors instead of landing on one.
- Spread-out joins. A new node takes many small slices from many existing nodes. Data streaming into the new node comes from several sources in parallel, which speeds up bootstrapping.
- Heterogeneous hardware. Give a machine with twice the disk and CPU twice as many vnodes. It then receives about twice the data and traffic.
Measuring the balance
You can check how even the load is by simulating many keys. The code below builds a ring, assigns 100,000 keys, and reports the spread between the most and least loaded node. It reuses the hashing approach from the earlier ring example, and it is complete as shown.
import bisect
import hashlib
from collections import Counter
def h(key: str) -> int:
return int.from_bytes(hashlib.md5(key.encode()).digest()[:8], "big")
class Ring:
def __init__(self, nodes, vnodes=64):
self._points = sorted(
(h(f"{node}#{i}"), node) for node in nodes for i in range(vnodes)
)
self._hashes = [p[0] for p in self._points]
def owner(self, key: str) -> str:
idx = bisect.bisect(self._hashes, h(key)) % len(self._points)
return self._points[idx][1]
def imbalance(vnodes: int, keys: int = 100_000) -> float:
"""Return max load divided by mean load across nodes."""
nodes = [f"node-{c}" for c in "abcdefghij"]
ring = Ring(nodes, vnodes)
counts = Counter(ring.owner(f"key:{i}") for i in range(keys))
mean = keys / len(nodes)
return max(counts.values()) / mean
for v in (1, 8, 64, 256):
print(f"vnodes={v:>3} max/mean load = {imbalance(v):.2f}")The ratio of the busiest node's load to the mean is a useful single number. A value of 1.00 would be perfect. With one vnode per node, the ratio is typically well above 1.5, so the busiest node holds more than half again its fair share. By 64 to 256 vnodes it usually falls to roughly 1.1 to 1.2. Exact values vary with the hash function and node names, so run the script yourself rather than relying on these figures.
The improvement follows a square-root pattern. The relative spread shrinks roughly in proportion to one over the square root of the vnode count. Going from 64 to 256 vnodes cuts the spread about in half, while going from 256 to 1024 buys the same relative gain at four times the cost.
Costs and trade-offs
More vnodes is not free.
| Concern | Effect of more vnodes |
|---|---|
| Ring metadata | Every node must store and gossip the whole ring. Memory and bandwidth grow with nodes times vnodes. |
| Lookup time | Binary search stays logarithmic, so lookups are cheap. Rebuilding the sorted structure on membership change costs more. |
| Replication overhead | Replica sets are more varied, so a node shares data with many more peers. |
| Repair cost | Merkle trees and repair work are done per range, and many small ranges mean many small trees. |
| Failure blast radius | A single node loss touches many peers at once, which spreads load but also means more nodes are involved in recovery. |
A common choice is somewhere between 16 and 256 vnodes per node, depending on cluster size and how uniform you need the load to be. Larger clusters need fewer vnodes per node for the same balance, because the total number of points is already large.
Interaction with replication
The ring example from the previous chapter returns a preference list: the first N distinct physical nodes found clockwise. With vnodes, this detail matters. Walking clockwise from a key, you may meet several consecutive points that belong to the same physical node. If you counted those as separate replicas, all your copies could land on one machine, and a single failure would lose the data.
The preference_list method skips points whose physical node is already in the result. It keeps walking until it has N distinct nodes. Without that check, replication would give no fault tolerance.
You can go further. If nodes sit in racks or availability zones, skip candidates in a rack you have already chosen. This keeps replicas in separate failure domains.
Edge cases and practical notes
- Hash collisions. Two vnodes can land on the same position in a small hash space. With a 64-bit hash this is very unlikely, but a robust implementation breaks ties deterministically, for example by sorting on
(hash, node). The example above does this because tuples sort by their second element when the first matches. - Small clusters. With three nodes and replication factor three, every node holds every key regardless of vnodes. Vnodes still help with traffic distribution for coordination, but not with data placement.
- Skewed keys. Vnodes balance the number of keys, not the traffic per key. A single hot key still hits one replica set. Fixes such as key splitting or caching belong at a different layer.
- Non-random assignment. Some systems assign token ranges deliberately instead of hashing, to get exact balance. Cassandra's newer allocation algorithm does this to reach good balance with few tokens per node. Randomness is simple, while deliberate allocation gives tighter balance with fewer points.
- Stable names. Vnode positions are derived from the node name and index. If a node is renamed or re-provisioned under a new name, its points move and data must be re-streamed. Use stable identifiers.
- Changing vnode counts. Raising a node's vnode count later shifts ownership toward it. This is the mechanism for rebalancing heterogeneous hardware, but each change triggers data movement.
Putting it together
The partitioning pipeline now looks like this: hash the key, find the first vnode point clockwise, map it to a physical node, then keep walking to collect N distinct nodes for replication. Vnodes change only the placement of points. They do not change how routing, replication, or quorums work, which is why this idea slots cleanly into the design.
Exercise
A cluster has 5 physical nodes, each with 128 vnodes, and a replication factor of 3. One node fails permanently. Roughly how many other nodes receive data from the failed node's ranges, and why is this better than a ring with one point per node?
Show answer
With 128 vnodes spread randomly, the failed node's ranges are followed by points belonging to all four surviving nodes, so all four take over some of its data and can stream replicas in parallel. With one point per node, only the single clockwise neighbor takes over the primary range, so it receives all the extra load and becomes a bottleneck.
Exercise
Your preference_list implementation returns the first 3 ring points clockwise without checking whether they belong to different physical nodes. What can go wrong, and how do you fix it?
Show answer
Consecutive points can belong to the same physical node, so two or all three replicas may sit on one machine and a single failure can lose data. Fix it by walking the ring and adding a node only if it is not already in the result, continuing until 3 distinct physical nodes are found, optionally also requiring distinct racks or zones.