Sub topic 11
Giving bigger nodes more of the ring
This chapter assumes you have read the earlier chapters on the hash ring, virtual nodes, and ring lookup with a sorted list. You should be able to read the HashRing class from the implementation chapter.
Why equal shares are not always right
A plain ring with virtual nodes gives every node about the same share of the keys. That is correct when all nodes are identical. Real clusters are often not identical:
- A cache fleet may mix machines with 16 GB and 64 GB of memory.
- A storage cluster may be upgraded one rack at a time, so old and new disks coexist.
- A node may share its host with other work and should take less traffic.
If each node gets an equal share, the smallest machine fills up or saturates first, and the larger machines sit partly idle. You want each node's share of the keys to be proportional to a weight you choose, such as its memory size or its core count.
The core idea: weight sets the number of virtual nodes
A node's share of the ring is the sum of the arcs that its virtual nodes own. With enough virtual nodes, each one owns about the same expected arc, so the share is roughly proportional to the node's virtual node count. To give a node twice the share, give it twice as many virtual nodes.
The formula is:
vnode_count(node) = max(1, round(base_vnodes * weight))
expected_share(node) = vnode_count(node) / sum of all vnode countsbase_vnodes is the count for a node of weight 1.0. The lookup code does not change. It still finds the first virtual node at or after the key's hash. Only the number of positions each node registers differs.
Implementation
The class below is self-contained. It differs from the earlier HashRing in three ways:
add_nodetakes a weight.- The ring remembers how many virtual nodes each node has.
- A new
set_weightmethod changes a node's weight in place.
import bisect
import hashlib
def _hash(value):
return int(hashlib.md5(value.encode()).hexdigest(), 16)
class WeightedHashRing:
def __init__(self, base_vnodes=100):
self.base_vnodes = base_vnodes
self._hashes = []
self._owners = {}
self._counts = {}
def _count_for(self, weight):
if weight <= 0:
raise ValueError("weight must be positive")
return max(1, round(self.base_vnodes * weight))
def _add_vnodes(self, node, start, stop):
for i in range(start, stop):
h = _hash(f"{node}#{i}")
bisect.insort(self._hashes, h)
self._owners[h] = node
def _remove_vnodes(self, node, start, stop):
for i in range(start, stop):
h = _hash(f"{node}#{i}")
self._hashes.remove(h)
del self._owners[h]
def add_node(self, node, weight=1.0):
if node in self._counts:
raise ValueError(f"{node} is already on the ring")
count = self._count_for(weight)
self._add_vnodes(node, 0, count)
self._counts[node] = count
def remove_node(self, node):
self._remove_vnodes(node, 0, self._counts.pop(node))
def set_weight(self, node, weight):
old = self._counts[node]
new = self._count_for(weight)
if new > old:
self._add_vnodes(node, old, new)
elif new < old:
self._remove_vnodes(node, new, old)
self._counts[node] = new
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]]Two details matter here.
The ring stores the count, not the weight. remove_node must remove exactly the positions that add_node created. Recomputing them from a floating-point weight risks a mismatch from rounding. Storing the integer count avoids that.
Virtual node names are stable. The nodes are called large#0, large#1, and so on. Raising the count from 400 to 600 adds large#400 through large#599 and leaves the first 400 positions where they were. This is what makes reweighting cheap, as the next section shows.
Checking the shares
Build a ring with weights 1, 2 and 4, then count where 20,000 keys land.
from collections import Counter
ring = WeightedHashRing(base_vnodes=100)
ring.add_node("small", 1)
ring.add_node("medium", 2)
ring.add_node("large", 4)
keys = [f"key{i}" for i in range(20000)]
counts = Counter(ring.get_node(k) for k in keys)
for node in ("small", "medium", "large"):
print(node, round(counts[node] / len(keys), 3))The expected shares are 1/7 ≈ 0.143, 2/7 ≈ 0.286 and 4/7 ≈ 0.571. The measured values land close to these, usually within a few hundredths. They will not match exactly, because the arcs are random. The relative error shrinks as the virtual node count grows, which is the same trade-off you met in the virtual nodes chapter: more positions give smoother balance at the cost of memory and slower inserts.
Changing a weight moves only the difference
Suppose large gets a hardware upgrade and its weight goes from 4 to 6. Under modulo hashing this would be a disaster. On the ring, only the new positions matter.
before = {k: ring.get_node(k) for k in keys}
ring.set_weight("large", 6)
after = {k: ring.get_node(k) for k in keys}
moved = [k for k in keys if before[k] != after[k]]
print(round(len(moved) / len(keys), 3))
print(Counter(after[k] for k in moved))The total changes from 700 to 900 virtual nodes. The share of large rises from 400/700 ≈ 0.571 to 600/900 ≈ 0.667. The fraction of keys that move is the difference, about 0.095, and every moved key goes to large. Keys never move between small and medium, because only large gained positions. A new virtual node can take keys from one of large's own existing virtual nodes, but those keys do not change owner, so they do not count as moved.
Lowering a weight is the mirror image. Only keys held by the removed positions move, and they go to the next clockwise neighbors.
Gotchas
Rounding limits the weight resolution
The count is an integer, so with base_vnodes=100 the smallest step in weight is 0.01. Weights closer than that are indistinguishable. A weight of 0.001 still gets one virtual node because of the max(1, ...) floor, which makes that node larger than its weight says. If your weights span a wide range, choose base_vnodes so the smallest node still gets dozens of positions.
Heavy nodes need more positions to look smooth
Variance depends on the number of virtual nodes in play, not on the weights. A node with 10 virtual nodes has a noisy share even if its target is 5%. Scale base_vnodes up for the lightest node you expect, not the typical one.
Weight is a statement about keys, not load
The ring balances the count of keys. If some keys are much hotter than others, a node with a small weight can still be overloaded. Weights also cannot fix one extremely hot key, because a key always maps to the same position. Treat weights as a capacity model for evenly spread traffic and add other mechanisms, such as caching in front or splitting hot keys, for skew.
Memory and insert cost grow with total virtual nodes
The sorted list holds every position. bisect.insort is O(n) for each insert because the list shifts, so building a ring with 100,000 positions one insert at a time is slow. For larger rings, collect all hashes and sort once, or use a tree-based structure.
Replication interacts with weights
When you pick replicas by walking clockwise and skipping nodes already chosen, as in the replication chapter, heavier nodes appear more often in the walk. That is usually what you want, since they hold more data. With very skewed weights and few nodes, though, a single heavy node can own most of the ring. The walk then skips many consecutive positions before it finds a second distinct node. The replica sets still come out correct, but the second and third replicas concentrate on whichever nodes sit next to the heavy node's arcs. Check the replica distribution as well as the primary distribution.
Hash collisions between positions
Two virtual nodes that hash to the same value would overwrite each other in _owners, and remove_node could then fail. With a 128-bit hash this is not a practical risk, but if you shorten the hash for compact storage, check for collisions on insert.
Weights in rendezvous hashing
Rendezvous hashing, covered in the next chapter, has a clean weighted form that needs no virtual nodes. Each node gets a score for the key, and the highest score wins. To weight it, use the score -weight / ln(u), where u is a hash of the node and key mapped to the open interval (0, 1). The probability that a node wins is then exactly proportional to its weight.
import math
import hashlib
def _hash(value):
return int(hashlib.md5(value.encode()).hexdigest(), 16)
def weighted_rendezvous(key, weights):
def score(node):
u = ((_hash(f"{node}:{key}") >> 75) + 0.5) / 2**53
return -weights[node] / math.log(u)
return max(weights, key=score)
weights = {"small": 1, "medium": 2, "large": 4}
print(weighted_rendezvous("key42", weights))The shift by 75 bits keeps the top 53 bits of the 128-bit hash, and adding 0.5 keeps u strictly between 0 and 1, so the logarithm is always defined and negative. The cost is that every lookup scores every node, which is O(n) instead of the ring's O(log n). Weights can be real numbers with no rounding step, and the share is exact in expectation.
| Approach | How weight is applied | Share accuracy | Lookup cost |
|---|---|---|---|
| Ring with virtual nodes | Number of positions | Approximate, improves with more positions | O(log V) |
| Weighted rendezvous | Score formula | Exact in expectation | O(n) |
Summary
Weighted consistent hashing gives a node a number of virtual nodes proportional to its weight, so its expected share of the keys is its virtual node count divided by the total. Lookup is unchanged. Reweighting adds or removes only the positions in the difference, so only the minimum fraction of keys moves. Limits to watch are integer rounding, noise for lightly weighted nodes, the fact that weights balance key counts and not hot keys, and the O(n) insert cost on large rings.
Exercise
Three machines have 16 GB, 32 GB and 64 GB of memory. You set the weight to memory divided by 16 and use base_vnodes=50. How many virtual nodes does each machine get, and what share of the keys should each hold in expectation? Then the 16 GB machine is upgraded to 32 GB. Roughly what fraction of all keys moves, and to which node?
Show answer
The weights are 1, 2 and 4, so the virtual node counts are 50, 100 and 200, for a total of 350. The expected shares are 50/350 = 1/7 ≈ 14.3%, 100/350 = 2/7 ≈ 28.6%, and 200/350 = 4/7 ≈ 57.1%. After the upgrade the small machine has weight 2 and 100 virtual nodes, so the total is 400 and its share is 100/400 = 25%. Its share rose from 1/7 to 1/4, so about 25% - 14.3% ≈ 10.7% of the keys move. They all move to the upgraded machine, since the other two machines gained no positions.