Anello di Hashing Consistente
Simulatore di hash ring con nodi virtuali e analisi di redistribuzione dei dati.
Con pochi punti per server gli archi sono disuguali e alcuni server ricevono molte più chiavi. Aumenta i nodi virtuali.
Informazioni su questo strumento
L’hashing consistente decide quale server conserva ciascuna chiave in un modo che regge l’arrivo e l’uscita dei server. Server e chiavi vengono mappati con un hash sullo stesso spazio circolare (l’anello); ogni chiave appartiene al primo punto di un server che si incontra in senso orario a partire dal suo hash. Quando un server scompare, si spostano solo le chiavi dei suoi archi — verso il server successivo sull’anello — invece di rimescolare quasi tutte le chiavi.
Questo laboratorio colloca 1000 chiavi di esempio su un anello con un vero hash FNV-1a. Attiva e disattiva i server e vedrai quante chiavi si sono davvero spostate, accanto a quante ne avrebbe spostate un semplice hash mod N. Un cursore dei nodi virtuali mostra come dare molti punti a ogni server bilanci il carico.
Come usare: Anello di Hashing Consistente
- Parti dai server predefiniti e guarda le barre delle chiavi per server; la linea sottile indica la quota ideale 1/N.
- Disattiva un server. La riga di stato confronta le chiavi spostate dall’hashing consistente e da hash mod N.
- Riattivalo, o aggiungine un altro, e confronta di nuovo.
- Porta il cursore dei nodi virtuali da 1 a oltre 100 e guarda lo squilibrio (deviazione standard divisa per la media) scendere.
Esempi
Togliere un server su quattro
1000 chiavi, 4 server, rimosso il server C
L’hashing consistente sposta solo il ~25 % di C; hash mod N sposterebbe circa il 75 % di tutte le chiavi
Effetto dei nodi virtuali
4 server, 1 punto ciascuno contro 150 punti ciascuno
Con 1 punto un server può tenere oltre il 40 % delle chiavi; con 150 punti ognuno resta vicino al 25 %
Implementazione in cinque linguaggi
Lo stesso algoritmo in Python, JavaScript, Java, Go e C++. Ogni programma è completo ed eseguibile; i commenti indicano cosa stampa.
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
} Perché hash mod N non funziona
Con server = hash(key) mod N, cambiare N cambia il risultato per quasi ogni chiave: passando da 4 a 3 server, una chiave resta al suo posto solo se hash mod 4 è uguale a hash mod 3. Per una cache significa una valanga di miss quasi totale; per un database, spostare quasi tutti i dati.
Dove si usa
- Cache distribuite: client memcached (ketama), bilanciamento ring-hash in Envoy e NGINX.
- Database partizionati: Amazon Dynamo, Cassandra e Riak collocano i dati su anelli di token con nodi virtuali.
- Varianti: l’hashing rendezvous (peso casuale più alto), Jump Consistent Hash e l’hashing Maglev bilanciano in modo diverso memoria, velocità e distribuzione.
Domande frequenti
Tutte le risposte sulla sicurezza e sulle funzionalità dello strumento.
Che cos’è un nodo virtuale?
Un server fisico viene mappato su molti punti dell’anello («A#0», «A#1», …). Archi più numerosi e più piccoli compensano la casualità della posizione, e il carico di un server rimosso si distribuisce su molti vicini invece che su uno solo.
Posso dare più carico a un server più potente?
Sì. Dagli proporzionalmente più nodi virtuali e possederà una quota proporzionalmente maggiore dell’anello.
Quale funzione di hash devo usare?
Va bene qualsiasi hash non crittografico veloce e ben miscelato: MurmurHash3, xxHash o FNV con un passo finale di miscelazione. La robustezza crittografica non serve.
I miei dati sono al sicuro durante l'utilizzo?
Assolutamente sì. Lo strumento opera al 100% nella memoria locale del tuo browser senza inviare dati all'esterno.
Strumenti correlati
Elezione del leader, replicazione dei log e gestione delle partizioni di rete.
Genera hash SHA-256, MD5 e converti URL, entità HTML ed Esadecimale.
Visualizzatore interattivo BST con inserimento, cancellazione e attraversamento.
Progetti in evidenza tech-fun.net
Scopri altri strumenti di IA e produttività
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.