Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Concept · 20 min · revision 1

The ring, virtual nodes and replica placement

Place nodes and keys on a hash ring, use exact arc sizes to see why one token per node balances badly and many tokens fix it, and walk the ring to put replicas on distinct nodes and zones.

Contentsand lesson path

What you will learn

  • Implement a hash ring with virtual nodes and measure load balance and key movement when a node is added or removed.
  • Apply consistent hashing to a cache cluster or partitioned store, including replica placement on the ring.

01. Why it matters

The previous lesson measured hash % N moving about 90% of the keys when one node joins a ten-node cluster. The hash ring is the classic fix. Variants of it are used by Amazon's Dynamo, by Apache Cassandra, by memcached client libraries that implement "ketama" hashing, and by Envoy's ring_hash load balancer.

The basic ring has two weaknesses, though. With one position per node it balances badly, and storage systems need several copies of each key, not one. This lesson explains how the ring works, why virtual nodes fix the balance, and how replicas are placed. The next lesson is a lab in which you build the ring and measure it.

02. Keys and nodes on one circle

Take the output range of a 64-bit hash, 0 to 2⁶⁴ − 1, and bend it into a circle so that the largest value is followed by 0 again. Hash each node's name to one or more positions on that circle; each position is called a token. Hash each key onto the same circle. A key belongs to the first token at or after its position, going clockwise. A key that lands after the last token wraps round to the first one. Each token therefore owns the arc between the previous token and itself.

Diagram · a ring with three nodes and two tokens each (not to scale)
ring position, drawn from 0.0 to 1.0; the right end wraps round to the left end

0.0                                                                      1.0
 |-----A#0--------B#0-----------C#0-------A#1------B#1-----------C#1-----|
            k1 ^         k2 ^                            k3 ^      k4 ^

 k1 -> B#0, node B          k2 -> C#0, node C
 k3 -> C#1, node C          k4 -> past the last token, wraps to A#0, node A

To look up a key, a client keeps the tokens in a sorted array and binary-searches it for the key's position. With T tokens that takes about log₂ T comparisons: 10 nodes with 100 tokens each give T = 1,000 and about 10 comparisons. The tokens are derived from node names, for example by hashing node-3#0, node-3#1 and so on, so every client that has the same node list builds exactly the same ring without talking to the others. Storage systems such as Dynamo and Cassandra instead let each node pick its tokens once, store them, and share them with the other nodes.

Here is why the ring moves so few keys. When a node joins, its tokens land inside existing arcs and split them. Only the keys in the part that the new token now owns change hands, and all of them go to the new node. When a node leaves, each of its arcs merges into the arc of the next token clockwise. No other key changes owner. That is monotonicity for joins, and its mirror image for removals, from the previous lesson.

03. Why one token per node is not enough

Random points cut a circle into very uneven pieces. The script below does not sample keys. It sorts the tokens and adds up the exact length of the arcs each node owns, for 10 nodes with 1, 10, 100 and 1,000 tokens each. Then it removes node-3 and reports who takes over its share.

Python 3.12 · ring_arcs.py (standard library only)
"""Exact share of a 64-bit ring owned by each of 10 nodes, for 1 to 1,000 tokens."""
import hashlib

SPACE = 2**64
NODES = [f"node-{i}" for i in range(10)]


def h64(text: str) -> int:
    digest = hashlib.blake2b(text.encode(), digest_size=8).digest()
    return int.from_bytes(digest, "big")


def shares(nodes: list[str], vnodes: int) -> dict[str, float]:
    tokens = sorted((h64(f"{n}#{i}"), n) for n in nodes for i in range(vnodes))
    owned = dict.fromkeys(nodes, 0)
    prev = tokens[-1][0] - SPACE  # the first arc wraps round from the last token
    for position, node in tokens:
        owned[node] += position - prev  # this token owns the arc (prev, position]
        prev = position
    return {n: arc / SPACE for n, arc in owned.items()}


print("tokens/node  smallest  largest  largest/mean")
for vnodes in (1, 10, 100, 1000):
    s = shares(NODES, vnodes).values()
    print(f"{vnodes:>11}{min(s):>10.1%}{max(s):>9.1%}{max(s) * len(NODES):>14.2f}")

print("\nnode-3 leaves; who takes over its share?")
for vnodes in (1, 100):
    before = shares(NODES, vnodes)
    after = shares([n for n in NODES if n != "node-3"], vnodes)
    gains = {n: after[n] - before[n] for n in after if after[n] > before[n]}
    low, high = min(gains.values()), max(gains.values())
    print(f"{vnodes:>4} token(s): node-3 had {before['node-3']:.1%};",
          f"{len(gains)} node(s) take it over, gaining {low:.1%} to {high:.1%}")
