Hashring

1.5.1 · maintenance · verified Sat Apr 11

Hashring is a Python library that implements consistent hashing, primarily using MD5 as its hashing function. It's designed for distributed systems and caches to minimize the remapping of keys when nodes are added or removed from a ring. The current version is 1.5.1, but the project has a very low release cadence, with the last update in 2015.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a HashRing with a list of nodes and retrieve the assigned node for a given key. It also shows how to apply weights to nodes for uneven distribution.

from hash_ring import HashRing

# Define a list of nodes (e.g., server addresses)
nodes = ['server1.example.com', 'server2.example.com', 'server3.example.com']

# Create a consistent hash ring
ring = HashRing(nodes)

# Get the node responsible for a specific key
key = "user:12345:data"
assigned_node = ring.get_node(key)

print(f"Key '{key}' is assigned to node: {assigned_node}")

# Example with weights
weighted_nodes = {
    'server1.example.com': 1,
    'server2.example.com': 2, # server2 gets twice the weight
    'server3.example.com': 1
}
weighted_ring = HashRing(weighted_nodes)
assigned_node_weighted = weighted_ring.get_node(key)
print(f"Key '{key}' is assigned to weighted node: {assigned_node_weighted}")

view raw JSON →