5 releases (3 breaking)

0.4.0 Nov 1, 2024
0.3.0 Jul 12, 2024
0.2.0 May 10, 2024
0.1.1 Apr 18, 2024
0.1.0 Feb 28, 2024

#2026 in Algorithms

Download history 6141/week @ 2024-09-28 4414/week @ 2024-10-05 6423/week @ 2024-10-12 4670/week @ 2024-10-19 9106/week @ 2024-10-26 11669/week @ 2024-11-02 6231/week @ 2024-11-09 11938/week @ 2024-11-16 11261/week @ 2024-11-23 9067/week @ 2024-11-30 10107/week @ 2024-12-07 10594/week @ 2024-12-14 5495/week @ 2024-12-21 4748/week @ 2024-12-28 8638/week @ 2025-01-04 8180/week @ 2025-01-11

29,028 downloads per month
Used in 14 crates (via pingora-load-balancing)

Apache-2.0

44KB
303 lines

pingora-ketama

A Rust port of the nginx consistent hashing algorithm.

This crate provides a consistent hashing algorithm which is identical in behavior to nginx consistent hashing.

Using a consistent hash strategy like this is useful when one wants to minimize the amount of requests that need to be rehashed to different nodes when a node is added or removed.

Here's a simple example of how one might use it:

use pingora_ketama::{Bucket, Continuum};

fn main() {
    // Set up a continuum with a few nodes of various weight.
    let mut buckets = vec![];
    buckets.push(Bucket::new("127.0.0.1:12345".parse().unwrap(), 1));
    buckets.push(Bucket::new("127.0.0.2:12345".parse().unwrap(), 2));
    buckets.push(Bucket::new("127.0.0.3:12345".parse().unwrap(), 3));
    let ring = Continuum::new(&buckets);

    // Let's see what the result is for a few keys:
    for key in &["some_key", "another_key", "last_key"] {
        let node = ring.node(key.as_bytes()).unwrap();
        println!("{}: {}:{}", key, node.ip(), node.port());
    }
}
# Output:
some_key: 127.0.0.3:12345
another_key: 127.0.0.3:12345
last_key: 127.0.0.2:12345

We've provided a health-aware example in pingora-ketama/examples/health_aware_selector.rs.

For a carefully crafted real-world example, see the pingora-load-balancing crate.

Dependencies

~78KB