Anillo de Hashing Consistente
Simulador de anillo de hash con nodos virtuales y análisis de migración.
Con pocos puntos por servidor los arcos son desiguales y algunos servidores reciben muchas más claves. Sube los nodos virtuales.
Acerca de esta herramienta
El hashing consistente decide qué servidor guarda cada clave de una forma que resiste la llegada y salida de servidores. Servidores y claves se proyectan con un hash sobre el mismo espacio circular (el anillo); cada clave pertenece al primer punto de servidor que se encuentra en sentido horario desde su hash. Cuando un servidor desaparece, solo se mueven las claves de sus arcos —al siguiente servidor del anillo— en lugar de redistribuirse casi todas.
Este laboratorio coloca 1000 claves de ejemplo en un anillo con un hash FNV-1a real. Activa o desactiva servidores y verás cuántas claves se movieron de verdad, junto a las que habría movido un simple hash mod N. Un control deslizante de nodos virtuales muestra cómo dar muchos puntos a cada servidor equilibra la carga.
Cómo usar: Anillo de Hashing Consistente
- Empieza con los servidores por defecto y mira las barras de claves por servidor; la línea fina marca la parte ideal 1/N.
- Desactiva un servidor. La línea de estado compara las claves movidas por el hashing consistente y por hash mod N.
- Vuelve a activarlo, o añade otro, y compara de nuevo.
- Lleva el control de nodos virtuales de 1 a más de 100 y observa cómo baja el desequilibrio (desviación típica dividida entre la media).
Ejemplos
Quitar uno de cuatro servidores
1000 claves, 4 servidores, se quita el servidor C
El hashing consistente mueve solo el ~25 % de C; hash mod N movería alrededor del 75 % de todas las claves
Efecto de los nodos virtuales
4 servidores, 1 punto cada uno frente a 150 puntos cada uno
Con 1 punto, un servidor puede quedarse con más del 40 % de las claves; con 150, todos se mantienen cerca del 25 %
Implementación en cinco lenguajes
El mismo algoritmo en Python, JavaScript, Java, Go y C++. Cada programa está completo y se puede ejecutar; los comentarios indican lo que imprime.
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
} Por qué falla hash mod N
Con server = hash(key) mod N, cambiar N cambia el resultado de casi todas las claves: al pasar de 4 a 3 servidores, una clave solo se queda donde estaba si hash mod 4 coincide con hash mod 3. En una caché eso es una avalancha de fallos casi total; en una base de datos, mover casi todos los datos.
Dónde se usa
- Cachés distribuidas: clientes de memcached (ketama), balanceo por anillo de hash en Envoy y NGINX.
- Bases de datos particionadas: Amazon Dynamo, Cassandra y Riak colocan los datos en anillos de tokens con nodos virtuales.
- Variantes: el hashing rendezvous (mayor peso aleatorio), Jump Consistent Hash y el hashing Maglev equilibran de forma distinta memoria, velocidad y reparto.
Preguntas frecuentes
Respuestas a tus dudas sobre el funcionamiento y la seguridad de los datos.
¿Qué es un nodo virtual?
Un servidor físico se proyecta en muchos puntos del anillo («A#0», «A#1», …). Arcos más numerosos y pequeños compensan el azar de la colocación, y la carga de un servidor retirado se reparte entre muchos vecinos en lugar de uno solo.
¿Puedo dar más carga a un servidor más potente?
Sí. Dale proporcionalmente más nodos virtuales y tendrá una parte proporcionalmente mayor del anillo.
¿Qué función hash debo usar?
Cualquier hash no criptográfico rápido y bien mezclado sirve: MurmurHash3, xxHash o FNV con una etapa final de mezcla. No hace falta fortaleza criptográfica.
¿Mis datos están seguros con esta herramienta?
Totalmente seguros. Todo el procesamiento se ejecuta de forma local en tu navegador sin enviar información a ningún servidor.
Herramientas relacionadas
Elección de líder, replicación de registros y particiones de red en clúster.
Genera hashes SHA-256, MD5 y convierte URL, entidades HTML y Hexadecimal.
Visualizador interactivo de BST con inserción, eliminación y recorridos.
Proyectos destacados tech-fun.net
Explora más herramientas de IA y productividad
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.