Hashring
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
- breaking The library internally uses MD5 as its hashing function. MD5 is cryptographically broken and is unsuitable for security-sensitive applications like password storage or digital signatures due to known collision vulnerabilities.
- deprecated The library's last release (1.5.1) was in April 2015. This indicates that the project is not actively maintained, which may lead to compatibility issues with newer Python versions and a lack of updates for performance or security enhancements.
- gotcha This library (`hashring`) should not be confused with `uhashring`, another popular and more actively maintained consistent hashing library. While both provide similar functionality, they are distinct projects with different import paths and maintenance statuses.
- gotcha Python's built-in `hash()` function is non-deterministic across different interpreter runs for strings and other types due to hash randomization (a security feature). This makes it unsuitable for consistent hashing across processes or restarts. `hashring` uses MD5 for its consistent hashing, which is deterministic.
Install
-
pip install hashring
Imports
- HashRing
from hash_ring import HashRing
Quickstart
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}")