HLDTraffic & Scaling7 min read

Consistent Hashing Explained Visually

Why modulo hashing collapses when a cache node dies, and how hash rings with virtual nodes bound rebalancing to 1/N.

Kshitij SinghKshitij SinghUpdated 2026-12-03
Animated consistent hashing architecture and hash ring diagram — 1. Why modulo hashing (hash % N) breaks on node failureVisual diagram comparing modulo hashing across cache shards with a circular consistent hash ring, showing clockwise key routing, node removal impact, and virtual nodes.. Say you split 10M keys across 4 cache nodes with modulo hashing: hash(key) % 4. Server S1 dies, so N drops from 4 to 3. Almost every key now computes a different remainder (~75% move). Millions of lookups miss at once and crush your Primary DB.REQUEST ROUTINGHASH RING SPACE (0 → 2³²-1)ORIGIN FALLBACK0°90°180°270°HASH RINGCW ↻ 0 → 2³²-1S0S1 ✕S2S3K1K2K3K4hash(key)Node ANode BMiss FloodHash RouterApp / Envoy Proxyhash % 3 ❌API Traffic40K Key Lookups/sCache Node ARing @ 30°Cache Node BRing @ 150°CRASHEDPrimary DBMiss Fallback75% MISS FLOOD40K req/s30K DB MISS/s
Animated consistent hashing architecture and hash ring diagram — 1. Why modulo hashing (hash % N) breaks on node failure
1 / 5

1. Why modulo hashing (hash % N) breaks on node failure

Say you split 10M keys across 4 cache nodes with modulo hashing: hash(key) % 4. Server S1 dies, so N drops from 4 to 3. Almost every key now computes a different remainder (~75% move). Millions of lookups miss at once and crush your Primary DB.

Modulo hashing ties every key’s location directly to N. Change N by one and the whole map scrambles.

