#consistent-hashing #hashing #consistent #google

maglev

Maglev - Google's consistent hashing algorithm

6 releases

0.2.1 Oct 26, 2021
0.2.0 Nov 14, 2020
0.1.3 Jan 23, 2017

#1886 in Algorithms

Download history 3425/week @ 2024-11-17 4106/week @ 2024-11-24 4980/week @ 2024-12-01 4681/week @ 2024-12-08 3377/week @ 2024-12-15 1525/week @ 2024-12-22 1827/week @ 2024-12-29 3368/week @ 2025-01-05 4437/week @ 2025-01-12 4532/week @ 2025-01-19 3369/week @ 2025-01-26 3203/week @ 2025-02-02 3488/week @ 2025-02-09 5162/week @ 2025-02-16 4471/week @ 2025-02-23 5292/week @ 2025-03-02

18,675 downloads per month
Used in sonya-proxy

Apache-2.0

16KB
281 lines

rust-maglev travis build crate docs

Google's consistent hashing algorithm

Usage

To use maglev, first add this to your Cargo.toml:

[dependencies]
maglev = "0.2"

And then, use Maglev with ConsistentHasher trait

use maglev::{ConsistentHasher, Maglev};

fn main() {
    let m = Maglev::new(vec!["Monday",
                            "Tuesday",
                            "Wednesday",
                            "Thursday",
                            "Friday",
                            "Saturday",
                            "Sunday"]);

    assert_eq!(m["alice"], "Friday");
    assert_eq!(m["bob"], "Wednesday");

    // When the node list changed, ensure to use same `capacity` to rebuild

    let m = Maglev::with_capacity(vec!["Monday",
                                  // "Tuesday",
                                    "Wednesday",
                                  // "Thursday",
                                    "Friday",
                                    "Saturday",
                                    "Sunday"],
                                m.capacity());

    assert_eq!(m["alice"], "Friday");
    assert_eq!(m["bob"], "Wednesday");
}

Maglev use std::collections::hash_map::DefaultHasher by default, we could use the given hash builder to hash keys.

use fasthash::spooky::Hash128;
use maglev::Maglev;

fn main() {
    let m = Maglev::with_hasher(vec!["Monday",
                                     "Tuesday",
                                     "Wednesday",
                                     "Thursday",
                                     "Friday",
                                     "Saturday",
                                     "Sunday"],
                                Hash128 {});

    assert_eq!(m["alice"], "Monday");
    assert_eq!(m["bob"], "Wednesday");
}

Dependencies

~0.8–2.2MB
~33K SLoC