Consistent Hashing
"The principle advantage of consistent hashing is that departure or arrival of a node only affects its immediate neighbors and other nodes remain unaffected." — DeCandia et al., Dynamo: Amazon's Highly Available Key-value Store, SOSP 2007, section 4.2
Summary: Consistent hashing places keys and nodes on the same circle of hash values so that adding or removing a node moves only the keys next to it (about K/n of K keys) instead of nearly all of them as hash(key) % n does. Focus: The hash ring, virtual nodes (tokens), replication along the ring, hotspots, bounded-load hashing, jump hash, rendezvous (HRW) hashing, Maglev, fixed hash slots (Redis Cluster's 16384), resharding cost, and what each product really does. Learning goal: Choose a placement scheme for a cache, a sharded database or a load balancer, predict how many keys move and how uneven the load will be, and read the numbers off a measured Go experiment.
This page is the complete reference for hash-based placement of keys on a changing set of nodes. It owns the ring, virtual nodes, rendezvous hashing, jump hash, Maglev, bounded loads, resharding cost and the Cassandra / Dynamo / Redis Cluster differences. It does not re-teach declarative partitioning and shard keys in PostgreSQL (Partitioning & Sharding in PostgreSQL), the scale ladder (Storage & Data Scaling), the Dynamo-style data model and quorums (Wide-Column & Key-Value at Scale), Redis data types (Redis), replication (Replication, Read Replicas & Failover) or probabilistic structures (Bloom Filters).
Page map
| If you are looking for | Go to |
|---|---|
| A table you can memorise in one minute | Everything in one minute |
Why hash(key) % n is not enough | Why consistent hashing exists |
| Karger 1997, Dynamo, rendezvous, ketama, jump hash, Maglev, bounded loads | Where it comes from |
| One scheme with a timeline and the fix in SQL, Go and Laravel | The concepts, one by one |
| What PostgreSQL, MySQL, Cassandra, Redis, MongoDB, Kafka, nginx, HAProxy, Envoy really do | Per-product behaviour |
| Token ranges, preference lists, gossip, hash tags, error replies | Mechanics |
| Memcached, Redis, Cassandra and cache-tag recipes | Solving the classic problems |
| Which scheme for which workload | Choosing a scheme |
| Monolith, microservices, replicas, 1x to 100x | In architecture |
| Reproduce the numbers on this page | Lab |
| Wrong beliefs, cheat sheet, every term defined | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The schemes. Every row is unpacked in the concepts section. "Moves" is the share of keys that change owner when one node is added to n.
| Scheme | One-line idea | Moves on join | Balance | Memory per client | Lookup cost | Used by |
|---|---|---|---|---|---|---|
Modulo hash(key) % n | Position in the node list | about n/(n+1) (86% for 6 to 7) | Perfect | O(n) list | O(1) | Kafka default partitioner, PostgreSQL / MySQL hash partitions, gomemcache |
| Hash ring, 1 token per node | Node owns the arc before its point | about 1/(n+1) | Poor (max/mean about 2.6 at 6 nodes) | O(n) | O(log n) | Textbook form |
| Hash ring with virtual nodes (tokens) | Many points per node | about 1/(n+1) | Good with 100+ tokens | O(n x T) | O(log nT) | Dynamo, Cassandra, Riak, ketama, Envoy ring_hash |
| Fixed hash slots | Key to slot by hash, slot to node by table | Exactly the slots you move | Whatever you assign | O(slots) | O(1) | Redis Cluster (16384), Dynamo strategy 3, Couchbase vBuckets, Citus shards |
| Jump consistent hash | Keys "jump" to a new bucket with probability 1/(n+1) | exactly 1/(n+1) | Near perfect | none | O(ln n) | Sharded stores with numbered shards |
| Rendezvous (HRW) | Every node scores the key, top score wins | about 1/(n+1) | Near perfect | O(n) names | O(n) | Caches, CDNs, top-k replica choice |
| Maglev | Big lookup table filled by permutations | about 1/(n+1) plus a little extra | Near perfect | O(M) table | O(1) | Google Maglev, Envoy maglev |
| Bounded-load ring | Ring plus a capacity cap ceil(c x average) | a little more than a plain ring | Capped at c x mean | ring + counters | O(log nT) plus probing | HAProxy hash-balance-factor |
The numbers that matter (measured in the lab, 120,000 keys, 6 nodes, node 7 added):
| Scheme | Keys moved | Moved to a node that is not the new one | max/mean load at 6 nodes |
|---|---|---|---|
| Modulo | 85.6% | 71.3% (85,601 keys shuffled between old nodes) | 1.0x |
| Ring, 1 token | 15.9% | 0 | 1.47x in this run, 2.56x on average |
| Ring, 16 tokens | 16.2% | 0 | 1.62x in this run, 1.35x on average |
| Ring, 256 tokens | 15.3% | 0 | 1.18x in this run, 1.10x on average |
| Jump hash | 14.2% | 0 | 1.01x |
| Rendezvous | 14.3% | 0 | 1.01x |
| Maglev (65537 slots) | 14.6% | 288 keys | 1.02x |
The three things to do.
| Situation | Do this |
|---|---|
| A cache tier that grows and shrinks (Memcached, Redis as cache) | Ketama ring (100-200 points per server, weighted) or rendezvous hashing; never modulo |
| A database that must rebalance in the background | A fixed number of small partitions (slots, vnodes, shards) and a table that maps partition to node; move partitions, not keys |
| A load balancer with sticky keys and uneven traffic | Consistent hashing plus a bounded load factor (HAProxy hash-balance-factor 125 to 200) or Maglev |
Why consistent hashing exists
You have a set of nodes and a stream of keys. Every client must agree, without asking anyone, which node holds a key. The obvious answer is node = hash(key) % n. It balances perfectly and costs nothing, until n changes. Then hash(key) % n and hash(key) % (n+1) agree only for about one key in n+1, so nearly every key changes owner: a cache loses its whole content in a second, a sharded database has to copy almost all its data. Karger et al. describe the failure in their 1997 paper: "When the range of the hash function (p in the example) changed, almost every item would be hashed to a new location. Suddenly, all cached data is useless because clients are looking for it in a different location."
| Simple (modulo) | Consistent |
|---|---|
| One line, no state, perfect balance | State (ring, table or node list), balance is statistical or engineered |
Changing n moves about n/(n+1) of the keys | Changing n moves about 1/(n+1) of the keys |
Every client needs the same n at the same instant | Clients with slightly different node lists mostly agree (Karger's "spread" property) |
| Fine for a fixed set of shards you never resize | Needed when nodes come and go: caches, autoscaling, failures |
| Hash functions can be weak | The hash function must mix bits well, because positions are compared, not just reduced |
The analogy we reuse on this page: a circular street of pharmacies. Every house has a number on the circle; a courier delivers a parcel to the first pharmacy clockwise from the house. When a new pharmacy opens, it only takes over the parcels of the stretch just before it. With modulo hashing, instead, opening one pharmacy re-numbers all pharmacies and every house is reassigned. Virtual nodes are chains: one company opens many small branches spread around the circle, so when it closes, its work spreads over many neighbours instead of dumping on one.
Three common misunderstandings, up front
- "Consistent hashing balances load." It minimises movement. Balance comes from virtual nodes, from engineered tables (Maglev, slots) or from a cap (bounded loads). A bare ring with one point per node is uneven: measured here, max/mean 2.56 on average and 4.04 worst over 20 clusters of 6 nodes.
- "Consistent hashing means no data moves." Only about
1/(n+1)of the keys move, but they still have to be streamed, and something must decide when the old copy may be deleted (Cassandranodetool cleanup). Movement is cheap, not free. - "It is a database feature." PostgreSQL and MySQL hash partitioning use plain modulo; Kafka's default partitioner uses
murmur2(key) % numPartitions; DynamoDB and MongoDB hash internally and rebalance chunks. Real consistent hashing lives in Dynamo-style stores, Redis Cluster (as fixed slots), client libraries and load balancers.
Where it comes from
1997, Karger, Lehman, Leighton, Panigrahy, Levine and Lewin at MIT introduced consistent hashing for web caches that "relieve hot spots": clients with different, partial views of the set of caches should still map an object to a small set of caches. Their definition: "When a machine is added to or removed from the set of caches, the expected fraction of objects that must be moved to a new cache is the minimum needed to maintain a balanced load across the caches." They call this property smoothness, and add two more, "spread" (over all client views, how many different caches one object is assigned to) and "load" (how many distinct objects one cache is assigned). The company Akamai grew out of this work (a secondary-source remark; the paper itself is about the protocol).
1996 and 1998, Thaler and Ravishankar (University of Michigan) invented rendezvous hashing, also called Highest Random Weight (HRW): every client scores every server for a key and picks the highest. The technical report CSE-TR-316-96 and the 1998 IEEE/ACM Transactions on Networking paper "Using Name-Based Mappings to Increase Hit Rates" describe it (the Wikipedia article is the secondary source used here for the dates).
Around 2007, ketama (Last.fm) replaced modulo mapping in memcached clients. The README says: "Previously, clients mapped keys->servers like this: server = serverlist[hash(key)%serverlist.length]; This meant that whenever we added or removed servers from the pool, everything hashed to different servers, which effectively wiped the entire cache." It hashes each server to "several (100-200)" points on a circle called the continuum. Libketama-compatible clients exist in every language.
2007, Dynamo (Amazon, SOSP) made the ring the storage layer: virtual nodes called tokens, a preference list of N distinct nodes, and later three partitioning strategies (section 6.2) because random tokens made bootstrapping and archiving painful. Cassandra and Riak inherited the design; Cassandra's documentation says it "maps every node to one or more tokens on a continuous hash ring".
2014, Lamping and Veach (Google) published jump consistent hash, "a fast, minimal memory, consistent hash algorithm that can be expressed in about 5 lines of code".
2016, Maglev (Google, NSDI) introduced a lookup-table consistent hash for network load balancers, and Mirrokni, Thorup and Zadimoghaddam (Google) introduced consistent hashing with bounded loads, now in HAProxy and several proxies.
Redis Cluster (2015, Redis 3.0) chose a different route: not a ring but 16384 fixed hash slots, with an explicit slot-to-node table.
Hash ring versus hash slots
A ring and a slot table are two ways to remember "which node owns which part of the hash space". A ring derives the table from node names (every client can compute it); slots store the table explicitly (someone must distribute it). Dynamo's strategy 3 is the bridge: "Q/S tokens per node, equal-sized partitions". Section Hash slots covers it.
The concepts, one by one
Each block follows the same order: plain words, the usual wrong belief, the definition, a timeline, real scenarios, what provides it per product, and the fix with SQL, Go and Laravel. The Go code for every block is one small standard-library module, academy/consistent-hashing, and the PHP files are Laravel 13 / PHP 8.3.
Modulo hashing, and why it breaks Must-know
In plain words: you number the servers 0 to n-1 and send each key to server hash(key) mod n. It is perfectly even and needs no memory. When n changes, nearly every key lands on a different server.
Common misunderstanding: "A good hash function makes resizing cheap." The hash is not the problem; the mod n is. For h mod n and h mod (n+1) to agree the key must satisfy a coincidence that happens for about 1/(n+1) of keys, whatever the hash.
Definition: owner(key) = nodes[H(key) mod n]. Going from n to n+1 nodes moves a fraction n/(n+1) of the keys, and, unlike consistent hashing, they move between old nodes too.
key h mod 6 h mod 7 verdict (adding a 7th cache node)
1 user:1001 2 5 moved: cache miss, DB hit
2 user:1002 4 4 stays (about 1 key in 7)
3 user:1003 0 3 moved
4 user:1004 5 1 moved
5 -- after the change about 86% of lookups miss: a thundering herd on the databaseReal scenarios: the day a Memcached pool grows from 6 to 7 servers and the hit rate falls from 98% to 14% for an hour while the database absorbs the load; a sharded MySQL where user_id % 4 becomes user_id % 5 and every row must be copied; a Kafka topic whose partition count is raised and keys with ordering guarantees land on a different partition (Kafka's BuiltInPartitioner computes Utils.toPositive(Utils.murmur2(serializedKey)) % numPartitions).
| Product | Where modulo is used | Consequence |
|---|---|---|
| PostgreSQL | Hash partitioning: FOR VALUES WITH (MODULUS m, REMAINDER r); "the hash value of the partition key divided by the specified modulus will produce the specified remainder" | Changing m means re-partitioning rows (split a partition into two with a larger modulus, or move data) |
| MySQL (InnoDB) | PARTITION BY HASH(expr): partition N = MOD(expr, num); LINEAR HASH uses a powers-of-two algorithm | Changing the partition count redistributes rows; LINEAR HASH redistributes less at the cost of uneven sizes |
| Kafka | murmur2(key) % numPartitions | Adding partitions breaks per-key ordering for existing keys |
Go gomemcache | crc32.ChecksumIEEE(key) % len(servers) in selector.go | Adding a server remaps most keys |
PHP Memcached | OPT_DISTRIBUTION: "Currently supported methods are modulo and consistent hashing" | Choose consistent explicitly |
Fix: use a consistent scheme (next blocks). If you must use modulo, fix n for the life of the data and over-provision: choose 256 or 1024 logical shards and map shards to servers in a table, which is the hash-slot idea. In SQL that table is ordinary data:
-- Logical shards are fixed forever; only the shard -> node mapping changes.
CREATE TABLE shard_map (
shard_id int PRIMARY KEY, -- 0..1023, hash(key) % 1024
node text NOT NULL, -- 'db-3.internal'
moved_at timestamptz NOT NULL DEFAULT now()
);
-- Resharding = copy one shard, then flip one row. 1/n of the shards move, not all keys.
UPDATE shard_map SET node = 'db-7.internal', moved_at = now() WHERE shard_id = 412;
-- Route a key (the application hashes, the database only stores the map):
SELECT node FROM shard_map WHERE shard_id = (abs(hashtextextended('user:1001', 0)) % 1024);(hashtextextended is a PostgreSQL internal function that is not documented as stable across versions; hash in the application with a documented function when the result must survive upgrades.)
Go: the failure is visible in 10 lines, see modulo in cmd/movement. Laravel: avoid computing crc32($key) % count($servers) in your own code; use the Memcached options below or a ShardRing.
The hash ring Must-know
In plain words: bend the range of hash values into a circle. Put every node on the circle at the hash of its name. A key goes to the first node clockwise from the key's own hash.
Common misunderstanding: "The ring is a data structure that links nodes in a circle." It is not a network topology. It is a sorted array of numbers with a binary search and a wrap-around; the nodes need not know each other for placement to work.
Definition: let H map to [0, 2^64). Node v gets position H(name(v)). Key k is owned by the node with the smallest position >= H(k) (modular, wrap to the smallest). The node is responsible for the range between its predecessor and itself. Dynamo: "Each node in the system is assigned a random value within this space which represents its 'position' on the ring ... walking the ring clockwise to find the first node with a position larger than the item's position."
event ring (positions, schematic) owner of key k
1 ring = [A@10, B@48, C@85] A B C --
2 hash(k) = 60 between B and C C (first clockwise)
3 node D joins at 70 A B [k=60] D@70 C D takes k (60 < 70 <= 85)
4 node D leaves again A B C C owns k again
5 hash(k) = 90, past the last point wraps around to A@10 AReal scenarios: a Memcached pool in front of a product catalogue; a CDN choosing the edge cache for a URL; a service-discovery client choosing the backend for a session id; sharding of Redis keys client-side.
| Where | Ring flavour |
|---|---|
| Dynamo / Cassandra / Riak | Ring of tokens; node owns the arc before each of its tokens |
ketama (libmemcached, PHP Memcached) | "continuum" of 100-200 points per server, MD5-based |
| nginx | hash $request_uri consistent; "the ketama consistent hashing method will be used" |
| HAProxy | hash-type consistent: "the hash table is a tree filled with many occurrences of each server" |
| Envoy | ring_hash: "the addition or removal of one host from a set of N hosts will affect only 1/N requests" |
Fix / how to use it (Go). The teaching ring is ring/ring.go: a sorted slice of (position, node), sort.Search for the lookup, Add and Remove that rebuild the slice.
// Package ring is a teaching consistent-hash ring with virtual nodes,
// replica walking and bounded-load placement (Karger et al. 1997, the
// Dynamo paper section 4, Mirrokni, Thorup & Zadimoghaddam 2016).
package ring
import (
"errors"
"fmt"
"math"
"sort"
"academy/consistent-hashing/hashutil"
)
type point struct {
pos uint64
node string
}
// Ring maps keys to nodes. It is not safe for concurrent writes; guard
// it with a sync.RWMutex or swap whole immutable rings atomically.
type Ring struct {
points []point // sorted by pos
tokens map[string]int
}
// New returns an empty ring.
func New() *Ring { return &Ring{tokens: map[string]int{}} }
// Add places a node on the ring at `tokens` positions (virtual nodes).
// Give a bigger machine more tokens, exactly as Dynamo section 4.2 says.
func (r *Ring) Add(node string, tokens int) {
r.Remove(node)
for i := 0; i < tokens; i++ {
r.points = append(r.points, point{hashutil.Sum64(fmt.Sprintf("%s#%d", node, i)), node})
}
r.tokens[node] = tokens
sort.Slice(r.points, func(i, j int) bool { return r.points[i].pos < r.points[j].pos })
}
// Remove deletes every token of node. Its ranges fall to the next
// token clockwise, which with many vnodes belongs to many different nodes.
func (r *Ring) Remove(node string) {
if _, ok := r.tokens[node]; !ok {
return
}
kept := r.points[:0]
for _, p := range r.points {
if p.node != node {
kept = append(kept, p)
}
}
r.points = kept
delete(r.tokens, node)
}
// Nodes returns the number of physical nodes.
func (r *Ring) Nodes() int { return len(r.tokens) }
// index returns the first point at or after the key's position,
// wrapping to 0 past the top of the ring.
func (r *Ring) index(key string) int {
h := hashutil.Sum64(key)
i := sort.Search(len(r.points), func(i int) bool { return r.points[i].pos >= h })
if i == len(r.points) {
i = 0
}
return i
}
// Locate returns the node that owns key (the primary replica).
func (r *Ring) Locate(key string) (string, error) {
if len(r.points) == 0 {
return "", errors.New("ring: empty")
}
return r.points[r.index(key)].node, nil
}
// Replicas returns the preference list: walk clockwise and collect n
// DISTINCT physical nodes, skipping further vnodes of a node already
// chosen (Dynamo section 4.3).
func (r *Ring) Replicas(key string, n int) []string {
if len(r.points) == 0 {
return nil
}
if n > len(r.tokens) {
n = len(r.tokens)
}
out := make([]string, 0, n)
seen := make(map[string]bool, n)
for i, step := r.index(key), 0; len(out) < n && step < len(r.points); step++ {
p := r.points[(i+step)%len(r.points)]
if !seen[p.node] {
seen[p.node] = true
out = append(out, p.node)
}
}
return out
}
// Bounded wraps a Ring with a per-node capacity of ceil(c * average
// load): consistent hashing with bounded loads. A key whose first node is
// full moves clockwise to the first node with room.
type Bounded struct {
R *Ring
C float64 // balance factor c = 1 + epsilon, for example 1.25
load map[string]int
sum int
}
// NewBounded returns a bounded-load view of r.
func NewBounded(r *Ring, c float64) *Bounded {
return &Bounded{R: r, C: c, load: map[string]int{}}
}
// Acquire assigns one unit of load for key and returns the chosen node.
func (b *Bounded) Acquire(key string) string {
capacity := int(math.Ceil(b.C * float64(b.sum+1) / float64(b.R.Nodes())))
i := b.R.index(key)
for step := 0; step < len(b.R.points); step++ {
p := b.R.points[(i+step)%len(b.R.points)]
if b.load[p.node] < capacity {
b.load[p.node]++
b.sum++
return p.node
}
}
panic("ring: no node has capacity (C must be > 1)")
}
// Release gives one unit of load back to node.
func (b *Bounded) Release(node string) {
if b.load[node] > 0 {
b.load[node]--
b.sum--
}
}
// Load returns the current load per node.
func (b *Bounded) Load() map[string]int { return b.load }SQL has no ring; keep the ring in the application or in the database client and store only membership:
CREATE TABLE ring_members (
node text PRIMARY KEY,
tokens int NOT NULL DEFAULT 160 CHECK (tokens > 0), -- weight: more tokens, more data
state text NOT NULL DEFAULT 'joining' -- joining | normal | leaving
);Laravel: ShardRing is the same algorithm in PHP 8.3 with hash('xxh3', ...) positions.
<?php
declare(strict_types=1);
namespace App\Redis;
use InvalidArgumentException;
/**
* Consistent-hash ring with virtual nodes (Karger 1997; Dynamo section 4.2).
* Immutable: to change membership build a new ring and swap it in.
*/
final class ShardRing
{
/** @var list<int> sorted token positions */
private array $positions = [];
/** @var array<int, string> position => physical node name */
private array $owners = [];
/** @var array<string, int> node => number of tokens */
private array $tokens = [];
/**
* @param array<string, int> $nodes node name => token count (weight)
*/
public function __construct(array $nodes)
{
if ($nodes === []) {
throw new InvalidArgumentException('A ring needs at least one node.');
}
foreach ($nodes as $name => $tokens) {
$this->tokens[$name] = $tokens;
for ($i = 0; $i < $tokens; $i++) {
// On a collision the later token wins; with 32-bit positions
// and a few thousand tokens that is astronomically rare.
$this->owners[self::position("{$name}#{$i}")] = $name;
}
}
ksort($this->owners);
$this->positions = array_keys($this->owners);
}
/** 32-bit position from xxh3 (PHP 8.1+). Stable across processes and hosts. */
public static function position(string $value): int
{
return (int) hexdec(substr(hash('xxh3', $value), 0, 8));
}
/** Primary owner: first token at or after the key, wrapping past the top. */
public function locate(string $key): string
{
return $this->owners[$this->positions[$this->indexOf($key)]];
}
/**
* Preference list: walk clockwise and collect $count DISTINCT nodes.
*
* @return list<string>
*/
public function replicas(string $key, int $count): array
{
$count = min($count, count($this->tokens));
$total = count($this->positions);
$start = $this->indexOf($key);
$chosen = [];
for ($step = 0; $step < $total && count($chosen) < $count; $step++) {
$node = $this->owners[$this->positions[($start + $step) % $total]];
$chosen[$node] = true;
}
return array_keys($chosen);
}
private function indexOf(string $key): int
{
$h = self::position($key);
$lo = 0;
$hi = count($this->positions);
// Lower bound: first index whose position >= $h.
while ($lo < $hi) {
$mid = intdiv($lo + $hi, 2);
if ($this->positions[$mid] < $h) {
$lo = $mid + 1;
} else {
$hi = $mid;
}
}
return $lo === count($this->positions) ? 0 : $lo;
}
}Virtual nodes (tokens) Must-know
In plain words: instead of one point per server, give each server many points scattered around the circle. Each server then owns many small arcs, so the total share is close to equal, and when a server joins or leaves, its load comes from or goes to many neighbours.
Common misunderstanding: "More vnodes is always better." Cassandra's documentation lists the cost: "Every token introduces up to 2 * (RF - 1) additional neighbors on the token ring, which means that there are more combinations of node failures where we lose availability for a portion of the token ring." Repairs and range scans also touch more ranges.
Definition: a virtual node (Dynamo) or token (Cassandra) is one position on the ring owned by a physical node. Dynamo: "A virtual node looks like a single node in the system, but each node can be responsible for more than one virtual node." The paper adds that the number of virtual nodes a node is responsible for can be set from its capacity, "accounting for heterogeneity in the physical infrastructure".
step what happens
1 node E (2x memory) joins with 320 tokens other nodes have 160 each
2 each token takes the arc just before it E steals many small slices from many nodes
3 E ends up with about 2/(n+1) of the data proportional to tokens, as Dynamo section 4.2 intends
4 later E fails its 320 arcs fall to 320 different successors, so every survivor gains about the sameReal scenarios: a heterogeneous Memcached pool where weight is the memory in MB (ketama's server file: "Just use the number of megs allocated to the server as the weight"); a Cassandra cluster mixing 16-core and 32-core nodes with different num_tokens; a Riak cluster with 64 partitions.
The measured effect of tokens (20 different 6-node clusters, 60,000 keys each, max/mean load):
| Tokens per node | Average max/mean | Worst max/mean | Reading |
|---|---|---|---|
| 1 | 2.56 | 4.04 | One node can hold four times its share |
| 16 | 1.35 | 1.60 | Cassandra 4's num_tokens default; 35% over the mean on the hottest node |
| 64 | 1.15 | 1.35 | |
| 256 | 1.10 | 1.16 | Cassandra 2.x default was 256 |
| 1024 | 1.04 | 1.07 | Standard deviation falls roughly as 1/sqrt(T) |
| Product | Default and knobs |
|---|---|
| Cassandra | num_tokens default 16 (documented in cassandra.yaml); "the only token allocation algorithm available was picking random tokens" in 2.x, so the default was 256; since 3.x allocate_tokens_for_keyspace / allocate_tokens_for_local_replication_factor choose tokens deterministically so a low count balances |
| Dynamo (paper) | T random tokens per node in strategy 1; strategy 3 fixes Q partitions and gives each node Q/S |
| Riak | Fixed ring size (number of partitions), each node runs partitions/nodes vnodes |
| ketama / libmemcached | 100-200 points per server, scaled by weight |
Envoy ring_hash | minimum_ring_size and maximum_ring_size; monitor min_hashes_per_host / max_hashes_per_host |
| Redis Cluster | No tokens: slots instead |
Fix: in Go, call r.Add(node, tokens) with tokens proportional to capacity; in Laravel, pass the weights to ShardRing; in SQL store tokens in ring_members. The distribution histogram is in the lab.
Replication along the ring, the preference list Must-know
In plain words: the node that owns a key stores the first copy; the next nodes clockwise store the others. The list of nodes for a key is its preference list.
Common misunderstanding: "Replicas are the next N tokens." With virtual nodes the next tokens often belong to the same physical machine, so you would store three copies on one server. The walk must skip tokens of nodes already chosen. Dynamo: "the preference list for a key is constructed by skipping positions in the ring to ensure that the list contains only distinct physical nodes."
Definition: with replication factor N (Dynamo's N, Cassandra's RF), the replicas of key k are the first N distinct physical nodes met while walking clockwise from H(k). Dynamo states that "each node is responsible for the region of the ring between it and its Nth predecessor". Rack- or datacenter-aware strategies (Cassandra NetworkTopologyStrategy) additionally skip nodes in a rack that already has a copy. Dynamo's list holds more than N nodes so failed nodes can be replaced (hinted handoff, sloppy quorum).
ring tokens clockwise from H(k) decision (RF = 3)
1 C2 (node C) take C
2 A3 (node A) take A
3 C3 (node C again) skip: node C already chosen
4 B3 (node B) take B -> preference list [C, A, B]
5 a write with W=2, a read with R=2 R + W > N = 3, so reads overlap writes (Dynamo)Real scenarios: a Cassandra write at QUORUM with RF=3 goes to the coordinator and is acknowledged by two of the three replicas; a node failure makes the preference list skip it and write a hint to the next node; a rack failure that loses all replicas of a range because the strategy was not rack-aware.
| Product | How replicas are picked |
|---|---|
| Dynamo | Next N distinct physical nodes clockwise; preference list longer than N for failures |
| Cassandra | "we 'walk' the ring in a clockwise fashion until we encounter three distinct nodes"; SimpleStrategy ignores racks, NetworkTopologyStrategy honours datacenter and rack |
| Riak | Partition owner plus "the vnodes responsible for the next N-1 partitions" |
| Redis Cluster | No ring: each slot has one master and replicas chosen when you set up the cluster (CLUSTER REPLICATE) |
| MongoDB | Replica sets per shard, independent of placement |
| DynamoDB | Hidden; the service replicates across Availability Zones |
Fix (Go): ring.Replicas(key, 3) in the teaching module walks the slice and keeps a seen set. Laravel: ShardRing::replicas($key, 3). SQL: store the placement in a catalogue only when the system is slot-based:
SELECT node FROM shard_replicas WHERE shard_id = 412 ORDER BY replica_rank; -- rank 0 is the primaryHash slots (fixed partitions) Must-know
In plain words: cut the hash space into a fixed number of small buckets (slots) once, forever. A table says which node owns which slots. To rebalance, move whole slots and change the table.
Common misunderstanding: "Redis Cluster is consistent hashing." The Redis Cluster specification calls the mechanism hash slots and does not use a ring: HASH_SLOT = CRC16(key) mod 16384. The key to slot mapping is modulo and never changes; only the slot to node table does, so resharding moves exactly the slots you choose.
Definition: Redis: "The cluster's key space is split into 16384 slots, effectively setting an upper limit for the cluster size of 16384 master nodes (however, the suggested max size of nodes is on the order of ~ 1000 nodes)." Hash tags: "If the key contains a "{...}" pattern only the substring between { and } is hashed in order to obtain the hash slot". The Dynamo paper's strategy 3 is the same idea: a fixed Q of equal partitions, each node holding Q/S of them. Couchbase vBuckets, Citus shards ("a row is stored in a shard if the hash of the value in the distribution column falls within the shard's hash range"), Vitess keyspace ids, MongoDB hashed chunks, Elasticsearch shards and Riak partitions are all variants.
step effect
1 cluster of 3 masters, slots 0-5460 | 5461-10922 | 10923-16383
2 client: CRC16("foo") mod 16384 = 12182 slot 12182 belongs to master C
3 redis-cli --cluster add-node, then reshard new master D owns no slot yet, serves nothing
4 CLUSTER SETSLOT 700 MIGRATING / IMPORTING slot 700 moves key by key (MIGRATE)
5 client asks A for a key in slot 700 A answers -MOVED 700 10.0.0.4:6379 (after the move) or -ASK 700 ... (during)
6 client refreshes its slot table the next 1/4 of all slots move; no key outside them is touchedReal scenarios: growing a Redis Cluster from 3 to 4 masters (moves 25% of slots); a Redis-backed cart service that stores {tenant:42}:cart and {tenant:42}:orders in one slot so SMOVE works; a ten-day Black Friday where you pre-split to 16384 slots and only ever move slots.
| Question | Answer |
|---|---|
| Why 16384? | The specification fixes 16384 and notes it caps the cluster at 16384 masters, with about 1000 nodes as the suggested practical maximum. The usual explanation for not choosing 65536 (heartbeat messages carry the slot bitmap, so a smaller bitmap is cheaper) comes from the Redis author's comments, not from the specification |
| What if a key has no tag? | The whole key is hashed |
| What if keys of one command are in different slots? | The server answers CROSSSLOT Keys in request don't hash to the same slot |
| Who knows the table? | Every node and every smart client; clients cache it and repair it on MOVED |
Fix (Go): the teaching module slots/slots.go implements the CRC16 and the hash-tag rule and checks slot(foo) = 12182, the value Redis gives for CLUSTER KEYSLOT foo. Laravel: ClusterKeys::slot() and ClusterKeys::tenantKey(). SQL: the shard_map table from the modulo block is the same pattern in a relational shape.
// Package slots reproduces Redis Cluster key-to-slot mapping:
// HASH_SLOT = CRC16(key) mod 16384, with the {hash tag} exception.
package slots
// Count is the number of hash slots in Redis Cluster.
const Count = 16384
// crc16 is CRC-16/XMODEM (poly 0x1021, init 0), as in the cluster spec.
func crc16(b []byte) uint16 {
var crc uint16
for _, c := range b {
crc ^= uint16(c) << 8
for i := 0; i < 8; i++ {
if crc&0x8000 != 0 {
crc = crc<<1 ^ 0x1021
} else {
crc <<= 1
}
}
}
return crc
}
// Slot returns the hash slot of key, honouring hash tags: if the key has
// a '{', a later '}' and at least one byte between the first '{' and the
// first '}' after it, only those bytes are hashed.
func Slot(key string) int {
for s := 0; s < len(key); s++ {
if key[s] != '{' {
continue
}
for e := s + 1; e < len(key); e++ {
if key[e] == '}' {
if e == s+1 {
return int(crc16([]byte(key)) % Count)
}
return int(crc16([]byte(key[s+1:e])) % Count)
}
}
break
}
return int(crc16([]byte(key)) % Count)
}
// Assign splits the slots into n contiguous ranges, as redis-cli
// --cluster create does for n masters; it returns the owner of each slot.
func Assign(n int) []int {
owner := make([]int, Count)
for i := range owner {
owner[i] = i * n / Count
}
return owner
}Hotspots and load imbalance Important
In plain words: even when every node holds the same number of keys, one node can still get most of the requests, because some keys are read much more than others, or because the arcs are of unequal size.
Common misunderstanding: "Uniform key distribution means uniform load." Dynamo's authors say it only holds "assuming the access distribution of keys is not highly skewed", and their design assumes "there are enough keys in the popular end of the distribution" so that popular keys spread out. A single viral key defeats any hash: it hashes to one place.
Definition: there are three sources of imbalance: unequal arcs (few tokens), unequal capacity (weights wrong), skewed access (hot keys). Dynamo measures "load balancing efficiency" as "the ratio of average number of requests served by each node to the maximum number of requests served by the hottest node".
cause symptom fix
1 one token per node max/mean 2.6 on average (4.0 worst, measured) more tokens or Maglev/slots
2 weights ignored small machine saturates first tokens proportional to capacity
3 one viral key one node at 100% CPU, others idle replicate the hot key (read from replicas), local cache, key splitting "key#0..key#7", bounded loads
4 a hot tag or counter one Redis slot is the bottleneck shard the counter: counter:{0..15}, sum on read
5 time-ordered keys on range all writes to the newest range hash the key (MongoDB hashed shard key) or prefix a bucketReal scenarios: a celebrity profile cached on one Memcached server; a Redis INCR counter for a global rate limit that melts one shard; a Cassandra partition for one tenant that holds 30% of the traffic; a MongoDB collection sharded by ObjectId where "the chunk with an upper bound of MaxKey receives the majority incoming writes" and a hashed shard key spreads inserts.
| Mitigation | Works for | Does not help |
|---|---|---|
| More tokens / bigger slot count | Unequal arcs | A single hot key |
| Bounded-load hashing | Load skew from hot keys on a node | A single key hotter than one node can serve |
Key splitting (key#0 .. key#7) | Hot read or write key | Needs readers to merge, loses single-key atomicity |
| Local (in-process) cache or CDN in front | Hot reads | Hot writes |
| Replicated reads (read from any replica) | Hot reads | Staleness is allowed |
Fix (Go): measure first, the distribution command prints a histogram and max/mean. SQL: SELECT shard_id, count(*) FROM orders GROUP BY 1 ORDER BY 2 DESC finds skew; pg_stat_statements finds hot queries. Laravel: shard a hot counter across n keys:
// Spread a hot counter over 16 keys; each INCR hits a different slot, a read sums them.
Redis::incr('likes:post:'.$postId.':'.random_int(0, 15));
$total = array_sum(Redis::mget(array_map(fn ($i) => "likes:post:$postId:$i", range(0, 15))));(On Redis Cluster the MGET above would be CROSSSLOT; use a hash tag such as likes:{post:$postId}:$i to keep the 16 keys in one slot and give up the spreading, or issue 16 separate GET calls through a pipeline. This trade-off is the point.)
Bounded-load consistent hashing Important
In plain words: give every node a capacity of "a bit more than the average". A key goes to its normal node, unless that node is full, in which case it moves clockwise to the next node with room.
Common misunderstanding: "Bounded loads are a different algorithm." It is a plain ring plus a counter and a loop: Mirrokni et al. start from "the consistent hashing scheme where current balls and bins are hashed to a unit cycle, and a ball is placed in the first bin succeeding it in clock-wise order" and "apply the idea of linear probing by forwarding the ball on the circle to the first non-full bin".
Definition: for balancing parameter c = 1 + epsilon > 1, no bin gets more than ceil(c x m / n) of m balls over n bins. The paper proves that when a ball or bin is inserted or deleted, the expected number of moves is within a factor O(1/epsilon^2) of the optimum for epsilon <= 1. Plain consistent hashing has no such cap: "the load balancing of these schemes is no better than a random assignment of clients to servers, so with n of each, we expect many servers to be overloaded with Θ(log n/log log n) clients."
event (n = 4 nodes, c = 1.25, average load 100) decision
1 key k hashes to node B, B has 124 of cap 125 accepted, B = 125
2 next key hashes to B again B is full: probe clockwise
3 C has 90 < 125 placed on C (and remembered)
4 request finishes Release(C): counters go down
5 c = 1.0 would be exact balance and many moves; c = 2 is nearly plain hashingReal scenarios: a video-segment cache where popular titles would all stick to one server; a stateful gateway routing a tenant to the same backend for cache locality but never above 125% of the average load; a game server matchmaker.
| Product | Knob |
|---|---|
| HAProxy | hash-balance-factor <factor>: "Setting <factor> to 0 (the default) disables the feature. Otherwise, <factor> is a percentage greater than 100. For example, if <factor> is 150, then no server will be allowed to have a load more than 1.5 times the average." "Reasonable values are from 125 to 200." |
| Envoy | ring_hash and Maglev themselves have no cap; use overload management or load-aware policies |
| nginx | hash ... consistent has no bounded-load option |
| Teaching Go module | ring.NewBounded(r, 1.25) |
Measured (120,000 keys, 6 nodes, 16 tokens, 20% of traffic on 250 hot keys): a plain ring gives max/mean 1.73 (one node at 34,535 of a 20,000 average), the bounded ring with c = 1.25 gives 1.25 exactly (25,000).
Fix (Go): b := ring.NewBounded(r, 1.25); node := b.Acquire(key); defer b.Release(node). SQL: no equivalent; the load counters live in the application or in the proxy. Laravel: keep per-node in-flight counters in Cache::increment() and probe ShardRing::replicas($key, $n) for the first node under the cap.
Jump consistent hash Important
In plain words: a five-line function that, given a key and a number of buckets n, returns a bucket from 0 to n-1, such that growing n by one moves exactly 1/(n+1) of the keys, all of them into the new bucket, and needs no memory at all.
Common misunderstanding: "Jump hash is a better ring." It cannot name nodes: "jump consistent hash does not support arbitrary server names, but only returns a shard number". It also cannot remove an arbitrary bucket: removing bucket 3 of 10 would renumber 4 to 9.
Definition: Lamping and Veach: "The function satisfies the two properties: (1) about the same number of keys map to each bucket, and (2) the mapping from key to bucket is perturbed as little as possible when the number of buckets is changed." The abstract adds: "Its main limitation is that the buckets must be numbered sequentially, which makes it more suitable for data storage applications than for distributed web caching." Compared with Karger's ring, it "requires no storage, is faster, and does a better job of evenly dividing the key space". Expected time is O(ln n).
n key k lands in bucket rule
1 1 0 only one bucket
2 2 0 or 1: moves to 1 with probability 1/2 the new bucket b = n-1 steals each key with prob 1/n
3 7 stays unless it jumps to 6 (prob 1/7) a key either stays or moves to the new bucket
4 8 stays unless it jumps to 7 (prob 1/8)
5 -- never moves between two old buckets, so a shard can be split by copying 1/(n+1) of the data to the new shardReal scenarios: a sharded key-value store where shards are numbered and you only ever add shards at the end; a numbered fleet of cache workers whose number is the Kubernetes StatefulSet ordinal (worker-0 .. worker-n), scaling only at the tail; map-reduce partitioning.
| Property | Jump hash | Ring with vnodes |
|---|---|---|
| Memory | none | O(n x T) |
| Balance | near perfect (measured max/mean 1.01) | statistical (1.04-1.35 with 64-1024 tokens) |
| Arbitrary add/remove | no: only the last bucket | yes |
| Weights | no | yes (tokens) |
| Named nodes | no | yes |
| Lookup | O(ln n) | O(log nT) |
Fix (Go): jump/jump.go is the paper's 5-line algorithm with uint64 keys; hash the key to 64 bits first.
// Package jump implements Jump Consistent Hash (Lamping & Veach, 2014).
package jump
// Hash maps a 64-bit key to a bucket in [0, buckets). It needs no memory,
// but buckets must be numbered 0..n-1 and only the highest-numbered
// bucket can be removed without moving unrelated keys.
func Hash(key uint64, buckets int) int {
var b int64 = -1
var j int64
for j < int64(buckets) {
b = j
key = key*2862933555777941757 + 1
j = int64(float64(b+1) * (float64(int64(1)<<31) / float64((key>>33)+1)))
}
return int(b)
}SQL: a numbered-shard table (shard_id 0..n-1) pairs well; stored-procedure implementations exist but the loop runs in the application. Laravel: port the loop with intdiv and float math as above; keep the integer overflow behaviour in mind (PHP integers are signed 64-bit and overflow to float, so use gmp_* or mask to 32 bits for portability).
Rendezvous (highest random weight) hashing Important
In plain words: for a key, every node computes a score from the pair (node, key); the key goes to the node with the highest score. If a node disappears, only its keys have a new highest scorer. If a node appears, it wins only the keys it scores highest on.
Common misunderstanding: "It is just consistent hashing under another name." Same goal, different mechanism: no ring, no tokens, no state beyond the node names, and the replica set falls out for free as the top k scores. The price is O(n) per lookup. Wikipedia describes it as "an algorithm that allows clients to achieve distributed agreement on a set of k options out of a possible set of n options".
Definition: owner(k) = argmax over nodes v of H(v, k). Thaler and Ravishankar introduced it (technical report 1996, IEEE/ACM ToN 1998). Weighted variants exist; the teaching code uses equal weights.
node scores for key k (schematic) score
1 cache-1 0x91...
2 cache-2 0xe4... <- highest, owner
3 cache-3 0x2a...
4 cache-2 is removed owner becomes the next highest: cache-1
5 other keys whose top score was never cache-2 unchangedReal scenarios: a small pool (under about 50 nodes) of caches where O(n) is cheap; picking the top-3 replicas of a shard without a ring; choosing the aggregation worker for a tenant in a data pipeline; CDN edge selection (the motivating use in the 1998 paper: hit rates of proxies).
| Product / library | Rendezvous |
|---|---|
Go github.com/dgryski/go-rendezvous and similar | Libraries exist; the teaching module is 40 lines |
| Apache Ignite | Rendezvous affinity function is the default for partition-to-node assignment (Ignite docs, not re-fetched here) |
| Kafka, Cassandra, Redis | not used |
Fix (Go): rendezvous/rendezvous.go: Locate is one loop, Top(key, k) returns replicas. In Laravel: usort nodes by hash('xxh3', $node.$key). In SQL there is no good form; an expression index on hash(node || key) does not help because the score depends on the node list.
// Package rendezvous implements Highest Random Weight hashing
// (Thaler & Ravishankar). Every node scores every key; the top score wins.
package rendezvous
import (
"sort"
"academy/consistent-hashing/hashutil"
)
// Set is a group of node names.
type Set struct{ nodes []string }
// New returns a Set with the given nodes.
func New(nodes ...string) *Set { return &Set{nodes: append([]string(nil), nodes...)} }
// Add appends a node. Remove deletes one. Neither moves unrelated keys.
func (s *Set) Add(n string) { s.nodes = append(s.nodes, n) }
// Remove deletes a node by name.
func (s *Set) Remove(n string) {
for i, x := range s.nodes {
if x == n {
s.nodes = append(s.nodes[:i], s.nodes[i+1:]...)
return
}
}
}
func score(node, key string) uint64 { return hashutil.Sum64(node + "\x00" + key) }
// Locate returns the node with the highest score for key: O(n) per lookup.
func (s *Set) Locate(key string) string {
var best string
var bestScore uint64
for i, n := range s.nodes {
if sc := score(n, key); i == 0 || sc > bestScore {
best, bestScore = n, sc
}
}
return best
}
// Top returns the k highest-scoring nodes: the replica set of key.
func (s *Set) Top(key string, k int) []string {
type scored struct {
node string
score uint64
}
all := make([]scored, 0, len(s.nodes))
for _, n := range s.nodes {
all = append(all, scored{n, score(n, key)})
}
sort.Slice(all, func(i, j int) bool { return all[i].score > all[j].score })
if k > len(all) {
k = len(all)
}
out := make([]string, k)
for i := range out {
out[i] = all[i].node
}
return out
}Maglev hashing Good to know
In plain words: precompute a big lookup table (65,537 or 655,373 slots) in which every backend owns an almost equal number of slots, spread so that removing a backend only rewrites its own slots plus a few extras. A packet's hash picks a slot; the table says the backend. Lookup is one array read.
Common misunderstanding: "Maglev is a rendezvous variant with better memory." It is a lookup-table construction: backends take turns claiming their next free preferred slot, which guarantees near-equal shares, at the price of a small amount of additional disruption beyond the minimum.
Definition: Eisenbud et al.: "The basic idea of Maglev hashing is to assign a preference list of all the lookup table positions to each backend. Then all the backends take turns filling their most-preferred table positions that are still empty, until the lookup table is completely filled in." The permutation of backend i is (offset + j x skip) mod M with offset = h1(name) mod M and skip = h2(name) mod (M-1) + 1, and "M must be a prime number so that all values of skip are relatively prime to it". Weights are made "by altering the relative frequency of the backends' turns". Maglev also keeps a per-connection table to protect long flows when the table changes.
M = 7, backends B0 B1 B2: the toy example of the Maglev paper (Tables 1 and 2)
1 permutations: B0 = 3 0 4 1 5 2 6 B1 = 0 2 4 6 1 3 5 B2 = 3 4 5 6 0 1 2
2 round 1: B0 takes 3, B1 takes 0, B2 wants 3 (taken) so takes 4
3 round 2: B0 takes 1 (0 and 4 are taken), B1 takes 2, B2 takes 5
4 round 3: B0 takes 6. Table: 0=B1 1=B0 2=B1 3=B0 4=B2 5=B2 6=B0 (3, 2, 2 slots)
5 remove B1: refill with B0 and B2 only -> 0=B0 1=B0 2=B0 3=B0 4=B2 5=B2 6=B2
6 changed: slots 0 and 2 (B1's own) plus slot 6 (B0 -> B2): "only one other entry (row 6) needs to be changed"
7 measured here (M = 65537, 6 -> 7 backends): 14.6% of keys move, 288 of them not to the new backendReal scenarios: the network load balancer in front of a search frontend, deciding per five-tuple; a service mesh sidecar choosing an upstream; a Redis proxy that must pick a shard in O(1).
| Product | Setting |
|---|---|
| Google Maglev | Table 65537 (small) and 655373 (large) in the paper's evaluation |
| Envoy | maglev load balancer, fixed table size 65537 by default (table_size), "Maglev has substantially faster table lookup build times as well as host selection times (approximately 10x and 5x respectively ...). While Maglev aims for minimal disruption, it is not as stable as ring hash when upstream hosts change ... approximately double the keys will move" |
| Cilium and other eBPF load balancers | Offer Maglev-style lookup tables (vendor docs, not re-fetched here) |
Fix (Go): maglev/maglev.go implements the population loop and Share() to check balance. Laravel and SQL do not need Maglev; it belongs in the L4/L7 proxy.
// Package maglev implements the Maglev lookup-table construction
// (Eisenbud et al., NSDI 2016): each backend has a permutation of table
// slots; backends take turns claiming their next free preferred slot.
package maglev
import "academy/consistent-hashing/hashutil"
// DefaultSize is a prime. The paper uses 65537 for small and 655373 for
// large tables. M must be prime so every skip is coprime with it.
const DefaultSize = 65537
// Table is a filled lookup table of backend indexes.
type Table struct {
backends []string
entry []int
}
// New builds a table of size m (prime) for the backends.
func New(backends []string, m int) *Table {
n := len(backends)
offset := make([]int, n)
skip := make([]int, n)
for i, b := range backends {
offset[i] = int(hashutil.Sum64Seed(b, 1) % uint64(m))
skip[i] = int(hashutil.Sum64Seed(b, 2)%uint64(m-1)) + 1
}
next := make([]int, n)
entry := make([]int, m)
for i := range entry {
entry[i] = -1
}
filled := 0
for filled < m {
for i := 0; i < n && filled < m; i++ {
c := (offset[i] + next[i]*skip[i]) % m
for entry[c] >= 0 {
next[i]++
c = (offset[i] + next[i]*skip[i]) % m
}
entry[c] = i
next[i]++
filled++
}
}
return &Table{backends: append([]string(nil), backends...), entry: entry}
}
// Locate returns the backend for key: one hash and one array read.
func (t *Table) Locate(key string) string {
return t.backends[t.entry[hashutil.Sum64(key)%uint64(len(t.entry))]]
}
// Share returns how many table slots each backend owns.
func (t *Table) Share() map[string]int {
out := make(map[string]int, len(t.backends))
for _, e := range t.entry {
out[t.backends[e]]++
}
return out
}Resharding cost: K/n keys move Must-know
In plain words: when you add the (n+1)th node, the new node must end up with K/(n+1) of the K keys. Consistent hashing takes exactly those, from the other nodes, and moves nothing else.
Common misunderstanding: "Zero downtime means the move is instant." The move is the expensive part: data must be streamed from existing nodes, which are serving traffic. Dynamo reports that with random tokens "the bootstrapping has taken almost a day to complete" in busy season, because "the nodes handing the key ranges off to the new node have to scan their local persistence store".
Definition: the lower bound is K/(n+1) keys for a join and K/n for a leave. Consistent hashing meets it within constant factors (ring, HRW, jump). Modulo moves about K x n/(n+1).
| Event (6 to 7 nodes, 120,000 keys) | Modulo | Consistent | Notes |
|---|---|---|---|
| Keys that move | 102,776 (85.6%) | 17,000 to 19,400 (14.2% to 16.2%) | The ideal is 17,143 (14.3%) |
| Where they go | anywhere | only to the new node (Maglev: a few extra) | Measured in the lab |
| Slots (Redis Cluster) | 8,191 of 16,384 slots (50.0%) if you naively re-split into 7 contiguous ranges | 2,340 (14.3%) if you only fill the new master | Rebalance by moving slots, not by recomputing ranges |
phase (Cassandra, adding node X) cost
1 X starts with auto_bootstrap=true joins the ring, state UJ (joining)
2 X streams its token ranges from the current replicas network + disk read on the donors
3 X becomes UN (normal); donors still hold stale copies disk is not freed yet
4 nodetool cleanup on every donor deletes keys they no longer own
5 repair later Merkle trees must be rebuilt for changed ranges (Dynamo section 6.2)Real scenarios: an autoscaled Memcached tier that grows daily; a Cassandra expansion from 6 to 9 nodes ahead of a sale; a Redis Cluster that adds two masters and moves 5,460 slots with redis-cli --cluster rebalance; a Kafka topic that doubles its partitions and breaks per-key ordering for a short time because Kafka does not do consistent hashing.
| Product | How resharding runs |
|---|---|
| Cassandra | Bootstrap streams ranges; nodetool cleanup removes moved data; nodetool decommission hands ranges back |
| Redis Cluster | CLUSTER SETSLOT MIGRATING/IMPORTING and MIGRATE, orchestrated by redis-cli --cluster reshard or rebalance; clients follow -MOVED and -ASK |
| MongoDB | The balancer migrates chunks between shards; since 8.0 sharding a collection "creates 1 chunk per shard by default and migrates across the cluster" |
| PostgreSQL | Hash partitions: re-partition (attach new partitions with a new modulus, move rows); Citus: rebalance_table_shards() moves shards |
| DynamoDB | Automatic: the service splits and moves partitions; you do not see it |
| CockroachDB | Range-based (not hash): ranges split by size and rebalance automatically, with no hash-ring at all |
Fix (SQL): copy first, flip later; for a PostgreSQL logical shard move: CREATE PUBLICATION, subscribe on the target, wait for sync, then UPDATE shard_map, then drop on the source. Go: the movement command counts moved keys per scheme. Laravel: after adding a Memcached server, expect a cold ratio of about 1/(n+1); warm it with a prefetch job rather than letting the database absorb the misses.
Hash functions: FNV, xxHash, murmur, CRC16, MD5 Important
In plain words: placement is only as even as the hash function mixes its input. Positions of node#1, node#2, node#3 must land far apart, and a cheap hash that changes only the low bits will not do that.
Common misunderstanding: "Any 64-bit hash is fine for a ring." FNV-1a is stable, simple and in Go's standard library (hash/fnv: New32, New32a, New64, New64a, New128), but its high bits change little when only the last bytes differ, and ring positions are compared as numbers, so near-identical vnode labels cluster. The teaching module therefore applies a splitmix64 finalizer after FNV. Hash functions in Go's hash/maphash use a per-process random seed and must never be used for placement shared between processes.
Definition and per-product choice:
| Hash | Used by | Notes |
|---|---|---|
| CRC16 (XMODEM) mod 16384 | Redis Cluster | "In our tests CRC16 behaved remarkably well in distributing different kinds of keys evenly across the 16384 slots." |
| Murmur3 (token range -2^63 .. 2^63-1) | Cassandra Murmur3Partitioner (the default partitioner); RandomPartitioner (MD5) and ByteOrderedPartitioner are legacy | The partitioner "can NOT be changed without reloading all data" |
| Murmur2 | Kafka producer default partitioner | modulo, not consistent |
| MD5 | ketama / libmemcached "libketama-compatible" | 4 positions per MD5 digest in the original |
| 160-bit SHA-1 | Riak ("a 160-bit binary hash of each bucket/key pair"), Dynamo (MD5 128-bit in the paper) | |
| xxHash (XXH64, XXH3) | Go github.com/cespare/xxhash/v2 (Sum64, Sum64String), PHP 8.1 hash('xxh3') / xxh64 | Fast, good avalanche, not cryptographic |
| sdbm + avalanche | HAProxy hash-type consistent default | hash-type ... djb2, wt6, crc32 alternatives |
| FNV-1a | Go stdlib hash/fnv, many small caches | Poor avalanche on short keys; add a finalizer |
Rules: the hash must be stable across processes, hosts, languages and software versions (otherwise two clients disagree); do not use language-randomised hashes (Python hash(), Go maphash, PHP spl_object_id); hash bytes, not objects; document the hash in the data schema because changing it re-maps everything.
Fix (Go): hashutil/hashutil.go is 25 lines. Laravel: hash('xxh3', $key); avoid crc32() for positions on a 64-bit ring (it is 32-bit and CRC-linear). SQL: PostgreSQL's hashtext() is internal; use the application hash or md5($key) converted with ('x'||left(md5(k),16))::bit(64)::bigint.
// Package hashutil holds the hash functions used by the teaching
// implementations. Only the standard library is used: hash/fnv for the
// base hash and a splitmix64 finalizer to repair its weak avalanche.
package hashutil
import "hash/fnv"
// FNV64a is the raw 64-bit FNV-1a hash. It is fast and stable across
// processes and releases, but its high bits change little when only the
// last bytes of the input change ("node-1#1", "node-1#2", ...). Placing
// vnodes with it directly clusters them on the ring.
func FNV64a(s string) uint64 {
h := fnv.New64a()
_, _ = h.Write([]byte(s))
return h.Sum64()
}
// Mix is the splitmix64 finalizer: every input bit flips about half of the
// output bits. It is cheap and deterministic.
func Mix(x uint64) uint64 {
x ^= x >> 30
x *= 0xbf58476d1ce4e5b9
x ^= x >> 27
x *= 0x94d049bb133111eb
x ^= x >> 31
return x
}
// Sum64 is FNV-1a followed by Mix. Use it wherever a position on a ring,
// a score or a table index is derived from a string. In production code
// prefer xxhash (github.com/cespare/xxhash/v2) or murmur3; the shape of
// the code does not change.
func Sum64(s string) uint64 { return Mix(FNV64a(s)) }
// Sum64Seed derives an independent hash from the same input, used where
// an algorithm needs two or more hash functions (Maglev offset and skip).
func Sum64Seed(s string, seed uint64) uint64 {
return Mix(FNV64a(s) ^ Mix(seed+0x9e3779b97f4a7c15))
}Per-product behaviour
"Never name a feature without the product" is the rule, so here is each product once, with what it hashes, what moves on a membership change, and the knob.
| Product | Placement scheme | On node join / leave | Hash and knob |
|---|---|---|---|
| Amazon Dynamo (paper) | Ring with tokens; later Q fixed partitions (strategy 3) | Steals ranges; bootstrap can take a day (random tokens) | MD5, T tokens, Q partitions |
| Amazon DynamoDB | Hidden: "the value of the partition key as input to an internal hash function"; the output "determines the partition" | Automatic partition splits and moves | None exposed |
| Apache Cassandra | Token ring + vnodes | nodetool bootstrap, cleanup, decommission | Murmur3Partitioner, num_tokens default 16, allocate_tokens_for_keyspace |
| Riak KV | Ring of fixed partitions, one vnode each | Handoff of partitions between nodes | 160-bit hash of bucket/key, ring size |
| Redis Cluster | 16384 fixed hash slots | Slot migration by MIGRATE, MOVED/ASK | CRC16, hash tags, cluster-require-full-coverage |
| Memcached + ketama client | Continuum of 100-200 points per server | Only about 1/(n+1) of keys remapped | MD5, weight |
| MongoDB | Hashed or ranged chunks, balancer | Chunk migration | { field: "hashed" } shard key; "hashed indexes truncate floating point numbers to 64-bit integers before hashing" |
| PostgreSQL | Hash partitioning (modulus/remainder); Citus hash ranges | Re-partitioning; rebalance_table_shards | Internal hash per type |
| MySQL / InnoDB | PARTITION BY HASH / KEY / LINEAR HASH | Redefine partitions, rows are copied | MOD(expr, num) |
| SQL Server | No hash distribution; partition functions are range-based | Application-level sharding | Computed column + range function |
| Oracle | Hash partitioning with a fixed partition count | Add / coalesce partitions | Internal hash |
| SQLite | A single file; no distribution | Application-level (file per tenant) | n/a |
| CockroachDB | Range-based, not hash | Ranges split by size and rebalance | n/a |
| Google Spanner | Range-based splits | Automatic | n/a |
| Kafka | murmur2(key) % partitions | Adding partitions reshuffles key to partition | Custom Partitioner interface |
| nginx | hash $key consistent; (ketama) | "only a few keys will be remapped" | hash ... consistent |
| HAProxy | hash-type consistent, hash-balance-factor | Only the node's associations move | sdbm default, hash-type map-based is modulo-like |
| Envoy | ring_hash and maglev | 1/N requests (ring) | minimum_ring_size, table_size |
Where it is used
| Layer | Systems | Key being hashed |
|---|---|---|
| Distributed stores | Dynamo, Cassandra, Riak, Voldemort | Partition key |
| In-memory caches | Memcached clients (ketama), Twemproxy, Redis client-side sharding | Cache key |
| Cluster databases | Redis Cluster, Couchbase (vBuckets), Citus, Vitess | Shard key / slot |
| Load balancers and proxies | Maglev, Envoy, nginx, HAProxy, Cloudflare and Akamai CDNs | Client IP, URL, session |
| Streaming | Kafka partitions (by comparison: modulo), Pulsar key-shared (hash ranges) | Message key |
| Object stores | Ceph CRUSH (placement function, a cousin), OpenStack Swift ring | Object path |
Mechanics
A lookup in a ring. The ring is a sorted array points[] of (position, node). Locate(key) computes h = H(key) and finds the first index with points[i].pos >= h by binary search; past the end it wraps to index 0. Cost: one hash plus O(log(n x T)) comparisons. Rebuild cost on Add is O(nT log nT) in the teaching code, so production code swaps whole immutable rings atomically and readers never lock.
operation complexity notes
1 Locate O(log(nT)) binary search over n x T points
2 Add node O(T log(nT)) insert T tokens; only arcs before them change owner
3 Remove node O(nT) rebuild without its tokens
4 Replicas(k, N) O(N + skips) walk clockwise, skip duplicates
5 memory O(nT) 160 tokens x 100 nodes = 16,000 points (about 256 KB)Membership agreement. A ring only works if every client has the same view. Dynamo uses a gossip-based protocol so "every node in the system can determine which nodes should be in this list for any particular key"; Cassandra uses gossip too; Redis Cluster uses a gossip bus with a slot-ownership bitmap; HAProxy requires "all servers have the exact same IDs" on multiple load balancers to get the same distribution. When two views disagree, requests go to the wrong node: Redis answers -MOVED, Cassandra coordinators forward, caches simply miss.
Redis Cluster redirections and errors:
| Reply | Meaning | Client action |
|---|---|---|
-MOVED 3999 127.0.0.1:6381 | Slot 3999 is served by that node now | Update the slot table, retry there |
-ASK 3999 127.0.0.1:6381 | Slot is migrating; this one key is on the target | Send ASKING then the command to the target, do not update the table |
-CROSSSLOT Keys in request don't hash to the same slot | A multi-key command spans slots | Use hash tags or separate commands |
-CLUSTERDOWN The cluster is down | Some slots have no owner (and full coverage is required) | Wait for failover or repair |
-TRYAGAIN | Multi-key command during migration | Retry shortly |
Cassandra operational commands: nodetool status (UN, UJ, UL, DN), nodetool ring, nodetool describering <keyspace>, nodetool getendpoints <keyspace> <table> <key> (prints the replica set of a key), nodetool cleanup, nodetool decommission, nodetool removenode. Token ranges are half-open: (t1, t2].
Failure behaviour. On a node failure with a plain ring, its arc falls to the next clockwise node, which doubles its load (the "cascade" that vnodes cure). With T tokens the load disperses over many nodes. Dynamo's preference list is longer than N so a write can fall to the next healthy node and be handed off later (hinted handoff).
Smoothness, spread and load (Karger). Smoothness = movement is minimal on membership change; spread = bounded number of caches per object across inconsistent views; load = bounded number of objects per cache. Jump hash and Maglev assume one consistent view (a coordinator), so they give up spread.
Solving the classic problems
| Problem | Solution | How | Advantage | Cost or limit |
|---|---|---|---|---|
| Memcached pool resize wipes the cache | ketama distribution in the client | Memcached::DISTRIBUTION_CONSISTENT + OPT_LIBKETAMA_COMPATIBLE; weights per server | Only about 1/(n+1) misses | No replication, no failover; slight imbalance |
| Redis cache that outgrows one node | Redis Cluster (native) | options.cluster = 'redis' in Laravel, clusters.default seeds | Failover, resharding, MOVED handling | Multi-key commands need hash tags |
| Redis cache of expendable data, no cluster | Client-side sharding | Predis with clusters and no options.cluster; or ShardRing | Simple | No failover, no resharding protocol |
| Sticky sessions behind a load balancer | hash $cookie consistent / hash-type consistent | nginx or HAProxy | Keeps cache locality as backends change | Uneven load, add hash-balance-factor |
| One tenant melts a shard | Bounded loads or tenant splitting | hash-balance-factor 150; or give the tenant its own slot range | Caps the hot node | The tenant's keys leave their home node |
| Hot cache key | Replicate reads or split the key | key#0..key#7, local cache | Spreads reads | Invalidation fan-out |
| Co-locating related keys | Hash tags | {tenant:42}:cart in Redis Cluster | Multi-key commands and Lua scripts legal | Hot tenants make hot slots |
| Resharding a SQL database online | Fixed logical shards + shard_map | Logical replication per shard, flip one row | Moves only 1/n of data | Needs an application router |
| Unbalanced ring | More tokens, Maglev or slots | num_tokens, bigger table | Lower max/mean | More metadata |
Memcached with ketama in Laravel
<?php
// config/cache.php (Laravel 13): Memcached with consistent (ketama) distribution.
// The PHP Memcached extension defaults to modulo distribution; without these
// two options, adding a server to this list re-maps almost every key.
return [
'stores' => [
'memcached' => [
'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
'options' => [
// libketama-compatible: MD5 key hash + weighted consistent hashing.
Memcached::OPT_LIBKETAMA_COMPATIBLE => true,
Memcached::OPT_DISTRIBUTION => Memcached::DISTRIBUTION_CONSISTENT,
Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [
// weight = number of ring points, like the ketama server file
['host' => env('MEMCACHED_A', '10.0.2.11'), 'port' => 11211, 'weight' => 100],
['host' => env('MEMCACHED_B', '10.0.2.12'), 'port' => 11211, 'weight' => 100],
['host' => env('MEMCACHED_C', '10.0.2.13'), 'port' => 11211, 'weight' => 200],
],
],
],
];The PHP Memcached extension documents the two options: OPT_DISTRIBUTION "Specifies the method of distributing item keys to the servers. Currently supported methods are modulo and consistent hashing", and OPT_LIBKETAMA_COMPATIBLE, which "sets the item key hashing algorithm to MD5 and distribution to weighted consistent hashing". Laravel's documentation shows the weight field of each server, which libketama turns into ring points.
Redis Cluster configuration in Laravel
Laravel 13 chooses native clustering by default: "By default, Laravel will use native Redis clustering since the options.cluster configuration value is set to redis. Redis clustering is a great default option, as it gracefully handles failover." For client-side sharding "you may remove the options.cluster configuration value" and note the caveat: "client-side sharding does not handle failover; therefore, it is primarily suited for transient cached data that is available from another primary data store." The file below shows both shapes, plus the independent connections used by the shard resolver.
<?php
// config/database.php (Laravel 13): the redis block, two deployment shapes.
use Illuminate\Support\Str;
return [
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
// 'redis' (the default) = native Redis Cluster: the client learns the
// 16384-slot map from the cluster and follows MOVED and ASK redirections.
// Remove this line for client-side sharding with Predis instead.
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-database-'),
],
// Native cluster: list a few seed nodes; the client discovers the rest.
'clusters' => [
'default' => [
['host' => env('REDIS_NODE_1', '10.0.0.11'), 'port' => 6379, 'password' => env('REDIS_PASSWORD')],
['host' => env('REDIS_NODE_2', '10.0.0.12'), 'port' => 6379, 'password' => env('REDIS_PASSWORD')],
['host' => env('REDIS_NODE_3', '10.0.0.13'), 'port' => 6379, 'password' => env('REDIS_PASSWORD')],
],
],
// Independent single-node connections, used by App\Redis\ShardResolver.
// Client-side sharding has no failover and no resharding protocol, so
// keep it for cache data that also exists in a primary store.
'shard-a' => ['host' => env('REDIS_SHARD_A', '10.0.1.11'), 'port' => 6379, 'database' => 0],
'shard-b' => ['host' => env('REDIS_SHARD_B', '10.0.1.12'), 'port' => 6379, 'database' => 0],
'shard-c' => ['host' => env('REDIS_SHARD_C', '10.0.1.13'), 'port' => 6379, 'database' => 0],
],
];A shard resolver and key design
<?php
declare(strict_types=1);
namespace App\Redis;
use Illuminate\Redis\Connections\Connection;
use Illuminate\Support\Facades\Redis;
/**
* Maps a key to one of the single-node connections in config/database.php.
* Use it for client-side sharding of expendable data (cache, counters).
* For data you cannot lose, use native Redis Cluster instead.
*/
final class ShardResolver
{
public function __construct(private readonly ShardRing $ring)
{
}
/** Build from the connection names; a bigger machine gets more tokens. */
public static function fromConfig(): self
{
return new self(new ShardRing([
'shard-a' => 160,
'shard-b' => 160,
'shard-c' => 320, // twice the memory, twice the tokens
]));
}
public function connectionFor(string $key): Connection
{
return Redis::connection($this->ring->locate($key));
}
public function get(string $key): mixed
{
return $this->connectionFor($key)->get($key);
}
public function put(string $key, string $value, int $ttlSeconds): void
{
$this->connectionFor($key)->setex($key, $ttlSeconds, $value);
}
/**
* Multi-key reads must be grouped per shard first; there is no cross-shard
* MGET. Returns key => value (null for misses).
*
* @param list<string> $keys
* @return array<string, mixed>
*/
public function many(array $keys): array
{
$byShard = [];
foreach ($keys as $key) {
$byShard[$this->ring->locate($key)][] = $key;
}
$out = [];
foreach ($byShard as $shard => $shardKeys) {
$values = Redis::connection($shard)->mget($shardKeys);
foreach ($shardKeys as $i => $key) {
$out[$key] = ($values[$i] ?? false) === false ? null : $values[$i];
}
}
return $out;
}
}<?php
declare(strict_types=1);
namespace App\Redis;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
/**
* Key design for native Redis Cluster: hash tags keep related keys in one
* slot, so multi-key commands, MULTI/EXEC and Lua scripts keep working.
*/
final class ClusterKeys
{
/** CRC-16/XMODEM, the function the cluster spec uses. */
public static function crc16(string $data): int
{
$crc = 0;
for ($i = 0, $n = strlen($data); $i < $n; $i++) {
$crc ^= ord($data[$i]) << 8;
for ($bit = 0; $bit < 8; $bit++) {
$crc = ($crc & 0x8000) ? (($crc << 1) ^ 0x1021) : ($crc << 1);
$crc &= 0xFFFF;
}
}
return $crc;
}
/** HASH_SLOT = CRC16(key) mod 16384, with the {hash tag} rule. */
public static function slot(string $key): int
{
$open = strpos($key, '{');
if ($open !== false) {
$close = strpos($key, '}', $open + 1);
if ($close !== false && $close > $open + 1) {
$key = substr($key, $open + 1, $close - $open - 1);
}
}
return self::crc16($key) % 16384;
}
/** One tenant, one slot: {tenant:42}:cart, {tenant:42}:orders ... */
public static function tenantKey(int $tenantId, string $name): string
{
return "{tenant:{$tenantId}}:{$name}";
}
public static function moveCartToOrders(int $tenantId, string $cartItem): void
{
$cart = self::tenantKey($tenantId, 'cart');
$orders = self::tenantKey($tenantId, 'orders');
// SMOVE names two keys, so both must live in one slot. With the
// {tenant:N} tag they do; without it the server answers
// "CROSSSLOT Keys in request don't hash to the same slot".
Redis::smove($cart, $orders, $cartItem);
}
/**
* Cache::tags() on the redis driver keeps one sorted set per tag
* (key "tag:<name>:entries"). On a cluster that set lives in ONE slot,
* so a very hot tag is a hot shard, and flushing a tag must visit every
* slot that holds one of its entries.
*/
public static function rememberProduct(int $id, callable $load): mixed
{
return Cache::tags(['products', "product:{$id}"])->remember("product:{$id}", 600, $load);
}
public static function forgetProduct(int $id): void
{
Cache::tags(["product:{$id}"])->flush();
}
}Cache tags and sharding. Cache::tags(['a','b']) on the Redis store is implemented with one sorted set per tag named tag:<name>:entries (verified in Illuminate\Cache\RedisTagSet); each put does a ZADD into it, and flush() reads the set and deletes the entries (in chunks of 1000). On a cluster, Laravel's RedisTaggedCache takes a different path for cluster connections (flushClusteredConnection, per-key DEL pipelines for Predis cluster) because keys hash to different slots and a single multi-key command would be CROSSSLOT. Two consequences: the tag set for a hot tag lives in one slot, so every cache write for that tag hits one shard; and a tag flush visits every slot that holds an entry. Prefer few, coarse tags or per-entity keys and explicit forget() for hot paths; Laravel's docs also note that tags are not supported on the file, dynamodb, database and storage cache drivers.
Measuring placement in Go
The movement command drives every scheme through the same experiment (6 nodes, add a 7th, count moved keys) and prints the Redis slot check.
// Command movement measures how many keys change owner when a 7th node
// joins 6 existing nodes, for modulo hashing and each consistent scheme,
// and prints the Redis Cluster slot check.
package main
import (
"fmt"
"academy/consistent-hashing/hashutil"
"academy/consistent-hashing/jump"
"academy/consistent-hashing/maglev"
"academy/consistent-hashing/rendezvous"
"academy/consistent-hashing/ring"
"academy/consistent-hashing/slots"
)
const keys = 120_000
func key(i int) string { return fmt.Sprintf("user:%d", i) }
// moved counts keys whose owner differs between two placement functions.
func moved(before, after func(string) string) (int, int) {
m, toNew := 0, 0
for i := 0; i < keys; i++ {
a, b := before(key(i)), after(key(i))
if a != b {
m++
if b == "node-6" {
toNew++
}
}
}
return m, toNew
}
func main() {
old := make([]string, 6)
for i := range old {
old[i] = fmt.Sprintf("node-%d", i)
}
grown := append(append([]string(nil), old...), "node-6")
fmt.Printf("adding node-6 to 6 nodes, %d keys; ideal movement = 1/7 = %.1f%%\n\n", keys, 100.0/7)
fmt.Printf("%-26s %8s %8s %s\n", "scheme", "moved", "share", "moved to a node other than node-6")
print := func(name string, before, after func(string) string) {
m, to := moved(before, after)
fmt.Printf("%-26s %8d %7.1f%% %d\n", name, m, 100*float64(m)/keys, m-to)
}
mod := func(nodes []string) func(string) string {
return func(k string) string { return nodes[hashutil.Sum64(k)%uint64(len(nodes))] }
}
print("modulo hash % n", mod(old), mod(grown))
for _, t := range []int{1, 16, 256} {
r1, r2 := ring.New(), ring.New()
for _, n := range old {
r1.Add(n, t)
r2.Add(n, t)
}
r2.Add("node-6", t)
loc := func(r *ring.Ring) func(string) string {
return func(k string) string { n, _ := r.Locate(k); return n }
}
print(fmt.Sprintf("ring, %d token(s)/node", t), loc(r1), loc(r2))
}
jmp := func(nodes []string) func(string) string {
return func(k string) string { return nodes[jump.Hash(hashutil.Sum64(k), len(nodes))] }
}
print("jump hash", jmp(old), jmp(grown))
h1, h2 := rendezvous.New(old...), rendezvous.New(grown...)
print("rendezvous (HRW)", h1.Locate, h2.Locate)
m1, m2 := maglev.New(old, maglev.DefaultSize), maglev.New(grown, maglev.DefaultSize)
print("maglev, table 65537", m1.Locate, m2.Locate)
// Redis Cluster: a key's slot never changes; only slot ownership does.
fmt.Println()
fmt.Printf("slot(foo)=%d (CLUSTER KEYSLOT foo is 12182)\n", slots.Slot("foo"))
fmt.Printf("slot({user1000}.following)=%d slot({user1000}.followers)=%d slot(user1000)=%d\n",
slots.Slot("{user1000}.following"), slots.Slot("{user1000}.followers"), slots.Slot("user1000"))
before, after := slots.Assign(6), slots.Assign(7)
mv := 0
for s := range before {
if before[s] != after[s] {
mv++
}
}
fmt.Printf("naive re-split of 16384 slots from 6 to 7 masters moves %d slots (%.1f%%); a rebalance that only fills node-6 moves %d (%.1f%%)\n",
mv, 100*float64(mv)/slots.Count, slots.Count/7, 100.0/7)
}The ring file (ring/ring.go, shown above) holds Add, Remove, Locate, Replicas and the Bounded wrapper. For fixed slots use the slots module and a table owner[slot] = node; moving a slot is one assignment plus a data copy.
Choosing a scheme
| Workload | Recommended | Extra technique | Reason |
|---|---|---|---|
| Memcached or Redis as a cache, nodes come and go | Ketama ring or Redis Cluster slots | Weights by memory, warm-up job | Resizing must not wipe the cache |
| Durable key-value store, 10 to 1000 nodes | Ring with tokens (Cassandra) or slots (Redis Cluster, Dynamo strategy 3) | Rack-aware replica placement, allocate_tokens_for_keyspace | Per-node rebalancing, failure dispersal |
| Numbered shards, add-at-tail only | Jump hash | A shard_map for later splitting | No memory, perfect balance |
| Few nodes (<50), top-k replicas wanted | Rendezvous (HRW) | Weighted variant | Simplest, no state |
| L4/L7 load balancer, millions of flows | Maglev | Connection tracking table | O(1) lookup, resilient |
| Cache-locality load balancing with skew | Ring + bounded loads | hash-balance-factor 125-200 | Caps the hot node |
| Fixed shard count, never resized (a relational database) | Modulo over many logical shards | shard_map table | Resizing by moving shards |
| Kafka-style log partitions | Modulo on a fixed partition count | Plan the count up front | Ordering depends on key to partition |
| Anything needing range scans | Range partitioning (not hashing) | Hash prefix for hot spots | Hashing destroys key order |
In architecture: from a single process to a distributed system
Monolith (one process, one database)
One process and one database need no placement scheme: a row is where it is. Consistent hashing first appears as a cache: a monolith with one Redis uses none; the moment you add a second Memcached for the page cache you need OPT_DISTRIBUTION consistent so that growing to three does not wipe it. A single PostgreSQL with a hash-partitioned table (MODULUS 8) is the simplest correct use of modulo: the partition count is fixed by design and the planner prunes partitions. See Partitioning & Sharding in PostgreSQL.
Modular monolith / multiple databases
When modules own their own databases (orders, billing, catalogue), each database is a shard of the whole system by module, not by key. If one module outgrows a node, shard that module's tables by tenant id with a shard_map: 1024 logical shards, 4 physical databases to start. The router is a class (TenantShardRouter) that hashes tenant_id, looks up the shard, and picks the connection with DB::connection($node). Hash tags in Redis keep a tenant's keys together; Cassandra's partition key is the tenant.
Microservices
Each service owns its data and chooses its placement independently. The place where hashing crosses a service boundary is the message key: an order-service publishes events with key = order_id to a Kafka topic with 12 partitions; murmur2(key) % 12 decides the partition, so all events of one order are ordered. Raising 12 to 24 reshuffles keys, so size topics ahead or version the topic. At the edge, an Envoy sidecar in front of the catalogue cache fleet uses ring_hash with the request path as key so one cache server holds each product; a hot product is handled by bounded load or a local cache. A saga or outbox flow is the place to remember that no placement scheme gives cross-key atomicity: see Distributed SQL, Consensus & 2PC.
Distributed data (replicas, caches, sharded or distributed SQL, multi-region)
In a Dynamo-style store the ring decides the replica set and the consistency level (QUORUM, LOCAL_QUORUM) decides how many of them must answer; read your writes needs R + W > N. During a membership change, ranges are in transit: Cassandra streams them, Redis answers ASK, and for a while a key can be on two nodes, so reads may be stale. Caches in front of the database multiply the problem: a ring-hashed cache that loses a node loses its slice, the database sees that slice's full load, and a thundering herd appears; protect with request coalescing (singleflight in Go, Cache::lock / Cache::flexible in Laravel) and warm-up. Multi-region: keep the ring per region and route by a region prefix, or use range-based systems (CockroachDB, Spanner) that place by locality instead of hash. See Replication, Read Replicas & Failover and Eventual Consistency in Database Systems.
Scaling path: 1x, 10x, 100x
| Load | Typical shape | Placement |
|---|---|---|
| 1x | One PostgreSQL, one Redis | None |
| 10x | Redis Cluster 3 masters, or 3 Memcached with ketama; read replicas | Slots / ring; 1024 logical DB shards in a shard_map |
| 100x | Cassandra or DynamoDB ring, hundreds of Redis slots, a Maglev/Envoy layer | Tokens or slots, bounded loads for hot keys, rack-aware replicas |
| 1000x | Multi-region cell architecture | Hash into cells (a cell is a full stack), consistent routing at the edge |
At every step the rule is the same: fix the number of logical partitions early (slots, shards), move whole partitions, and keep the hash and the routing table versioned.
Lab
Everything runs with the standard library only. From the repository root:
cd docs/snippets/database/consistent-hashing/go
gofmt -l . && go vet ./... # both silent
go run ./cmd/distribution # histograms for ring, jump, HRW, Maglev, bounded load
go run ./cmd/movement # keys moved when node 7 joins; Redis slot checkThe modules are hashutil (FNV-1a plus a splitmix64 finalizer), ring (vnodes, replicas, bounded load), jump, rendezvous, maglev, slots (CRC16, hash tags).
Experiment 1: distribution histogram before and after adding a node
distribution prints the histogram for 6 nodes; movement adds the 7th. Measured output (120,000 keys, deterministic, abbreviated):
ring, 1 token(s) per node (max/mean = 1.47) node-0 27570 #### node-1 14961 ## node-3 11162 # node-5 29385 ####
ring, 256 token(s) per node (max/mean = 1.18) node-0 23622 node-3 16928 node-5 21188
jump hash (max/mean = 1.01) every node 19890 .. 20114
rendezvous (HRW) (max/mean = 1.01) every node 19867 .. 20135
maglev, table 65537 (max/mean = 1.02) every node 19773 .. 20379
skewed traffic, plain ring, 16 tokens (max/mean = 1.73) node-5 34535
skewed traffic, bounded load c=1.25 (max/mean = 1.25) node-5 25000After adding node-6 the expected load per node is 17,143. Re-run the histogram with seven names to see the "after" shape; the movement command shows what had to move to get there:
adding node-6 to 6 nodes, 120000 keys; ideal movement = 1/7 = 14.3%
scheme moved share moved to a node other than node-6
modulo hash % n 102776 85.6% 85601
ring, 1 token(s)/node 19051 15.9% 0
ring, 16 token(s)/node 19385 16.2% 0
ring, 256 token(s)/node 18409 15.3% 0
jump hash 17073 14.2% 0
rendezvous (HRW) 17132 14.3% 0
maglev, table 65537 17564 14.6% 288
slot(foo)=12182 (CLUSTER KEYSLOT foo is 12182)Experiment 2: the effect of tokens
The last block of distribution runs 20 clusters per token count. Expected: the average max/mean falls from 2.56 (1 token) through 1.35 (16), 1.15 (64), 1.10 (256) to 1.04 (1024).
Experiment 3: a real Redis Cluster slot check
docker run -d --name rc -p 7000-7005:7000-7005 grokzen/redis-cluster:latest # any 6-node cluster image
redis-cli -c -p 7000 CLUSTER KEYSLOT foo # 12182
redis-cli -c -p 7000 CLUSTER KEYSLOT '{user1000}.following' # same as for {user1000}.followers
redis-cli -c -p 7000 MSET a 1 b 2 # (error) CROSSSLOT Keys in request don't hash to the same slot
redis-cli -c -p 7000 MSET '{t}a' 1 '{t}b' 2 # OK
redis-cli -p 7000 CLUSTER SLOTS | head # slot ranges per masterExperiment 4: Cassandra token ownership
docker run -d --name c1 cassandra:5
docker exec c1 nodetool status
docker exec c1 nodetool ring | head
docker exec c1 cqlsh -e "CREATE KEYSPACE ks WITH replication={'class':'SimpleStrategy','replication_factor':1}; CREATE TABLE ks.t(k text PRIMARY KEY, v int);"
docker exec c1 nodetool getendpoints ks t some-key # the replica set of a keyCommon misconceptions
| Belief | Reality |
|---|---|
| "Consistent hashing balances load evenly" | It minimises movement; evenness needs many tokens, slots, Maglev, or bounded loads (1 token: max/mean 2.56 average, 4.04 worst) |
| "Adding a node with modulo hashing moves 1/n of the keys" | It moves about n/(n+1) (85.6% for 6 to 7), including between old nodes |
| "Redis Cluster uses a ring" | It uses 16384 fixed hash slots with CRC16 mod 16384 and an explicit table |
| "Kafka partitions use consistent hashing" | murmur2(key) % numPartitions: adding partitions remaps keys |
| "PostgreSQL / MySQL hash partitioning can be resized cheaply" | Modulus changes re-partition the rows |
| "More virtual nodes is always better" | Cassandra warns of availability, repair and scan costs; 16 to 256 are typical |
| "Replicas are the next N tokens" | They are the next N distinct physical nodes |
| "Jump hash replaces the ring" | It numbers buckets, cannot remove arbitrary ones, cannot weight |
| "Consistent hashing fixes hot keys" | One key lands on one node; use replication, key splitting or bounded loads |
| "Any hash function will do" | Positions need good avalanche: FNV-1a alone clusters vnodes; Python hash() and Go maphash differ per process |
| "Resharding is free because only 1/n moves" | Streaming, cleanup, Merkle tree rebuilds and cache warm-up still cost (Dynamo: almost a day) |
| "Client-side sharding in Laravel handles failover" | Laravel's docs: it does not; keep it for transient cache data |
Cheat sheet
| Topic | What to remember |
|---|---|
| Modulo | h % n: moves n/(n+1) of keys when n changes |
| Ring | Sorted positions, first point >= hash(key), wrap around; join moves about 1/(n+1) |
| Vnodes | 100-200 points per server (ketama); Cassandra default num_tokens: 16; weight = tokens |
| Replication | Next N distinct physical nodes clockwise; skip same-node tokens |
| Hash slots | Redis Cluster: CRC16(key) mod 16384, table slot to node, {tag} co-locates |
| Bounded load | Capacity ceil(c x mean), probe clockwise; HAProxy hash-balance-factor 125-200 |
| Jump hash | 5 lines, no memory, buckets 0..n-1, only the last can leave |
| Rendezvous | Score every node, max wins, O(n), top-k = replicas |
| Maglev | Prime table M (65537), permutation per backend, O(1) lookup |
| Hotspots | Hash cannot split one key: replicate, split the key, bound load |
| Hash function | Stable across processes, good avalanche: xxHash, murmur3, CRC16; FNV-1a needs a finalizer |
| Laravel Redis | options.cluster = 'redis' = native Cluster; remove it for Predis client-side sharding |
| Laravel Memcached | OPT_DISTRIBUTION => DISTRIBUTION_CONSISTENT + OPT_LIBKETAMA_COMPATIBLE |
| Resharding | Move partitions not keys; nodetool cleanup, redis-cli --cluster rebalance |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why does hash(key) % n remap about 86% of keys when a 6-node cache becomes 7 nodes? Must-know
Answer
Answer: The remainder modulo 6 and modulo 7 agree only for about 1 key in 7, whatever the hash. About n/(n+1) of the keys change owner, and they move between old nodes as well. See Modulo hashing.
2 — On a ring with one token per node, who gets a removed node's keys? How do virtual nodes change this? Must-know
Answer
Answer: The next node clockwise takes the whole arc, doubling its load. With T tokens per node the arcs are many and small, owned by many different successors, so the load disperses. See Virtual nodes.
3 — How does Dynamo build a preference list when virtual nodes are used? Good to know
Answer
Answer: It walks the ring clockwise and collects the first N distinct physical nodes, skipping tokens that belong to a node already chosen. See Replication along the ring.
4 — What is HASH_SLOT in Redis Cluster and what does a hash tag do? Must-know
Answer
Answer: CRC16(key) mod 16384; if the key contains {...} with at least one byte inside, only that substring is hashed, so {user1000}.following and {user1000}.followers share a slot and can be used together in multi-key commands. See Hash slots.
5 — Why can jump hash not remove node 3 of 10? Good to know
Answer
Answer: It returns a number from 0 to n-1 with no names; removing bucket 3 would renumber buckets 4 to 9 and remap their keys. Only the highest-numbered bucket can leave. See Jump hash.
6 — What does the bounded-load capacity ceil(c x m / n) guarantee, and what does it cost? Good to know
Answer
Answer: No node holds more than c times the average load; the cost is a somewhat higher number of key moves than plain consistent hashing (within O(1/epsilon^2) for epsilon <= 1) and a counter to maintain. See Bounded-load consistent hashing.
7 — How do you set Laravel 13 to use Redis Cluster versus client-side sharding? Good to know
Answer
Answer: Native cluster is the default: options.cluster = 'redis' plus clusters.default seed nodes. For client-side sharding (Predis) remove options.cluster; this has no failover and suits only transient cache data. See Redis Cluster configuration in Laravel.
8 — Which of PostgreSQL hash partitioning, Kafka's default partitioner and Cassandra uses real consistent hashing? Important
Answer
Answer: Only Cassandra (token ring). PostgreSQL uses modulus/remainder and Kafka uses murmur2(key) % numPartitions. See Per-product behaviour.
9 — A single celebrity key overloads one node on a good ring. Name three mitigations. Must-know
Answer
Answer: Replicate reads to several nodes, split the key (key#0..key#7), put a local cache or CDN in front, or use bounded-load hashing so the overflow goes to a neighbour. See Hotspots.
10 — Why is hash-function choice part of the data format? Important
Answer
Answer: Every client must compute the same position; changing the hash re-maps every key. Use a stable documented hash (xxHash, murmur3, CRC16) and never a per-process randomised one. See Hash functions.
Glossary
| Term | Meaning |
|---|---|
| Consistent hashing | Mapping keys to nodes so that a membership change moves only about 1/(n+1) of the keys |
| Modulo hashing | hash(key) mod n; remaps about n/(n+1) of keys when n changes |
| Hash ring | The hash space bent into a circle; positions compared numerically with wrap-around |
| Token | One position on a Dynamo-style ring owned by a node (Cassandra term) |
| Virtual node (vnode) | A token seen as a virtual server; one physical node has many |
num_tokens | Cassandra setting: tokens per node; default 16 |
| Preference list | The ordered list of distinct nodes responsible for a key |
| Replication factor (RF, N) | Number of replicas per key |
| Hash slot | A fixed bucket of the hash space; Redis Cluster has 16384 |
| Hash tag | {...} part of a Redis key that alone is hashed, to co-locate keys |
CROSSSLOT | Redis Cluster error for a multi-key command spanning slots |
MOVED / ASK | Redis Cluster redirections: permanent vs during migration |
MIGRATE | Redis command that moves a key to another node, used in resharding |
| Bootstrap | A new node joining a ring and streaming its ranges |
nodetool cleanup | Cassandra command that deletes data a node no longer owns |
| Partitioner | Cassandra component hashing partition keys to tokens (Murmur3Partitioner) |
| Bounded loads | Consistent hashing with a per-node capacity ceil(c x average) |
Balance factor c | 1 + epsilon; HAProxy hash-balance-factor as a percentage |
| Jump consistent hash | Lamping and Veach's memoryless algorithm over numbered buckets |
| Rendezvous / HRW | Highest Random Weight: each node scores a key, the maximum wins |
| Maglev hashing | Lookup-table consistent hash from Google's Maglev load balancer (prime table size M) |
| Continuum | Ketama's name for its ring of points |
| Ketama | The memcached client hashing scheme (100-200 points per server, MD5) |
| Smoothness, spread, load | Karger's three consistency properties |
| Hotspot | A node (or key) carrying disproportionate load |
| Load balancing efficiency | Dynamo's mean load / max load |
| Avalanche | Property that one input bit flips about half the output bits |
| Hinted handoff | Dynamo/Cassandra: another node holds a write for a down replica |
| Sloppy quorum | Quorum over the first N healthy nodes of the preference list, not the first N |
| Gossip | Peer-to-peer membership protocol used by Dynamo, Cassandra and Redis Cluster |
| Logical shard | A fixed small partition, many per physical node, moved as a unit |
shard_map | A table mapping logical shard to physical node |
| Thundering herd | Many cache misses hitting the database at once after a remap |
hash-type consistent | HAProxy: server table is a tree with many occurrences per server |
ring_hash / maglev | Envoy consistent-hash load balancing policies |
OPT_LIBKETAMA_COMPATIBLE | PHP Memcached option: MD5 and weighted consistent distribution |
Cache::tags | Laravel cache tagging; one sorted set per tag on Redis |
hash/fnv | Go standard-library FNV hashes (New64a) |
xxhash | Fast non-cryptographic hash; Go github.com/cespare/xxhash/v2, PHP hash('xxh3') |
| Murmur2 / Murmur3 | Kafka's / Cassandra's partitioning hashes |
| CRC16 | The 16-bit CRC used by Redis Cluster slots |
| Strategy 3 (Dynamo) | Q equal partitions, each node holding Q/S of them |
| vBucket | Couchbase's fixed slot, same idea as a hash slot |
| Merkle tree | Hash tree used by anti-entropy repair; must be rebuilt when ranges change |
References
- Karger, Lehman, Leighton, Panigrahy, Levine, Lewin, "Consistent Hashing and Random Trees: Distributed Caching Protocols for Relieving Hot Spots on the World Wide Web", STOC 1997. PDF
- DeCandia et al., "Dynamo: Amazon's Highly Available Key-value Store", SOSP 2007, sections 4.2, 4.3, 6.2. PDF
- Lamping, Veach, "A Fast, Minimal Memory, Consistent Hash Algorithm", 2014. arXiv 1406.2294
- Mirrokni, Thorup, Zadimoghaddam, "Consistent Hashing with Bounded Loads", 2016. arXiv 1608.01350
- Eisenbud et al., "Maglev: A Fast and Reliable Software Network Load Balancer", NSDI 2016. PDF
- Thaler, Ravishankar, "A Name-Based Mapping Scheme for Rendezvous", CSE-TR-316-96. PDF; secondary: Wikipedia, Rendezvous hashing
- Redis: Redis Cluster specification
- Apache Cassandra: Dynamo architecture (token ring, vnodes), cassandra.yaml
- RJ, libketama README
- nginx:
ngx_http_upstream_modulehash directive - HAProxy: Configuration manual (
hash-type,hash-balance-factor) - Envoy: Load balancers: ring hash and Maglev
- Riak KV: Clusters
- MongoDB: Hashed Sharding
- Amazon DynamoDB: Partitions and data distribution
- PostgreSQL: Table partitioning; MySQL 8.4 (via web.archive.org): HASH partitioning; Citus: Data modeling
- Apache Kafka source:
BuiltInPartitioner.java - Go:
hash/fnv,xxhash/v2; gomemcacheselector.go - PHP: Memcached constants
- Laravel 13: Redis, Cache; framework source:
RedisTaggedCache.php,RedisTagSet.php