Consistent Hashing Ring
Consistent hashing ring simulator with virtual nodes and rehash avalanche analysis.
With few points per server the arcs are uneven, so some servers get far more keys. Raise the virtual nodes slider.
About this tool
Consistent hashing decides which server stores which key in a way that survives servers joining and leaving. Servers and keys are hashed onto the same circular space (the ring); each key belongs to the first server point found clockwise from the key’s hash. When a server disappears, only the keys on its arcs move — to the next server along the ring — instead of almost every key being reshuffled.
This lab places 1,000 sample keys on a ring with real FNV-1a hashing. Toggle servers and it reports how many keys actually moved, next to what plain hash mod N would have moved. A virtual-node slider shows how giving each server many points evens out the load.
How to use Consistent Hashing Ring
- Start with the default servers and look at the keys-per-server bars; the thin line marks the ideal 1/N share.
- Switch a server off. The status line shows the keys consistent hashing moved versus hash mod N.
- Turn it back on, or add another, and compare again.
- Move the virtual-node slider from 1 up to 100+ and watch the imbalance (standard deviation divided by mean) drop.
Examples
Removing one of four servers
1,000 keys, 4 servers, server C removed
Consistent hashing moves only C’s ~25%; hash mod N would move about 75% of all keys
Effect of virtual nodes
4 servers, 1 point each vs. 150 points each
With 1 point one server may hold over 40% of keys; with 150 points every server stays close to 25%
Implementation in five languages
The same algorithm in Python, JavaScript, Java, Go and C++. Each program is complete and runnable; the comments show what it prints.
import bisect
def fnv1a(s):
"""32-bit FNV-1a over the UTF-8 bytes of s."""
h = 0x811C9DC5
for b in s.encode():
h ^= b
h = (h * 0x01000193) & 0xFFFFFFFF
return h
class Ring:
def __init__(self, vnodes=100):
self.vnodes = vnodes
self.points = [] # sorted (hash, server) pairs
def add(self, server):
for i in range(self.vnodes):
bisect.insort(self.points, (fnv1a(f"{server}#{i}"), server))
def remove(self, server):
self.points = [p for p in self.points if p[1] != server]
def lookup(self, key):
h = fnv1a(key)
i = bisect.bisect_left(self.points, (h, "")) # first point >= h
return self.points[i % len(self.points)][1] # wrap around
ring = Ring()
for s in ["A", "B", "C", "D"]:
ring.add(s)
keys = [f"user:{i}" for i in range(1000)]
before = {k: ring.lookup(k) for k in keys}
ring.remove("C")
moved = sum(before[k] != ring.lookup(k) for k in keys)
print(sum(v == "C" for v in before.values()), moved) # 196 196: only the keys on C move // 32-bit FNV-1a over the UTF-8 bytes of s.
function fnv1a(s) {
let h = 0x811c9dc5;
for (const b of new TextEncoder().encode(s)) {
h ^= b;
h = Math.imul(h, 0x01000193) >>> 0;
}
return h >>> 0;
}
class Ring {
constructor(vnodes = 100) {
this.vnodes = vnodes;
this.points = []; // sorted { hash, server }
}
add(server) {
for (let i = 0; i < this.vnodes; i++) {
this.points.push({ hash: fnv1a(`${server}#${i}`), server });
}
this.points.sort((a, b) => a.hash - b.hash || (a.server < b.server ? -1 : 1));
}
remove(server) {
this.points = this.points.filter((p) => p.server !== server);
}
lookup(key) {
const h = fnv1a(key);
let lo = 0, hi = this.points.length; // binary search: first point >= h
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (this.points[mid].hash < h) lo = mid + 1;
else hi = mid;
}
return this.points[lo % this.points.length].server; // wrap around
}
}
const ring = new Ring();
for (const s of ['A', 'B', 'C', 'D']) ring.add(s);
const keys = Array.from({ length: 1000 }, (_, i) => `user:${i}`);
const before = new Map(keys.map((k) => [k, ring.lookup(k)]));
ring.remove('C');
const moved = keys.filter((k) => before.get(k) !== ring.lookup(k)).length;
const onC = [...before.values()].filter((v) => v === 'C').length;
console.log(onC, moved); // 196 196: only the keys on C move import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Main {
// 32-bit FNV-1a over the UTF-8 bytes of s, returned as an unsigned value.
static long fnv1a(String s) {
int h = 0x811c9dc5;
for (byte b : s.getBytes(StandardCharsets.UTF_8)) {
h ^= (b & 0xff);
h *= 0x01000193;
}
return h & 0xffffffffL;
}
static class Ring {
private final TreeMap<Long, String> points = new TreeMap<>();
private final int vnodes;
Ring(int vnodes) { this.vnodes = vnodes; }
void add(String server) {
for (int i = 0; i < vnodes; i++) points.put(fnv1a(server + "#" + i), server);
}
void remove(String server) {
points.values().removeIf(server::equals);
}
String lookup(String key) {
Map.Entry<Long, String> e = points.ceilingEntry(fnv1a(key)); // first point >= h
return (e != null ? e : points.firstEntry()).getValue(); // wrap around
}
}
public static void main(String[] args) {
Ring ring = new Ring(100);
for (String s : new String[] {"A", "B", "C", "D"}) ring.add(s);
Map<String, String> before = new HashMap<>();
for (int i = 0; i < 1000; i++) before.put("user:" + i, ring.lookup("user:" + i));
ring.remove("C");
int moved = 0, onC = 0;
for (Map.Entry<String, String> e : before.entrySet()) {
if (e.getValue().equals("C")) onC++;
if (!e.getValue().equals(ring.lookup(e.getKey()))) moved++;
}
System.out.println(onC + " " + moved); // 196 196: only the keys on C move
}
} package main
import (
"fmt"
"sort"
)
// fnv1a is 32-bit FNV-1a over the bytes of s (the standard library's hash/fnv gives the same result).
func fnv1a(s string) uint32 {
h := uint32(0x811c9dc5)
for i := 0; i < len(s); i++ {
h ^= uint32(s[i])
h *= 0x01000193
}
return h
}
type point struct {
hash uint32
server string
}
type Ring struct {
vnodes int
points []point // sorted by hash
}
func (r *Ring) Add(server string) {
for i := 0; i < r.vnodes; i++ {
r.points = append(r.points, point{fnv1a(fmt.Sprintf("%s#%d", server, i)), server})
}
sort.Slice(r.points, func(a, b int) bool {
if r.points[a].hash != r.points[b].hash {
return r.points[a].hash < r.points[b].hash
}
return r.points[a].server < r.points[b].server
})
}
func (r *Ring) Remove(server string) {
kept := r.points[:0]
for _, p := range r.points {
if p.server != server {
kept = append(kept, p)
}
}
r.points = kept
}
func (r *Ring) Lookup(key string) string {
h := fnv1a(key)
i := sort.Search(len(r.points), func(i int) bool { return r.points[i].hash >= h }) // first point >= h
return r.points[i%len(r.points)].server // wrap around
}
func main() {
ring := &Ring{vnodes: 100}
for _, s := range []string{"A", "B", "C", "D"} {
ring.Add(s)
}
before := map[string]string{}
for i := 0; i < 1000; i++ {
k := fmt.Sprintf("user:%d", i)
before[k] = ring.Lookup(k)
}
ring.Remove("C")
moved, onC := 0, 0
for k, v := range before {
if v == "C" {
onC++
}
if v != ring.Lookup(k) {
moved++
}
}
fmt.Println(onC, moved) // 196 196: only the keys on C move
} #include <cstdint>
#include <iostream>
#include <iterator>
#include <map>
#include <string>
#include <unordered_map>
// 32-bit FNV-1a over the bytes of s.
uint32_t fnv1a(const std::string& s) {
uint32_t h = 0x811c9dc5u;
for (unsigned char c : s) {
h ^= c;
h *= 0x01000193u;
}
return h;
}
class Ring {
std::map<uint32_t, std::string> points; // hash -> server, kept sorted
int vnodes;
public:
explicit Ring(int v) : vnodes(v) {}
void add(const std::string& server) {
for (int i = 0; i < vnodes; i++) points.emplace(fnv1a(server + "#" + std::to_string(i)), server);
}
void remove(const std::string& server) {
for (auto it = points.begin(); it != points.end();) {
it = it->second == server ? points.erase(it) : std::next(it);
}
}
const std::string& lookup(const std::string& key) const {
auto it = points.lower_bound(fnv1a(key)); // first point >= h
return (it != points.end() ? it : points.begin())->second; // wrap around
}
};
int main() {
Ring ring(100);
for (const char* s : {"A", "B", "C", "D"}) ring.add(s);
std::unordered_map<std::string, std::string> before;
for (int i = 0; i < 1000; i++) {
std::string k = "user:" + std::to_string(i);
before[k] = ring.lookup(k);
}
ring.remove("C");
int moved = 0, onC = 0;
for (const auto& [k, v] : before) {
if (v == "C") onC++;
if (v != ring.lookup(k)) moved++;
}
std::cout << onC << ' ' << moved << '\n'; // 196 196: only the keys on C move
} Why hash mod N fails
With server = hash(key) mod N, changing N changes the result for nearly every key: going from 4 to 3 servers keeps a key in place only if hash mod 4 equals hash mod 3. For a cache this means a near-total miss storm; for a database it means moving almost all data.
Where it is used
- Distributed caches: memcached clients (ketama), Envoy and NGINX ring-hash load balancing.
- Partitioned databases: Amazon Dynamo, Cassandra and Riak place data on token rings with virtual nodes.
- Variants: rendezvous (highest random weight) hashing, jump consistent hash and Maglev hashing trade memory, speed and balance differently.
Frequently asked questions
Everything you need to know about this tool and data security.
What is a virtual node?
One physical server is hashed to many points on the ring (e.g. “A#0”, “A#1”, …). More, smaller arcs average out the luck of hash placement, and a removed server’s load spreads over many neighbours instead of one.
Can I give a bigger server more load?
Yes. Give it proportionally more virtual nodes and it will own a proportionally larger share of the ring.
Which hash function should I use?
Any fast, well-mixed non-cryptographic hash works: MurmurHash3, xxHash or FNV with a finalizer. Cryptographic strength is not needed.
Is my data safe when using this tool?
Yes, 100% safe. This tool operates entirely inside your web browser using client-side JavaScript and WebAssembly. Your data never touches any external server.
Related Tools
Distributed consensus visualization with leader election, log replication, and network partitions.
Generate SHA-256, MD5 hashes, and convert URL, HTML entities, and Hex.
Interactive BST visualizer with insertion, deletion, and tree traversals.
Featured Projects tech-fun.net
Explore more AI & productivity tools
Nihongo GameBox
Master Japanese typing, Kana, and JLPT N5–N1 vocabulary through interactive retro arcade games.
ResumeGPT
Tailors CVs and cover letters to every job opportunity with a multi-agent LLM pipeline, job tracking, and scheduled discovery.
CollectMind
Turns your bookmarks into a searchable AI knowledge base — entirely on-device, powered by Chrome's built-in Gemini Nano.