Keys Remapped
75.0%
Catastrophic
Cache Hit Rate
24.8%
-71% drop
DB CPU Load
99%
Outage Risk
Formula
hash % N
N: 4 → 3
Read all 5 diagram steps as text
  1. 1. Why modulo hashing (hash % N) breaks on node failure

    Say you split 10M keys across 4 cache nodes with modulo hashing: hash(key) % 4. Server S1 dies, so N drops from 4 to 3. Almost every key now computes a different remainder (~75% move). Millions of lookups miss at once and crush your Primary DB.

  2. 2. Place both servers and keys on a circular hash ring

    Consistent hashing bends the 32-bit hash space (0 to 2³² - 1) into a circular hash ring. You hash each server’s ID onto the ring (S0 at 30°, S1 at 120°, S2 at 210°, S3 at 300°), then hash every data key onto the same circle with the same hash function.

  3. 3. Walk clockwise from the key to its owning server

    Key K1 hashes to 75°. Walking clockwise hits S1 at 120°, so S1 owns K1. Key K2 at 255° walks clockwise to S3 at 300°. In code, servers sit in a sorted array so finding the first point >= hash(key) is a fast O(log N) binary search.

  4. 4. Server S1 crashes, and rebalancing moves only 1/N (25%) of keys

    When S1 at 120° goes down, K1 (at 75°) walks past the dead spot and lands on S2 at 210°. Keys on S0, S2, and S3 never move. Rebalancing affects only K/N (25%) of keys instead of 75%, keeping the Primary DB stable.

  5. 5. Virtual nodes fix uneven arcs and hot-neighbor failover

    A raw ring has two bugs: 4 random points create lopsided arcs, and when S1 dies, 100% of its load hits one neighbor (S2). Virtual nodes fix both. Each physical box gets 100–200 hashed points around the ring (A#1, A#2...), keeping standard deviation under 5% and spreading failure load across all survivors.

Architecture Flow Summary

Save image
Consistent hashing architecture infographic comparing Modulo Hashing (75% keys remapped when node S1 fails) against a Consistent Hash Ring with virtual nodes where only 1/N (25%) of keys move clockwise to S2
Modulo hashing vs. Consistent Hash Ring with virtual nodes when server S1 goes offline.

How a Consistent Hash Ring Looks in Real Code

Under the hood, a consistent hash ring is tiny: one sorted slice of uint32 hashes plus a map from each hash point back to a physical server name. Registering a server means hashing "redis-01#0" through "redis-01#149" with a fast, non-cryptographic hash like MurmurHash3, xxHash, or CRC32 (avoid slow SHA-1 or SHA-256).

At request time, compute the key hash and binary-search the sorted slice. If the key hash is larger than the last entry, wrap around to index 0. The whole lookup runs in ~50 nanoseconds inside CPU cache.

Minimal Consistent Hash Ring Lookup in Gogo
func (r *HashRing) GetNode(key string) string {
    h := crc32.ChecksumIEEE([]byte(key))
    idx := sort.Search(len(r.sortedHashes), func(i int) bool {
        return r.sortedHashes[i] >= h
    })
    if idx == len(r.sortedHashes) {
        idx = 0 // wrap around the ring
    }
    return r.vnodeToServer[r.sortedHashes[idx]]
}

How Production Systems Adapt Consistent Hashing

Most real infrastructure uses consistent hashing or a close cousin with practical tweaks:

  • DynamoDB & Apache Cassandra (Clockwise Replication)

    Each key is stored on the first R distinct physical servers clockwise, skipping repeated virtual nodes on the same machine or availability zone.

  • Redis Cluster (16,384 Hash Slots)

    Redis maps keys via CRC16(key) % 16384 into fixed slots and assigns slot ranges to shards. Scaling migrates specific slots without rehashing untouched keys.

  • Envoy & NGINX (Sticky Sessions via Ring Hash / Maglev)

    Edge proxies use consistent hashing for sticky sessions to stateful backends (WebSocket gateways or servers with warm local caches) with minimal churn during deploys.

  • Rendezvous Hashing (Highest Random Weight)

    Scores every node using hash(key, node_id) and picks the highest score. Needs zero ring memory and handles weights cleanly, at O(N) lookup cost per request.

What Consistent Hashing Cannot Fix: The Celebrity / Hot-Key Problem

Virtual nodes balance the number of keys per shard, not requests per key. In the classic celebrity problem (or a flash-sale SKU getting 50,000 RPS), every request for that hot key hashes to the exact same point on the ring and melts one shard.

Handle hot keys separately: put a 2–5 second in-process L1 LRU cache on your app servers, or salt hot read keys (sku#0..sku#9) across multiple shards.

Virtual Nodes & Memory Sizing (20-Node Cache)

You run a 20-node cache cluster storing 10 million objects and need to pick V (virtual nodes per server).

  • Physical servers (N): 20
  • Cached keys (K): 10,000,000
  • Load standard deviation scales roughly as 1 / sqrt(V)
  • Each ring entry uses ~16 bytes (uint32 hash + pointer)
Keys Moved on 1 Failure
K / N = 10M / 20
500K keys (5% vs 95% modulo)
Load Variance at V = 150
1 / sqrt(150) ≈ 0.08
~5–8% spread across nodes
Router Ring RAM Footprint
20 × 150 × 16 bytes
48 KB (fits in CPU L2 cache)
Lookup Comparisons
log2(3,000)
~12 comparisons (<50 ns)

100–200 virtual nodes per server is the practical sweet spot: tight balance, <50KB table size, and sub-microsecond lookups.

Modulo vs. Hash Ring vs. Rendezvous Hashing vs. Jump Hash

Pick the partitioning scheme based on cluster size, arbitrary node removal needs, and router memory.

StrategyKeys Moved on ResizeLookupMemoryBest Fit
Modulo (hash % N)Up to (N-1)/N (~95%)O(1)O(1)Fixed shard count that never changes
Consistent Ring + vNodes~K / NO(log(N × V))O(N × V) (~50KB)Memcached, Cassandra, Envoy routing
Rendezvous Hashing (HRW)~K / N (exact)O(N)ZeroSmall-to-medium clusters (<100 nodes) needing zero ring state
Hash Slots (Redis)Only migrated slotsO(1) table lookup16,384 slotsManaged cluster with explicit slot moves
Jump Consistent Hash~K / N (exact)O(ln N)ZeroNumbered buckets 0..N-1 (no arbitrary removals)

Quick Check

1. A 10-node consistent hashing cache runs WITHOUT virtual nodes. One node crashes at peak traffic. What happens to the other 9?

2. One flash-sale key "iphone-17-pro" hits 80,000 RPS on a 16-node Redis cluster with 200 vNodes per shard. One shard CPU hits 100%. Why?

Cheat Sheet

When to use it

  • Distributed caches (Redis/Memcached) where scaling must not trigger DB miss storms.
  • Partitioned NoSQL stores (Cassandra, DynamoDB) with clockwise replication.
  • Sticky sessions in Envoy/NGINX for WebSocket gateways or servers with warm local caches.

When to skip it

  • Plain stateless HTTP pods where least-connections balancing is simpler and spreads load better.
  • Trying to fix a single viral hot key or celebrity account (use L1 local cache or key salting instead).
vNodes / server
100 – 200
Modulo remap (4→3)
~75% moved
Ring remap (N nodes)
~1/N moved
Ring space
0 to 2³² - 1
Lookup cost
O(log(N × V))
Redis Cluster slots
16,384

Common mistakes

  • Stopping at the basic ring and forgetting Virtual Nodes (uneven arcs + neighbor overload).
  • Saying consistent hashing solves the celebrity hot-key problem.
  • Using slow cryptographic hashes like SHA-256 instead of xxHash, MurmurHash3, or CRC32.

FAQ

Why is consistent hashing better than modulo hashing (hash % N)?
With modulo hashing, losing or adding one server changes N and remaps up to (N-1)/N of all keys, flooding your database with cache misses. Consistent hashing limits rebalancing to roughly K/N keys.
What do virtual nodes do and how many should I pick?
Virtual nodes place each physical server at multiple points around the hash ring (like S1#0 to S1#149). This keeps key distribution even and spreads failover traffic across every survivor. 100 to 200 per server works well in production.
How does consistent hashing compare to Rendezvous Hashing?
Consistent hashing needs an O(N × V) ring table in memory and does O(log(N × V)) lookups. Rendezvous Hashing (Highest Random Weight) needs zero ring memory and computes hash(key, node) across all N nodes in O(N) time, making it great for smaller clusters.
Does Redis Cluster use consistent hashing?
Redis Cluster uses 16,384 fixed hash slots via CRC16(key) % 16384 and assigns slot ranges to master shards. Scaling migrates individual slots online without recalculating keys on untouched shards.
Does consistent hashing solve the celebrity or hot-key problem?
No. Every request for the same viral key hashes to the same shard regardless of virtual nodes. Handle hot keys with short-TTL local L1 caches on app servers or salted read copies.