Saltar al contenido principal
ProductosHerramientas de escritorioTASTECADRevisión de planosTASTEFILESGestión de archivosTASTEFTPTransferencia de archivosTASTESSHEspacio de trabajo remotoTASTEZIPCompresión y extracciónTASTEWINMGestión de archivosHerramientas para desarrolladoresTASTECODEEntorno de desarrollo integrado para RustTASTESTUDIOEntorno integrado de desarrollo y pruebasTASTEETLIntegración de datos (ETL)ServidoresTASTEREMOTEServidor de escritorio remotoTASTEGEOServidor geoespacialTASTEMAILEspacio de trabajo de correoInversiónTASTESTOCKAplicación de escritorio de trading automático de accionesEmpezarDescargasDocumentaciónComprarTodos los productos
Marketplace
Noticias
TecnologíaNoticiasNoticias de desarrollo de hoyDocumentaciónLenguajes de programaciónRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps y escritorioTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos esencialesAlgoritmos avanzadosAlgoritmos prácticos
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparateGuía de la comunidad
ColaboraTransferencia técnicaDesarrollo de sitio webDesarrollo de app de escritorioCanal de lanzamiento y pagosSocio de ventasContacto
ServiciosEscritorio remotoPaquetes de instalación a medida
TASTEDEV
Productos

Herramientas de escritorio

TASTECADAbre planos complejos con ligerezaTASTEFILESSolo los archivos que necesitas, lo más rápido posibleTASTEFTPEl camino más limpio para tus archivosTASTESSHEntre tu servidor y tú, una conexión más sólidaTASTEZIPComprime más rápido, descomprime más seguroTASTEWINMUn gestor de archivos de dos paneles pensado para el teclado

Herramientas para desarrolladores

TASTECODEEdita, compila, depura y prueba apps de Rust en una sola ventanaTASTESTUDIODe la edición a las pruebas remotas y las correcciones con IA aprobadasTASTEETLMueve datos viendo sus valores

Servidores

TASTEREMOTEUn escritorio remoto que funciona en tu propio servidorTASTEGEOUn servidor geoespacial compatible con GeoServer, reconstruido en RustTASTEMAILRecupera el control de tu correo

Inversión

TASTESTOCKTrading automático de acciones según las reglas que tú defines: cuándo y qué

Empezar

DescargasÚltimas versiones de cada productoDocsCómo usar cada productoComprarSuscripciones y licencias perpetuasTodos los productosTodos los productos de un vistazo
Todos los productos
MarketplaceNoticias
Tecnología

Noticias

Noticias de desarrollo de hoyAnuncios oficiales de lenguajes, frameworks, GitHub e IADocumentaciónGuías de lenguajes, frameworks y algoritmos

Lenguajes de programación

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps y escritorioTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálisis de complejidad · Ordenamiento · Búsqueda · Estructuras de datos básicas · Árboles y montículosAlgoritmos esencialesRecorrido de grafos · Camino mínimo y árbol generador mínimo · Programación dinámica · Algoritmos voraces · Divide y vencerás · Backtracking (vuelta atrás)Algoritmos avanzadosAlgoritmos de cadenas · Matemáticas y teoría de números · Manipulación de bits · Árboles de segmentos · Union-FindAlgoritmos prácticosEstrategia para entrevistas de código · Caché LRU · Limitación de tasa · Hashing consistente
Toda la documentación de desarrollo
Comunidad
ProyectosDescubre creadores y su trabajoRegistros de desarrolloDecisiones y aprendizajesPromptsInstrucciones reutilizablesProblemas con herramientas de IAProblemas y alternativas de Claude, Codex, GeminiEscaparateResultados terminadosGuía de la comunidadCómo construimos en abierto
Colabora
Transferencia técnicaApps nativas con Rust y eguiDesarrollo de sitio web10 idiomas, cuentas, documentación y descargasDesarrollo de app de escritorioRust y egui, sin WebViewCanal de lanzamiento y pagosFirma, MSI, deb, rpm, AppImage, hashesSocio de ventasRecomiéndanos y gana el 30 %ContactoDesarrollo, alianzas e inversión
Servicios
Escritorio remotoAccede a tu ordenador desde el navegadorPaquetes de instalación a medidaSolo lo necesario, ajustes precargados
Comprar
ES
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Iniciar sesión
Iniciar sesión
TASTEDEV

