Belajar
← All lessons

How consistent hashing works

Keys on a hash ring

ring.js

const ring = servers  .map((name) => ({ name, pos: hash32(name) }))  .sort((a, b) => a.pos - b.pos); function serverFor(key) {  const h = hash32(key);  const next = ring.find((s) => s.pos >= h);  return next ?? ring[0]; // past the last spot, wrap to the first}

modulo.js

function serverFor(key) {  // N changes, so almost every key gets a new server  return servers[hash32(key) % servers.length];}

Look up a key, flip servers and count what moves

Key
Servers
Lookup

lookup.js

function serverFor(key) {  const h = hash32(key);  const next = ring.find((s) => s.pos >= h);  return (next ?? ring[0]).name;} function serverForModulo(key) {  return servers[hash32(key) % servers.length];}

Add one server to a big cluster with and without virtual nodes

Servers now
Spots per server110100
Keys that move when one more server joins
Keys per server on the ring

Counted over 10,000 real keys, user:1 to user:10000

ring.js

// each server takes many spots, which evens out the arcsfor (const name of servers) {  for (let i = 0; i < SPOTS; i++) {    ring.push({ name, pos: hash32(`${name}#${i}`) });  }}ring.sort((a, b) => a.pos - b.pos);

Topics

Next: How circuit breakers work

Open lesson