Skip to main content

Consistent Hashing

Learning objectives
  • Explain why hash(key) mod N remaps almost every key when N changes and quantify the damage
  • Describe the hash ring, virtual nodes and replica placement, and compute expected key movement when nodes join or leave
  • Compare ring hashing, jump consistent hash, rendezvous (HRW) hashing, Maglev and fixed hash slots, and pick one for caches, storage shards and load balancers
  • Implement a ring with virtual nodes, jump hash and rendezvous hashing in Go

TL;DR​

  • Mod-N hashing moves ≈ N/(N+1) of keys when you add one node — for a cache cluster, that is a near-total cache flush and a database stampede.
  • Consistent hashing moves only ≈ 1/(N+1) of keys on a join and ≈ 1/N on a leave — the theoretical minimum.
  • On a ring, nodes and keys hash to positions on a circle; a key belongs to the first node clockwise. Virtual nodes (many positions per physical node) even out load and let you weight bigger machines.
  • Jump hash: no memory, perfectly balanced, very fast — but buckets are numbered 0..n−1 and can only be added or removed at the end.
  • Rendezvous (HRW): score every node for each key, pick the highest; minimal disruption, natural top-k replicas, O(N) per lookup.
  • Maglev and fixed hash slots (Redis Cluster's 16,384 slots) trade a little disruption or a small directory for O(1) lookups and operational control.
  • Consistent hashing decides where keys go; it does not move data, fix hot keys, or agree on membership for you.

Why it matters​

  • E-commerce cache tier: before a sale you scale the Redis or Memcached cluster from 10 to 16 nodes. With mod-N client-side sharding, ≈ 87% of keys suddenly map to a different node, every lookup misses, and the catalog database takes the full read load at the worst possible moment (see Caching).
  • Storage: Dynamo-style databases (Cassandra, Riak, DynamoDB's ancestry) place data and replicas with consistent hashing so nodes can join and leave without global reshuffles.
  • Routing with affinity: send all requests for a cart, a WebSocket session, or a per-account rate-limit counter to the same backend, and keep most of them there when the pool scales (see Load Balancing).
  • Interviews: "Design a distributed cache" or "design a key-value store" almost always leads here; SDI Vol. 1 dedicates a chapter to it.

Core concepts​

The problem with mod N​

With node = hash(key) mod N, a key stays on the same node after N → N+1 only if hash mod N == hash mod (N+1), which happens for about 1/(N+1) of keys. So:

ChangeKeys that move with mod NKeys that must move (ideal)
4 → 5 nodes≈ 80%≈ 20%
10 → 11 nodes≈ 91%≈ 9%
10 → 16 nodes≈ 87.5%≈ 37.5%
One of 10 nodes fails (10 → 9)≈ 90%10% (only the dead node's keys)

For 100 M cached keys, scaling 10 → 11 nodes with mod N invalidates ≈ 91 M of them; with consistent hashing ≈ 9 M.

The hash ring​

Map the hash space (say 0 … 2³² − 1) onto a circle. Hash each node to a position; hash each key to a position; the key belongs to the first node clockwise.

  • Join: a new node D at position 2500 takes only the keys between B (1400) and D (2500), previously owned by C. Everyone else is untouched.
  • Leave: when B dies, only B's keys move — to the next node clockwise (C).

Virtual nodes​

With one position per node, arcs are uneven: some nodes own several times the average share, and when a node leaves, its entire load lands on one neighbour. Virtual nodes fix both:

  • Each physical node gets V positions (tokens), for example nodeA#0 … nodeA#199.
  • Load per node becomes the sum of many small arcs, so the spread narrows — roughly in proportion to 1/√V. A few hundred vnodes per node typically brings imbalance down to around ten percent (rough; depends on hash and node count).
  • When a node leaves, its arcs are scattered around the ring, so its load spreads over many remaining nodes.
  • Heterogeneous hardware: give a machine with twice the memory twice the vnodes.
  • Cost: a larger sorted token table (N × V entries) and more metadata to gossip in storage systems.

Rebalancing maths​

With K keys and N nodes (assuming even spread):

  • Adding one node: expected keys moved ≈ K/(N+1). The new node takes a fair share from (many) existing nodes.
  • Removing one node: expected keys moved ≈ K/N — exactly the removed node's keys.
  • Adding m nodes at once: ≈ K × m/(N+m).
  • Data volume, not just keys: for a storage cluster with 60 TB on 12 nodes, adding a 13th moves ≈ 60/13 ≈ 4.6 TB. At an effective 200 MB/s of rebuild bandwidth, that is ≈ 6–7 hours of streaming — which is why storage systems throttle rebalancing and why you add capacity before you need it.

Replica placement on the ring​

To store R replicas, walk clockwise from the key's position and take the next R distinct physical nodes (skipping vnodes of nodes already chosen). Dynamo calls this the preference list. Production systems also skip nodes in the same rack or availability zone so a single failure domain cannot hold all replicas.

Jump consistent hash​

Lamping and Veach (Google, 2014) published a hash that maps a 64-bit key to a bucket in [0, n) with no memory, about ln(n) iterations, perfectly even spread, and the minimal-movement property when n grows. The catch: buckets are just numbers. You can add bucket n or remove bucket n−1, but you cannot remove bucket 3 out of 10 without renumbering. That fits sharded storage where shards are numbered and each shard is itself replicated (a "failed" shard is handled by its replicas, not by removing it from the hash). It does not fit a cache cluster where arbitrary nodes come and go.

Rendezvous (highest random weight) hashing​

Thaler and Ravishankar's HRW hashing (1990s): for a key, compute score = hash(key, node) for every node and choose the node with the highest score.

  • Minimal disruption: removing a node only moves keys for which it was the winner; adding a node only steals keys where it now wins.
  • Natural replicas: the top-k scores give k replicas, already well spread.
  • Weights: a standard weighted variant scales scores by node capacity.
  • Cost: O(N) hash computations per lookup — trivial for tens of nodes, noticeable for thousands (hierarchical variants exist). No shared table to build or keep in sync, just the node list.

Maglev hashing and fixed slots​

  • Maglev (Google's software load balancer, NSDI 2016) builds a lookup table of prime size M where each backend fills slots following its own permutation. Lookups are O(1) and load is near-perfectly even; disruption on change is small but not strictly minimal. Envoy offers both RING_HASH and MAGLEV load-balancing policies.
  • Fixed hash slots: Redis Cluster hashes keys with CRC16 into 16,384 slots and assigns slots to nodes. It is not a ring, but it gives the same benefit — rebalancing moves whole slots — plus explicit, operator-controlled placement. It is effectively the logical-shard pattern from Database Replication & Sharding.
  • Kafka assigns a keyed message to hash(key) mod partitions. Adding partitions therefore changes which partition existing keys map to and breaks per-key ordering across the change — plan partition counts up front (see Message Queues & Event Streaming).

Where it is used​

SystemSchemeNotes
Amazon Dynamo (2007 paper)Ring with virtual nodes, preference listsPaper also describes moving to fixed, equal-sized partitions to simplify operations
Apache CassandraToken ring with vnodes (num_tokens)Default token count and allocation algorithm vary by version
RiakRing of fixed partitions claimed by nodes
Memcached client librariesRing (for example the "ketama" scheme)The server knows nothing; clients must agree on membership
Envoy, HAProxyRing hash, Maglev; HAProxy supports bounded-load hashingAffinity routing in proxies
Redis Cluster16,384 fixed slotsSlot map, not a ring
Apache IgniteRendezvous affinity functionHRW for partition placement

Trade-offs​

SchemeStrengthsWeaknessesChoose when
Mod NTrivial, perfectly evenRemaps almost everything on changeN never changes, or data can be rebuilt cheaply
Ring + virtual nodesMinimal movement, weights, arbitrary joins/leavesToken table memory, imbalance unless V is largeCaches, Dynamo-style stores, affinity routing
Jump hashNo memory, fast, perfectly evenOnly add/remove at the end; numeric bucketsNumbered shards that are individually replicated
Rendezvous (HRW)Minimal movement, simple, top-k replicas, weightsO(N) per lookupTens to hundreds of nodes, replica selection
MaglevO(1) lookup, very evenSlightly more than minimal disruption, table rebuildsHigh-throughput L4/L7 load balancers
Fixed slots / logical shardsOperator control, simple rebalancing unitNeeds a slot map distributed to clientsRedis Cluster, sharded databases
Bounded-load consistent hashingCaps any node at (1 + ε) × average loadSome keys spill to non-preferred nodesHot keys with affinity routing

In practice​

  • Hash function: use a fast, well-mixing non-cryptographic hash (xxHash, MurmurHash3, or FNV followed by a finaliser). Cryptographic hashes are unnecessary and slower; weak hashes cluster vnodes.
  • Vnode count: ≈ 100–256 per node is a common starting point for caches; storage systems tune it with token-allocation algorithms instead of brute force.
  • Membership agreement is the real problem. Every client must see the same node list, or the same key goes to different nodes. Distribute membership from one source (service discovery, a config service, gossip with versioning) and change it deliberately.
  • Replication and hot keys still need handling: consistent hashing spreads keys, not traffic per key. A flash-sale product key still lands on one node; use bounded loads, key replication or L1 caches.
  • A ring with virtual nodes in Go:
package chash

import (
"hash/crc32"
"slices"
"strconv"
)

// Ring is a consistent-hash ring with virtual nodes. Not safe for concurrent
// mutation; build a new Ring and swap it atomically on membership change.
type Ring struct {
vnodes int
points []uint32 // sorted vnode positions
owner map[uint32]string // position -> physical node
}

func NewRing(vnodes int) *Ring {
return &Ring{vnodes: vnodes, owner: make(map[uint32]string)}
}

func pos(s string) uint32 { return crc32.ChecksumIEEE([]byte(s)) }

func (r *Ring) Add(node string) {
for i := 0; i < r.vnodes; i++ {
p := pos(node + "#" + strconv.Itoa(i))
if _, taken := r.owner[p]; taken {
continue // rare collision: skip this vnode
}
r.owner[p] = node
r.points = append(r.points, p)
}
slices.Sort(r.points)
}

func (r *Ring) Remove(node string) {
kept := r.points[:0]
for _, p := range r.points {
if r.owner[p] == node {
delete(r.owner, p)
continue
}
kept = append(kept, p)
}
r.points = kept
}

// Get returns the node owning key: the first vnode clockwise from its position.
func (r *Ring) Get(key string) (string, bool) {
if len(r.points) == 0 {
return "", false
}
i, _ := slices.BinarySearch(r.points, pos(key))
if i == len(r.points) {
i = 0 // wrap around the ring
}
return r.owner[r.points[i]], true
}
  • Jump hash and rendezvous in Go are each a dozen lines:
package chash

import "hash/fnv"

// JumpHash maps key to a bucket in [0, numBuckets) (Lamping & Veach, 2014).
func JumpHash(key uint64, numBuckets int32) int32 {
var b, j int64 = -1, 0
for j < int64(numBuckets) {
b = j
key = key*2862933555777941757 + 1
j = int64(float64(b+1) * (float64(int64(1)<<31) / float64((key>>33)+1)))
}
return int32(b)
}

// Rendezvous returns the node with the highest score for key.
func Rendezvous(key string, nodes []string) string {
var best string
var bestScore uint64
for _, n := range nodes {
h := fnv.New64a()
h.Write([]byte(n))
h.Write([]byte{0})
h.Write([]byte(key))
if s := mix(h.Sum64()); best == "" || s > bestScore {
best, bestScore = n, s
}
}
return best
}

// mix is the MurmurHash3 64-bit finaliser; it improves FNV's bit diffusion.
func mix(x uint64) uint64 {
x ^= x >> 33
x *= 0xff51afd7ed558ccd
x ^= x >> 33
x *= 0xc4ceb9fe1a85ec53
x ^= x >> 33
return x
}

Common pitfalls​

  • Client-side mod-N sharding of a cache, then scaling during peak. Symptom: hit ratio collapses to near zero, DB CPU spikes, sale page errors.
  • Clients disagree on membership. Symptom: duplicated or inconsistent cache entries, invalidations that "do not work" because they went to a different node than the write.
  • Too few vnodes. Symptom: one node holds twice the average keys and runs out of memory first.
  • Assuming consistent hashing moves the data. It only computes ownership. Symptom: after a join, the new node answers "not found" for keys it now owns until data is streamed to it (storage) or warmed (cache).
  • Adding Kafka partitions to a keyed topic. Symptom: per-account event ordering breaks for in-flight keys because they now map to a different partition.
  • Ignoring hot keys. Symptom: perfectly balanced key counts, one node at 100% CPU.
  • Using a weak hash. Symptom: vnodes cluster, imbalance far worse than expected.

Interview angle​

  • Where it appears: distributed cache, key-value store, URL shortener storage, chat server routing, sharded rate limiter, CDN request routing.
  • Strong answer covers: the mod-N failure with a number, the ring and clockwise ownership, virtual nodes and why, replica placement across failure domains, what happens on join/leave (including data movement), and alternatives (rendezvous, jump, slots) with a reason for the choice.
  • Follow-ups: "How many keys move when you add a node?", "How do you handle heterogeneous machines?", "How do clients learn about membership changes?", "What about hot keys?", "Why does Redis Cluster use slots instead?"
  • Red flags: drawing the ring without explaining vnodes; claiming it solves hot keys; forgetting that data must be copied; no answer for how clients agree on the ring.

Self-check​

1. Show why adding one node to a mod-N cluster of 4 moves about 80% of keys.

A key stays put only if h mod 4 == h mod 5. Over the 20 residues of h mod 20, that holds only for 0–3, i.e. 4 of 20 = 20%. So ≈ 80% of keys change node. In general, going from N to N+1 keeps ≈ 1/(N+1) of keys in place, the opposite of what you want.

2. What two problems do virtual nodes solve, and what do they cost?

They even out the share of the ring each physical node owns (many small arcs instead of one random arc), and they spread a departing node's load over many survivors instead of one neighbour. They also allow weighting by capacity. The cost is a larger token table and more membership metadata to store and propagate.

3. A 12-node storage cluster holds 60 TB. Estimate the data moved when adding a node and how long it takes at 200 MB/s.

The new node takes ≈ 1/13 of the data: 60/13 ≈ 4.6 TB. At 200 MB/s that is ≈ 4.6 × 10⁶ MB / 200 MB/s ≈ 23,000 s ≈ 6.4 hours. Plan the expansion ahead of peak and throttle streaming to protect foreground latency.

4. When would you choose jump hash over a ring, and when not?

Choose jump hash for numbered storage shards that are each replicated and only ever grow at the end: zero memory, perfectly even, very fast. Do not use it where arbitrary members fail or are removed (cache nodes, backends), because removing a bucket from the middle renumbers others and moves many keys.

5. How does rendezvous hashing give you replicas, and what is its lookup cost?

Compute a score for every node for the key and sort; the top k nodes are the k replicas. When a node disappears, only keys for which it was in the top k change. The cost is O(N) hashes per lookup, fine for tens or hundreds of nodes.

6. Scenario: you route per-account rate-limit counters to 8 Redis nodes with a ring. Before a sale you add 4 nodes. What happens to rate limiting, and how do you make it safe?

≈ 1/3 of accounts move to new nodes whose counters start empty, so those accounts briefly get a fresh allowance. For rate limiting that is usually acceptable (it is a short over-allowance), but for stricter limits you can pre-warm or dual-read old and new owners during a transition window, or add nodes well before the sale. For money limits (daily transfer caps) do not use cache-style counters at all — keep them in the ledger database.

🧠 Flashcards0/8 learned · 0 retries

Exercise​

  1. Implement the Ring above plus a small benchmark harness: insert 1 M random keys over 10 nodes with V = 1, 10, 100, 500 vnodes. Report the max/average key ratio per node for each V.
  2. Add an 11th node and measure the fraction of keys that changed owner; compare with mod-N hashing on the same keys.
  3. Repeat step 2 with Rendezvous and JumpHash (map node index to bucket). Record lookup time with go test -bench.
  4. Write two paragraphs: which scheme you would use for (a) a client-side Redis cache tier and (b) a sharded order database, and why.

Done looks like: a table of V vs imbalance, movement percentages within a point or two of the theoretical values, benchmark numbers, and a justified choice.

Further reading​

  • Karger et al., "Consistent Hashing and Random Trees" (STOC 1997) — the original paper.
  • DeCandia et al., "Dynamo: Amazon's Highly Available Key-value Store" (SOSP 2007), sections on partitioning and replication.
  • Lamping & Veach, "A Fast, Minimal Memory, Consistent Hash Algorithm" (2014, arXiv).
  • Thaler & Ravishankar, "Using Name-Based Mappings to Increase Hit Rates" (IEEE/ACM Transactions on Networking, 1998) — rendezvous hashing.
  • Eisenbud et al., "Maglev: A Fast and Reliable Software Network Load Balancer" (NSDI 2016).
  • Mirrokni, Thorup, Zadimoghaddam, "Consistent Hashing with Bounded Loads" (SODA 2018).
  • System Design Interview, Vol. 1 (Alex Xu), Ch. 5 "Design Consistent Hashing".
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).