De pequeñas herramientas a un mejor desarrollo.

support@tastedev.netApoyar a TASTEDEV
ProductosLínea de productosComprarDocsDescargasMarketplaceSoporte
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparate
PolíticasQuiénes somosPolítica de privacidadTérminos de servicioCondiciones de suscripciónReembolsosNormas de la comunidad
CuentaIniciar sesiónRegistrarse
Visitantes
Hoy
Ayer
Vistas totales
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro mercantil
853-44-00368
Dirección
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Teléfono
+82-10-4404-1523
Correo electrónico
whitecalvin@tastedev.net
Responsable de privacidad
CHOI YOUNG GU

© 2026 TASTEDEVLa información de los productos se basa en fuentes de desarrollo verificadas.Publicado · en mejora

Documentación de Hashing consistente
Hashing consistente
Consistent hashing conceptsHow it worksImplementationComplexityPractice problemsReal-world use
Debates

Guía de Hashing consistente · 3/6

Implementation

Por ahora, este capítulo solo está disponible en inglés.

A hash ring with virtual nodes on Python's bisect, ported to C++, Java and TypeScript. Sharing one hash, all four agree on every key.

Python

Avoid the built-in hash(): string hashing is randomized per process. We use 64-bit FNV-1a plus MurmurHash3's fmix64 finalizer to spread similar names like node#1.

import bisect

MASK = (1 << 64) - 1


def hash64(text: str) -> int:
    x = 0xCBF29CE484222325  # FNV-1a offset basis
    for b in text.encode("utf-8"):
        x = ((x ^ b) * 0x100000001B3) & MASK
    x ^= x >> 33  # fmix64 finalizer
    x = (x * 0xFF51AFD7ED558CCD) & MASK
    x ^= x >> 33
    x = (x * 0xC4CEB9FE1A85EC53) & MASK
    return x ^ (x >> 33)


class HashRing:
    def __init__(self, vnodes: int = 100):
        self.vnodes = vnodes
        self.points: list[int] = []  # sorted positions
        self.owner: dict[int, str] = {}  # position -> node

    def add(self, node: str) -> None:
        for i in range(self.vnodes):
            p = hash64(f"{node}#{i}")
            bisect.insort(self.points, p)
            self.owner[p] = node

    def remove(self, node: str) -> None:
        for i in range(self.vnodes):
            p = hash64(f"{node}#{i}")
            del self.owner[p]
            self.points.pop(bisect.bisect_left(self.points, p))

    def get(self, key: str) -> str:
        if not self.points:
            raise LookupError("ring is empty")
        i = bisect.bisect_left(self.points, hash64(key))
        if i == len(self.points):  # wrap around
            i = 0
        return self.owner[self.points[i]]
  • hash64: XOR each byte, multiply by the FNV prime, keep 64 bits with & MASK.
  • points, owner: sorted positions and a position-to-node map.
  • add: derives vnode positions from node#i and keeps them sorted via insort.
  • remove: recomputes the same positions, so nothing per node is stored. (64-bit collisions are negligible and ignored.)
  • get: bisect_left finds the first point at or after the key; past the end, wrap.

C++

std::map is sorted, so lower_bound is the clockwise search.

#include <cstdint>
#include <map>
#include <stdexcept>
#include <string>

std::uint64_t hash64(const std::string& text) {
    std::uint64_t x = 0xCBF29CE484222325ULL;
    for (unsigned char b : text) x = (x ^ b) * 0x100000001B3ULL;
    x ^= x >> 33; x *= 0xFF51AFD7ED558CCDULL;
    x ^= x >> 33; x *= 0xC4CEB9FE1A85EC53ULL;
    return x ^ (x >> 33);
}