Terminal
python3 ring_arcs.py
Expected output
tokens/node  smallest  largest  largest/mean
          1      2.1%    36.9%          3.69
         10      6.5%    15.0%          1.50
        100      8.1%    11.5%          1.15
       1000      9.6%    10.4%          1.04

node-3 leaves; who takes over its share?
   1 token(s): node-3 had 6.4%; 1 node(s) take it over, gaining 6.4% to 6.4%
 100 token(s): node-3 had 11.5%; 9 node(s) take it over, gaining 0.7% to 1.7%

With one token each, the luckiest node owns 36.9% of the ring and the unluckiest 2.1%, a factor of about 17 between them. A perfect hash function cannot fix this, because the problem is where the ten tokens fall, not how keys are hashed. The removal lines show a second weakness: with one token, node-3's whole share goes to a single neighbour, whose load jumps. Adding a node has the mirror problem, since the newcomer relieves only the one node whose arc it lands in.

The fix is to give each physical node many tokens, called virtual nodes or vnodes. Each node's share is then the sum of many small arcs, and the sum averages out. With 100 tokens per node, the largest share is 1.15 times the mean, and node-3's share is spread over all nine remaining nodes when it leaves. The spread shrinks roughly with the square root of the token count: ten times more tokens make it about 3.2 times smaller (√10 ≈ 3.2). Lamping and Veach measured the same pattern, a relative standard deviation of 0.998, 0.315, 0.0997 and 0.0316 for 1, 10, 100 and 1,000 points per bucket.

Virtual nodes also handle machines of different sizes. A node that should carry twice the data gets twice as many tokens; Dynamo chose a node's number of virtual nodes from its capacity, and Envoy's ring hash places each host on the ring a number of times proportional to its weight.

04. Placing replicas on the ring

A store that keeps R copies of each key needs R nodes per key, and every client must find the same ones. The ring gives an ordered list for free: start at the key's position and walk clockwise. In the Dynamo paper, the node that owns the key coordinates it and copies it to the next N − 1 nodes clockwise (Dynamo calls the replica count N). The list of nodes responsible for a key is its preference list.

Virtual nodes add a trap: the next few tokens can belong to the same physical machine, and two copies on one machine are not two copies. Dynamo builds the preference list by skipping positions, so that the list contains only distinct physical nodes. Real deployments go further and skip nodes in a rack or zone that already holds a copy. Cassandra's NetworkTopologyStrategy tries to place replicas in different racks, and Dynamo spreads each preference list over several data centres.

Diagram · building a 3-node preference list (positions are illustrative)
key k hashes to 0.412; the tokens after it, clockwise:

  0.415  node-4  -> copy 1
  0.419  node-4  -> skip: node-4 already holds a copy
  0.431  node-7  -> copy 2
  0.440  node-4  -> skip
  0.452  node-2  -> copy 3, the list is complete: [node-4, node-7, node-2]

Two consequences are easy to miss. First, each node stores about R/N of all keys, not 1/N. With 3 copies on 9 balanced nodes, every node holds a copy of about a third of the keys, so size disks and memory for that. Second, replicas change what "keys that move" means. When a node joins, it becomes one of the R holders for about R/(N + 1) of the keys, roughly R times the share whose first owner changes, even though the data that must be copied to it is still only about 1/(N + 1) of all copies. The lab measures both numbers.

05. Check your understanding

Practice check · 3 questions

Rings, tokens and replicas

Three questions about weights, storage per node and the cost of more tokens.

Q1. Every node on a ring has 100 tokens. You add node F, which has twice the memory of each other node. How do you make F receive about twice as many keys as each other node?
Q2. A store keeps 3 copies of every key on 12 nodes, placed on distinct nodes by a well-balanced ring. It holds 4 TB of unique data. About how much data does each node store?
Q3. A client-side ring has 50 nodes. You raise the tokens per node from 100 to 1,000. What happens to the client's lookups and memory?
Practice only: not graded, not saved, not evidence.

06. Apply it

Before the lab, extend ring_arcs.py in two ways and predict each result first:

  1. Give node-0 twice as many tokens as the others at 100 tokens per node, and check that its share is close to 2/11 (18.2%).
  2. Print the largest/mean ratio for 4,000 tokens per node and compare it with your square-root estimate from the 1,000-token line.

Then do the lab, which builds the ring with lookups and replicas and measures key movement for the skill's practice task.

07. Review prompt

From memory, draw a ring with three nodes and two tokens each, place four keys on it and say which node owns each, including one key that wraps round. Then explain why one token per node gives poor balance, what virtual nodes cost, and how a three-copy preference list avoids putting two copies on one machine.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check