Spread data over servers so adding or removing a server moves very little data.
Consistent hashing is a way to decide which server stores which data, so that when we add or remove a server, only a small part of the data moves.
hash(key) % N, breaks badly when N changes. Almost every key moves.We have many servers (for example, many cache servers or database shards). For each key (like a user id) we must pick one server. We need a rule that every machine can compute the same way, without asking a central place.
Pick the server with server = hash(key) % N. With N = 3 servers this works. But if one server dies and N becomes 2, the answer changes for almost every key. All cached data is suddenly in the wrong place. Every request misses the cache and hits the database. This can crash it.
With only a few servers, the random positions may be uneven. One server can get a huge arc, and others a tiny arc. The fix is virtual nodes: each real server is placed on the ring many times (for example, 100 times) with different labels, like S1#0, S1#1, and so on. The arcs become small and well mixed, so the load evens out. A bigger server can get more virtual nodes.
| Point | hash % N | Consistent hashing |
|---|---|---|
| Keys moved when a server is added | Almost all | About 1/N |
| Easy to understand | Very easy | A bit harder |
| Lookup cost | Instant | Search the ring (fast, O(log n)) |
| Even load | Yes, if the hash is good | Needs virtual nodes |
| Good for | A fixed number of servers | Servers that come and go |
Each dot is a key, drawn in the colour of the server that owns it (the first server clockwise). A white ring means the key just moved.
ring = sorted list of (position, server)
def owner(key):
p = hash(key)
for (pos, server) in ring: # in real code: binary search
if pos >= p:
return server
return ring[0].server # wrap around the circle| Term | Meaning in easy words |
|---|---|
| Hash function | A function that turns any key into a number. The same key always gives the same number. |
| Hash ring | A circle of positions from 0 to the biggest hash value, where the end joins the start. |
| Key | The thing we store or look up, like a user id. |
| Node / server | A machine that stores some keys. |
| Clockwise | The direction we walk on the ring to find the owner. |
| Virtual node (vnode) | One of many ring positions that belong to one real server. |
| Rebalancing | Moving keys between servers after the server list changes. |
| Hot spot | A server that gets much more load than others. |
| Replication factor | How many servers keep a copy of each key. |
| Sharding | Splitting data across many servers. |
| Choice | We gain | We lose |
|---|---|---|
| More virtual nodes | Smoother load | Bigger ring, more to update |
| Fewer virtual nodes | Small and simple ring | Uneven load |
| More replicas | Safer data | More storage and write work |
| Consistent hashing vs a lookup table | No central table | Less control over exact placement |