class HashRing {
public:
    explicit HashRing(int vnodes = 100) : vnodes_(vnodes) {}
    void add(const std::string& node) {
        for (int i = 0; i < vnodes_; ++i) ring_[hash64(node + "#" + std::to_string(i))] = node;
    }
    void remove(const std::string& node) {
        for (int i = 0; i < vnodes_; ++i) ring_.erase(hash64(node + "#" + std::to_string(i)));
    }
    const std::string& get(const std::string& key) const {
        if (ring_.empty()) throw std::runtime_error("ring is empty");
        auto it = ring_.lower_bound(hash64(key));
        return (it == ring_.end() ? ring_.begin() : it)->second;
    }
private:
    int vnodes_;
    std::map<std::uint64_t, std::string> ring_;
};
¿Tienes preguntas sobre este capítulo?
Capítulo anteriorHow it worksCapítulo siguienteComplexity

Java

No unsigned long, so the TreeMap uses Long::compareUnsigned; ceilingEntry does the search.

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.TreeMap;

public class HashRing {
    private final int vnodes;
    private final TreeMap<Long, String> ring = new TreeMap<>(Long::compareUnsigned);

    public HashRing(int vnodes) { this.vnodes = vnodes; }

    static long hash64(String text) {
        long x = 0xCBF29CE484222325L;
        for (byte b : text.getBytes(StandardCharsets.UTF_8)) x = (x ^ (b & 0xFF)) * 0x100000001B3L;
        x ^= x >>> 33; x *= 0xFF51AFD7ED558CCDL;
        x ^= x >>> 33; x *= 0xC4CEB9FE1A85EC53L;
        return x ^ (x >>> 33);
    }

    public void add(String node) {
        for (int i = 0; i < vnodes; i++) ring.put(hash64(node + "#" + i), node);
    }

    public void remove(String node) {
        for (int i = 0; i < vnodes; i++) ring.remove(hash64(node + "#" + i));
    }

    public String get(String key) {
        if (ring.isEmpty()) throw new IllegalStateException("ring is empty");
        Map.Entry<Long, String> e = ring.ceilingEntry(hash64(key));
        return (e != null ? e : ring.firstEntry()).getValue();
    }
}

TypeScript

bigint covers 64-bit math; the binary search is hand-written.

const MASK = (1n << 64n) - 1n;

function hash64(text: string): bigint {
  let x = 0xcbf29ce484222325n;
  for (const b of new TextEncoder().encode(text)) x = ((x ^ BigInt(b)) * 0x100000001b3n) & MASK;
  x ^= x >> 33n; x = (x * 0xff51afd7ed558ccdn) & MASK;
  x ^= x >> 33n; x = (x * 0xc4ceb9fe1a85ec53n) & MASK;
  return x ^ (x >> 33n);
}

class HashRing {
  private points: bigint[] = [];
  private owner = new Map<bigint, string>();
  constructor(private readonly vnodes = 100) {}

  private lowerBound(h: bigint): number {
    let lo = 0, hi = this.points.length;
    while (lo < hi) {
      const mid = (lo + hi) >> 1;
      if (this.points[mid] < h) lo = mid + 1; else hi = mid;
    }
    return lo;
  }
  add(node: string): void {
    for (let i = 0; i < this.vnodes; i++) {
      const p = hash64(`${node}#${i}`);
      this.points.splice(this.lowerBound(p), 0, p);
      this.owner.set(p, node);
    }
  }
  remove(node: string): void {
    for (let i = 0; i < this.vnodes; i++) {
      const p = hash64(`${node}#${i}`);
      if (this.owner.delete(p)) this.points.splice(this.lowerBound(p), 1);
    }
  }
  get(key: string): string {
    if (this.points.length === 0) throw new Error("ring is empty");
    const i = this.lowerBound(hash64(key));
    return this.owner.get(this.points[i === this.points.length ? 0 : i])!;
  }
}

Summary

  • A ring is sorted positions plus owners.
  • Lookup: first position at or after the key, wrapping at the end.
  • Sorted trees make point insertion and deletion O(log n).

0 comentarios

Comentarios destacadosMás recientes primero

Iniciar sesión · Inicia sesión para dejar un comentario.