Skip to content
System Design Explorer
algorithms

Consistent Hashing

By Ankur NayakReviewed

Consistent hashing maps keys and servers onto the same circular hash space, so each key belongs to the next server clockwise. Adding or removing a server only moves the keys next to it, instead of reshuffling almost everything like hash mod N.

Consistent Hashing diagramComponents: Router, Node A (0–120°), Node B (120–240°), Node C (240–360°). Connections: Router to Node A; Router to Node B (hash(user:42) = 170°); Router to Node C.RouterServiceNode A0–120°Node B120–240°Node C240–360°
Keys follow the ring

How it works

With naive sharding, a key goes to server hash(key) mod N. Change N and nearly every key maps somewhere new, which empties caches and forces massive data movement.

Consistent hashing places servers at points on a ring (by hashing their IDs). A key is hashed onto the same ring and owned by the first server found walking clockwise. When a server joins, it takes over only the keys between it and its predecessor; when it leaves, only its keys move to the next server. On average just 1/N of keys move.

Each physical server is usually given many virtual nodes on the ring, which evens out the load and spreads a departed server's keys across many survivors. Dynamo-style databases, Cassandra, distributed caches and Uber's Ringpop all use variations of this idea.

Key points

  • Keys and servers share one hash ring
  • Membership changes move ~1/N of keys
  • Virtual nodes smooth out load imbalance
  • Replicas are the next K distinct servers on the ring

When to use it, and pitfalls

Use it for

  • Distributed caches and key-value stores
  • Routing users or channels to stateful servers
  • Any cluster that grows and shrinks often

Watch out for

  • Without virtual nodes, load can be very uneven
  • Every client must agree on ring membership (gossip or a coordinator)
  • Hot keys still land on one server

Used in

Frequently asked questions

Why not just use hash mod N?

Because changing N remaps almost every key. With consistent hashing, adding or removing one of N servers moves only about 1/N of the keys, so caches stay warm and data migration is small.

What are virtual nodes?

Each physical server is placed at many points on the ring instead of one. This evens out how much of the ring each server owns and, when a server fails, spreads its keys over many servers rather than overloading a single neighbour.

Sources