Consistent Hashing in Practice
Consistent hashing is a distributed hashing technique used in scalable systems like Amazon DynamoDB, Apache Cassandra, Riak, and Voldemort to partition data across nodes while minimizing data movement during scaling (add/remove nodes). It avoids the pitfalls of traditional modulo hashing, where adding a node reshuffles all keys.
Imagine a fixed-size ring (like a clock face) representing the hash space, typically 0 to 2¹⁶⁰-¹ (using a hash like MD5 or SHA-1). Both keys (e.g., user IDs) and nodes (servers) are hashed to points on this ring. Data for a key goes to the "successor" node—the first node encountered moving clockwise from the key's position.
Below, I'll break it down by the requested topics, with practical examples from Cassandra (which popularized vnodes).
1. Ring Design
- Structure: The ring is a circular space. Each physical node chooses one or more positions (tokens) on the ring via
hash(node_id).
- Example: Node A hashes to position 100, Node B to 500, Node C to 900 (on a 0-1000 ring for simplicity).
- Ownership: The ring is divided into arcs between nodes. Node B owns keys hashing to 101–900, Node C owns 901–100, Node A owns 1–100 (wrapping around).
- Replication: For fault tolerance, data is replicated to the next
R successors (e.g., R=3 in Cassandra). Key at 200 goes to Node B (primary) + next 2 clockwise.
- In practice: Cassandra's ring is visualized in
nodetool ring -p. Nodes auto-join by picking tokens, ensuring even coverage.
Visual (simplified ring):
0 ---------------- 100 (Node A) --- 500 (Node B) --- 900 (Node C) --- back to 0
Keys 0-100 → A; 101-500 → B; 501-900 → C; 901-0 → A
2. Virtual Nodes (Vnodes)
- Problem solved: Plain hashing can unevenly distribute load (e.g., one node gets a huge arc if hashes cluster).
- How it works: Each physical node runs multiple vnodes (e.g., 256 in Cassandra), each with a unique token. One physical node owns many small arcs scattered around the ring.
- Example: Node A runs vnodes at 50, 200, 800 → owns three small arcs instead of one big one.
- Benefits:
- Load balancing: Keys distribute more evenly across physical nodes.
- Heterogeneous clusters: Handles nodes with varying capacity (e.g., assign more vnodes to beefier servers).
- In practice: Cassandra defaults to 256 vnodes/node. Enable with
num_tokens: 256 in cassandra.yaml. Riak uses ~100 vnodes/node.
3. Key Distribution
- Process:
- Client hashes key:
position = hash(key) (e.g., Murmur3 in Cassandra for speed).
- Walk clockwise to find successor vnode (coordinate via gossip protocol or partitioner).
- Store/read from that vnode's physical node (+ replicas).
- Client involvement: Smart clients (e.g., Cassandra drivers) compute the target node locally using a ring snapshot, avoiding coordinator hops.
- In practice: In DynamoDB, keys are hashed and routed to partitions. Hot keys (e.g., leaderboards) are spread via this.
Example:
Key "user123" → hash=300 → successor is Node B's vnode at 350 → store on Node B.
4. Rebalancing Strategy
- Core advantage: Only ~1/N of keys move when adding/removing the Nth node (vs. all keys in modulo hashing).
- Adding a node:
- New node picks tokens in underloaded arcs (auto or manual via
nodetool bootstrap).
- Steals small arcs from neighbors' vnodes.
- Neighbors stream only their affected keys to the new node (incremental, via hinted handoff).
- Removing a node:
- Mark as decommissioned (
nodetool decommission).
- Its vnodes' keys stream to successors.
- Ring heals automatically.
- Time complexity: O(K/N) data moved, where K=total keys. Vnodes make it granular (e.g., 256 streams/node).
- In practice: Cassandra's
nodetool cleanup post-rebalance removes stale data. Takes minutes-hours for TB-scale clusters, not days.
Before add (3 nodes) → After (Node D at 600):
A(100)-B(500)-C(900) → A(100)-B(500)-D(600)-C(900)
Only B's 501-600 keys move to D (~16% of B's load).
5. Hotspots Mitigation
- Problem: Skewed keys (e.g., timestamp-based IDs like Twitter timelines hash to one spot) overload a vnode/node.
- Strategies:
- Vnodes: Spread one physical node's load across the ring, diluting hotspots.
- Multiple hash spaces: Cassandra's
Murmur3Partitioner + salting (append random suffix to hot keys client-side).
- Token-aware drivers: Clients detect overloaded nodes via
TRY_SUCCESS topology and retry with offset hash.
- Dynamic reassignment: Tools like
nodetool move shift tokens. Or use capacity-based vnodes (more on strong nodes).
- Composite keys: Design keys to distribute (e.g.,
{bucket, user_id} where bucket rotates).
- Monitoring: OpsCenter or Prometheus tracks per-node load. Thresholds trigger auto-rebalance.
- In practice: Riak uses "ownership weight" for vnodes. DynamoDB auto-splits hot partitions behind the scenes.
Summary Table:
| Aspect | Key Feature | Benefit in Practice |
|---|
| Ring | Clockwise successor | Visualizes ownership |
| Vnodes | 100s per node | Even load, easy scale |
| Key Dist. | hash(key) → successor | Client-local routing |
| Rebalance | Steal small arcs | Minimal data movement |
| Hotspots | Vnodes + salting | Handles zipfian skew |
This design scales to 1000s of nodes with sub-second joins. For code, check Cassandra's TokenMetadata or libraries like python-hash-ring. Questions?