What it is
Consistent hashing is a way to assign keys (user IDs, cache keys, partition keys) to a changing set of servers so that each key always maps to the same server, and so that adding or removing a server moves only a small fraction of the keys. It is used by load balancers for sticky, cache-friendly routing, by client libraries for cache clusters, and by distributed databases to place data on nodes.
Why it exists
Some work is cheaper on the server that has seen the key before: its cache is warm, its shard holds the data, its session is in memory. Plain balancing algorithms (round robin, least connections) ignore the key, so every server's cache competes for the whole key space. Hashing the key fixes that. The naive formula, hash(key) mod N, breaks the moment N changes: going from N to N+1 servers changes the result for about N/(N+1) of all keys. A scaling event or a single failure would empty almost every cache at once. Consistent hashing keeps the affinity and limits the damage.
How it works
The ring. Hash values form a circle (for example 0 to 2³² − 1, wrapping around). Each server is hashed to a point on the circle. Each key is hashed too, and belongs to the first server point found clockwise from it.
Adding and removing servers. A new server takes over only the arc between its point and the previous point; every other key keeps its owner. A removed server's arc goes to its clockwise neighbour. Either way about 1/N of the keys move.
Virtual nodes. With one point per server, arcs are uneven by chance and a failed server dumps all its keys onto a single neighbour. Placing each server at many points (tens to hundreds of virtual nodes) makes the shares nearly equal and spreads a departing server's keys over many neighbours. Weights are easy: a bigger server gets more virtual nodes.
Lookups. The ring is a sorted array of points; finding a key's owner is a binary search, O(log(N × vnodes)).
Replication. Storage systems such as Dynamo and Cassandra store each key on the owner and the next R − 1 distinct servers clockwise, so the same ring also decides replica placement.
When to use it
- Distributing keys across a cache cluster (memcached and Redis client libraries, CDN cache tiers).
- Partitioning data across database or key-value nodes that join and leave.
- Routing requests to stateful services where locality matters: per-user sessions, per-room chat servers, per-tenant workers.
- Any balancer where cache hit ratio matters more than perfectly even load.
When not to
- Stateless services with no locality benefit: least connections or power of two choices balance load better.
- When key popularity is extremely skewed and you cannot add hot-key handling.
- Small, fixed clusters that never change size: a static mapping or
mod Nis simpler. - When range queries matter: hashing scatters adjacent keys; range partitioning keeps them together.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Consistent hashing over mod N | Only ~1/N keys move on membership change | Ring bookkeeping, virtual nodes to tune |
| Key affinity over load-aware balancing | Warm caches, data locality | Uneven load from hot keys; no reaction to slow servers |
| More virtual nodes | More even shares, smoother redistribution | Larger ring, more memory and rebuild work |
| Hash partitioning over range partitioning | Even spread of sequential keys | Range scans touch every node |
Alternatives
- Rendezvous (highest random weight) hashing: for each key, score every server with hash(key, server) and pick the highest. Same minimal movement, no ring, O(N) per lookup.
- Jump consistent hash: a tiny, fast function mapping keys to buckets 0…N−1 with minimal movement, but servers can only be added or removed at the end.
- Consistent hashing with bounded loads: caps each server at, say, 1.25× the average load and passes overflow clockwise, trading some affinity for balance.
- Directory or lookup service: an explicit table from key ranges to servers; flexible and rebalanceable, at the cost of a component to maintain.
- Range partitioning: contiguous key ranges per node, good for scans, needs splitting of hot ranges.
Failure modes
- Hot keys: one very popular key always maps to one server, which saturates while others idle.
- Uneven ring: too few virtual nodes or a weak hash function leaves some servers owning far more than their share.
- Cold caches after a move: moved keys are misses on their new server; a large membership change causes a burst of backend reads.
- Inconsistent views: clients or balancers with different server lists send the same key to different servers, splitting its cache entries and, for storage, its writes.
- Cascading failure: a failed server's keys land on its neighbours; with few virtual nodes one neighbour gets them all and may fail in turn.
In production
Use a well-distributed hash (MurmurHash, xxHash, or a cryptographic hash) and 100–200 virtual nodes per server, or weight by capacity. Keep cluster membership consistent through service discovery, and change it gradually: add one server, let caches warm, then the next. Track per-server request rate and hot keys, and handle them explicitly with a small local cache, key replication or key splitting. Envoy's ring hash and Maglev balancers, nginx's hash ... consistent, and HAProxy's hash-type consistent provide it at the balancer; most cache client libraries implement Ketama-style rings.
Common misconceptions
- "Consistent hashing balances load." It balances keys. Load follows key popularity, which is rarely uniform.
- "Nothing moves when a server is added." About 1/N of the keys move, by design; that is far fewer than with mod N, not zero.
- "Virtual nodes are an optimisation for speed." They are for balance and smooth redistribution.
- "It is only for databases." It is just as useful for routing requests to warm caches and stateful services.
Interview angle
Consistent hashing comes up whenever you shard a cache or database or need sticky routing. Explain the problem with mod N in one sentence, draw the ring, mention virtual nodes and the ~1/N movement, then volunteer the weakness: hot keys, and how you would handle them (local caching, replication, key salting, bounded loads). Comparing it briefly with rendezvous hashing or a directory service shows breadth.
Model assumptions
The simulation is a simplified model, not a benchmark. Requests carry a key from 1 to 2,000 with Zipf-distributed popularity (exponent 0.9, 0 for uniform, 1.3 for very skewed). Each app server has 8 workers, a 20 ms service time and its own LRU cache of 150 keys; on a miss it reads a shared database (30 ms) and stores the key (cache-aside). The balancer either uses round robin or a ring with 64 virtual nodes per server, skipping servers it believes unhealthy. Server identifiers in the model were chosen so that the simulator's ring splits keys evenly; its point hash is simple and clusters for very short, similar names, which a production implementation avoids with a stronger hash. Health checks run every 500 ms. Arrivals are random (Poisson). Numbers show behaviour and orders of magnitude only.