Skip to content
BytePatterns

Consistent Hashing Ring

MediumSystem Design#consistent-hashing#virtual-nodes#bisect~25m

Problem

A sharded store places keys on database nodes with a consistent hashing ring. Every node is hashed onto the ring 100 times, as "node#0" to "node#99", to spread its share evenly. A key belongs to the first node point at or after the key's own hash, going clockwise and wrapping around past the top. Use the first 8 hex digits of MD5 as the hash so the placement is identical on every machine. Build the ring and its owner(key) lookup, then show the property that makes it worth using: when a fourth node joins, only the keys it takes over move, and they all move to it.

Examples

Input:  nodes = db-a, db-b, db-c; owner("user:42") before and after db-d joins
Output: db-c db-c
Input:  keys user:0 to user:999, then db-d joins
Output: 251 {'db-d'}
Why:    about a quarter of the keys move, and every one of them moves to the new node
Input:  a ring with the single node "solo"; owners of user:0, user:1, user:2
Output: ['solo', 'solo', 'solo']
Why:    edge case, every lookup wraps around to the only node

Hints

0 / 3

Stuck on the idea rather than the code? Database Sharding covers it.