Consistent Hashing Virtual Nodes and Resharding

Replication Sharding and the Capstone · 45 min

System Design · Module 7 · Lesson 3 of 4 · 45 min

Consistent Hashing Virtual Nodes and Resharding

Assign keys on a clockwise ring, calculate which sampled keys move, and distinguish a placement function from a safe live migration.

Explore key movement on the ring →
Changing the owner function is only one step; live data movement must preserve an explicit read and write ownership protocol.

01 The idea

The problem this lesson solves

The ring has A at 20, B at 50 and C at 80. The six key positions are 5,25,35,55,75,95.

Prerequisite: earlier lessons introduce the vocabulary and shared examples used here. Follow the module order.

TokenA node position in the hash space.
Virtual nodeOne of several token positions assigned to a physical node.
Logical partitionA stable ownership unit mapped to a physical server through routing metadata.

02 Worked example

Follow one worked example

Consistent hash ring after adding D at 60clockwise ownerfirst token ≥ keyA 20B 50D 60C 80Add D at token 60Only the range (50, 60] changes owner55 → Dwas owned by C95 → Awraps to token 20Placement is not a live migration protocol.Consistent hash ring after adding D at 60clockwise ownerfirst token ≥ keyA 20B 50D 60C 8055 → D: newly captured range95 → A: wrap around
A at 20: Wraparound owner • B at 50: Owns key 35 • D at 60: New: owns key 55 • C at 80: Remaining range.

Trace the example in order. Follow the same identities, units and state transitions through the diagram and the events below.

1
Place the original tokensThe ring has A at 20, B at 50 and C at 80. The six key positions are 5,25,35,55,75,95.
2
Assign clockwiseTheir owners are A,B,B,C,C,A respectively. Position 95 wraps around to token A at 20.
3
Add D at 60Only the key at 55 moves to D. The owners become A,B,B,D,C,A.
4
State the limitationOne of these six selected keys moved, or 16.7%. This is a result for this toy dataset; it is not a universal guarantee that every new node moves this exact percentage.

Changing the owner function is only one step; live data movement must preserve an explicit read and write ownership protocol.

03 The method

Mechanisms decisions and a guided tutorial

Work through the explanation in order, then apply it in the tutorial. Each comparison names a cost as well as a benefit.

Choice or conceptPurposeBoundary or cost
Ring placementLimited changed rangesStill needs a data-movement protocol
Virtual nodesSmaller distributed rangesMore metadata; hot keys remain
Logical partitionsStable routing unitReliable owner map
Live reshardingMove serving state safelyConcurrent writes and cutover coordination

Use logical partitions to make movement manageable

If application code computes hash(key) modulo the physical node count directly, changing that count remaps many keys. Instead, map to a larger stable set of logical partitions and maintain a versioned mapping from partition to physical owner. A migration copies data, catches up concurrent changes, validates the destination, cuts over routing and retains a rollback path. During the transition, reads and writes must follow an explicit ownership protocol. Copying rows alone is not a resharding strategy.

Read a consistent-hash ring

Hash each key to a position on a circle. Starting at the key position, walk clockwise to the first node token, wrapping around if needed. That token's node owns the key. With tokens A at 20, B at 50 and C at 80, key 35 belongs to B and key 95 wraps to A. Adding D at 60 changes only keys in the interval (50,60] to D. The fraction moved depends on token placement and key distribution; the familiar approximate 1/(N+1) result assumes balanced placement and uniformly distributed keys.

Virtual nodes improve balance but do not cure everything

Give each physical node multiple token positions so its ownership consists of several smaller ranges. This often smooths uneven ranges and makes movement more flexible, at the cost of more metadata. One extremely popular key remains hot under simple ownership even with many virtual nodes. Replication, request coalescing and hot-key-specific serving strategies solve different parts of that problem.

Follow the first clockwise owner

Use a ring from 0 to 99 with A at 20, B at 50 and C at 80. A key at 35 belongs to B because B is the first token at or after 35. A key at 95 wraps to A. Adding D at 60 transfers the interval (50,60] from C to D.

The selected keys 5,25,35,55,75,95 originally map to A,B,B,C,C,A. After adding D they map to A,B,B,D,C,A. One of six selected keys moves. The observed 16.7 percent is a property of this sample and placement, not a universal promise. Expected balanced-fraction claims require suitable assumptions about tokens and key distribution.

Separate balance from popularity

Several virtual nodes per physical owner split ownership into smaller ranges and can smooth uneven placement. A stable set of logical partitions can also be mapped through a directory to physical nodes, making movement explicit and manageable. Both add routing metadata and operational work.

Neither automatically divides one extremely popular key. Uniformly distributed key hashes can still produce highly nonuniform request rates. Measure key concentration and per-owner demand, then choose a hot-key serving strategy independently of the partition-count strategy.

Migrate while writes continue

A live move typically copies the affected data, catches up concurrent changes, verifies the new owner, coordinates cutover and retains a recovery or rollback path. Readers and writers must agree which owner is authoritative during each phase.

