Course contents

03. Scaling and Load Balancing Lesson 7 of 8

Consistent Hashing

Route each key to the same server with a hash ring: cache affinity, why mod N reshuffles everything, virtual nodes, 1/N key movement and hot keys.

16 minIntermediate8 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Hashing by key gives affinity: N local caches behave like one cache N times the size.
  • hash(key) mod N spreads keys evenly but remaps almost all of them when N changes.
  • On a hash ring a key belongs to the next server point clockwise; virtual nodes even out the arcs.
  • Adding or removing one of N servers moves only about 1/N of the keys.
  • Hashing balances keys, not load: hot keys need replication, splitting or bounded loads.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

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 N is 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.

The lesson as textEvery step of the simulation, written out.
  1. 1. Three servers, three separate caches

    Each request asks for one of 2,000 items (a product, a profile); a few are very popular, most are rare. Every app server keeps the 150 items it used most recently in its own cache and reads the database on a miss.

    The balancer uses round robin, so any item can land on any server. Each cache ends up holding much the same popular items as the other two, and fewer than half of the lookups hit.

    Scene: A round-robin balancer spreads requests for 2,000 keys over three servers, each with its own 150-key cache in front of a shared database. Fewer than half of the cache lookups hit.

    Key idea: Without key affinity, every server’s cache competes for the whole key space.

  2. 2. Hash the key, not the turn

    Now the balancer hashes the item’s key and always sends a given key to the same server. Each server sees only about a third of the keys, so its 150 cache slots cover a much larger share of the traffic it receives.

    The overall hit ratio rises, fewer requests go to the database and median latency drops. The three caches now behave like one cache three times the size.

    Scene: The balancer sends each key to the same server every time. Each cache holds a different part of the key space, the hit ratio is clearly higher and latency is lower.

    Key idea: Key affinity partitions the key space, so N small caches act like one large one.

  3. 3. Why not just hash(key) mod N?

    The obvious way to map keys to servers is server = hash(key) mod N. It spreads keys evenly, until N changes. Going from 3 servers to 4 changes the result for about three keys in four; going from 3 to 2 after a crash, for about two in three.

    Every moved key is a cache miss on its new server, so a single scaling event would empty most caches at once and send a flood of reads to the database.

    Scene: An annotation explains that with hash(key) mod N, changing from three to four servers would move about three quarters of all keys to a different server.

    Key idea: With mod N, changing N remaps almost every key.

  4. 4. The hash ring and virtual nodes

    Consistent hashing puts servers and keys on the same circle of hash values. A key belongs to the first server point clockwise from its hash. To avoid one server owning a huge arc by bad luck, each server is placed at 64 points (virtual nodes), which evens out the arcs.

    To see the ring’s balance on its own, we make every key equally popular for a while. Each server now receives close to a third of the requests.

    Scene: Keys are now equally popular. The hash ring with 64 virtual nodes per server gives each of the three servers close to a third of the requests.

    Key idea: Many virtual nodes per server give each server an almost equal share of the ring.

  5. 5. Adding a server moves only its share

    App 4 boots with an empty cache and joins the ring once it passes its health checks, one to two seconds in. Its 64 points take over small arcs from the other three servers.

    Only the keys on those arcs move, about a quarter of the requests, and they are cache misses on App 4 at first. Every other key stays where it was, so the three existing caches keep hitting. Removing a server works the same way in reverse: only its keys move, to their clockwise neighbours.

    Scene: App 4 joins the ring after passing health checks. About a quarter of the requests move to it; the caches of App 1 to 3 keep their hit ratio while Cache 4 warms up.

    Key idea: Adding or removing one of N servers moves only about 1/N of the keys.

  6. 6. A server fails: its keys move, nothing else

    One second in, App 2 crashes. Until health checks remove it, requests for its keys fail. Then its keys move to the next points clockwise, spread over App 1, App 3 and App 4, which see them as cache misses at first.

    Keys that belonged to the survivors never move, so they keep hitting their caches. With mod N, the same crash would have reshuffled about three quarters of all keys.

    Scene: App 2 crashes and is removed after its health checks fail. Its keys move to the other three servers; their own keys stay put.

    Key idea: A failure costs the failed server’s keys, not everyone’s.

  7. 7. Hot keys break the balance

    App 2 is back and popularity is strongly skewed again: the top few items get a large share of all requests. A key always goes to the same server, so the server that owns the hottest keys gets far more traffic than the others, however even the ring is.

    This is the price of affinity. Mitigations: cache hot keys in front of the ring, replicate them to several servers, add a random suffix to split one hot key into several, or use consistent hashing with bounded loads, which moves keys away from a server above its fair share.

    Scene: Key popularity is very skewed. The server that owns the most popular keys receives far more requests than the others.

    Key idea: Hashing balances keys, not load: a hot key stays on one server.

  8. 8. Where consistent hashing is used

    Use consistent hashing when where a key lives matters: cache clusters (memcached clients), sharded databases and key-value stores (Dynamo, Cassandra), sticky routing to stateful services. It keeps key movement to about 1/N when the cluster changes.

    It does not balance load by itself. Watch per-server traffic, plan for hot keys, and remember a moved key is a cold key.

    Scene: Four servers on the hash ring, each with its own cache, serve skewed traffic.

    Key idea: Consistent hashing gives stable key placement with minimal movement; load balance needs extra care.