If clients independently switch routing at different times without a protocol, writes can diverge or reads can miss data still on the old owner. Version routing metadata and define forwarding, dual-read or other transition behavior carefully. The Python tutorial computes placement only; it deliberately does not implement replication, consensus or migration correctness.

Guided tutorial

1. Assign by hand

Use the original tokens and calculate owners of all six sample keys.

2. Add the token

Find the newly owned interval before rerunning the console.

3. Run Python

Compare the printed owners with your trace.

4. Write migration phases

Name the authoritative writer, catch-up condition and rollback behavior at each phase.

# Python 3: a placement model, not a database cluster
from bisect import bisect_left
ring = [(20, 'A'), (50, 'B'), (60, 'D'), (80, 'C')]
positions = [token for token, _ in ring]
for key in [5, 25, 35, 55, 75, 95]:
    owner = ring[bisect_left(positions, key) % len(ring)][1]
    print(key, owner)
# Expected owners: A B B D C A

05 Cheat sheet

Review the decisions

Use this table to explain the mechanism and its limit without memorizing a product name.

Choice or conceptRememberCheck
Ring placementLimited changed rangesStill needs a data-movement protocol
Virtual nodesSmaller distributed rangesMore metadata; hot keys remain
Logical partitionsStable routing unitReliable owner map
Live reshardingMove serving state safelyConcurrent writes and cutover coordination
TokenA node position in the hash space.
Virtual nodeOne of several token positions assigned to a physical node.
Logical partitionA stable ownership unit mapped to a physical server through routing metadata.

06 Where & why

Check the primary references

Use official references for protocol and implementation details. The questions here are teaching prompts.

Primary reference
PostgreSQL replication

Read PostgreSQL replication

Primary reference
PostgreSQL synchronous replication

Read PostgreSQL synchronous replication

Primary reference
Dynamo paper

Read Dynamo paper

State the implementation version and the workload assumptions when defending your own design.

07 Interview questions

Explain the reasoning out loud

Answer before opening the explanation. The questions progress from vocabulary to decisions and failure behavior.

What does Token mean?
A node position in the hash space.
What does Virtual node mean?
One of several token positions assigned to a physical node.
What does Logical partition mean?
A stable ownership unit mapped to a physical server through routing metadata.
Why does 95 belong to A in this ring?
There is no token at or above 95 before the end, so the clockwise search wraps to the first token at 20.
Does adding a node move every key?
Not under this ring placement. The new token changes ownership of its newly captured range; actual movement depends on placement and distribution.
Why not promise one exact movement percentage?
A finite sample and uneven token positions can differ from a balanced uniform expectation. State the assumptions and observed dataset.
Do virtual nodes fix one viral key?
No. They improve range placement balance, but simple ownership still places that key’s traffic on one serving owner.
What is missing from the Python example?
Durable storage, replication, authority, concurrent-change capture and migration cutover. It is an inspectable placement model only.

08 Practice problems

Practice a new case

Solve the new cases before revealing hints. Complete worked solutions follow the set.

Copies and partitions

Easy
A system has 4 shards and 3 full copies per shard; state the logical partitions and total shard copies.
Follow-up
A copy is not necessarily a separate physical machine.
Show the hint
Multiply only when counting copies.

Wraparound

Easy
Assign key 98 with tokens A=15, B=55, C=85.
Follow-up
State the assumption or edge case that makes the answer correct.
Show the hint
Continue clockwise past the end.

Ring ownership

Medium
For tokens A=10, B=40, C=90, assign keys 5,30,70,95; then add D=60 and name changed keys.
Follow-up
The ring wraps around after 90.
Show the hint
Choose the first token clockwise, including equality.

Move a range

Medium
With A=20, B=50, C=80, add D=65 and identify the new interval.
Follow-up
State the assumption or edge case that makes the answer correct.
Show the hint
The prior clockwise owner loses the captured segment.

Hot key

Medium
All tokens have equal key counts but one key receives 70% of requests; explain the remaining imbalance.
Follow-up
State the assumption or edge case that makes the answer correct.
Show the hint
Key count is different from request demand.

Migration protocol

Hard
Describe the safe-cutover questions when writes continue while a partition moves.
Follow-up
State the assumption or edge case that makes the answer correct.
Show the hint
Copy completion alone is insufficient.

Worked solutions

1. Copies and partitions

There are 4 logical partitions and 12 shard copies. Physical machines depend on how copies are placed.

2. Wraparound

It wraps to A at 15.

3. Ring ownership

Original owners are A,B,C,A. After adding D=60 they remain A,B,C,A: none of these sampled keys lies in (40,60]. A key at 50 would move from C to D. A new node can move data without affecting every sampled set.

4. Move a range

D owns (50,65], previously owned by C. Exact moved-key count requires the actual key distribution.

5. Hot key

Its owner can still be overloaded. More virtual nodes do not split that key’s serving load; use an appropriate freshness-aware hot-key strategy.

6. Migration protocol

Specify the authoritative writer, capture/replay of new changes, readiness verification, routing version, transition reads/writes, cutover condition and rollback behavior. Test delayed clients and failures around the authority switch.