Consistent hashing

In one sentence

Place nodes and keys on the same hash ring and give each key to the next node clockwise, so adding or removing a node moves only ~1/N of the keys.

Analogy: Waiters stand at points around a round table; each serves the guests seated between the previous waiter and themselves. A new waiter takes guests from just one neighbour; everyone else keeps theirs.

A lookup is a binary search over sorted vnode tokens; a joining node only claims the arcs just before its own tokens.

How it works

  • With hash % N, growing 10 → 11 nodes moves ~91% of keys and a cache cluster turns cold.
  • Finding a key's node is a binary search over the sorted node positions on the ring.
  • Each server gets many virtual nodes, so load evens out and a dead node's keys spread over many peers.
  • Replication keeps walking clockwise: the next R distinct nodes hold the copies, as in Dynamo and Cassandra.
  • In LLM serving, hashing the session id sends repeat requests to the replica already holding their KV cache.

Check yourself

Answer to mark it learned; your answers aren't scored.

To reuse KV cache, you route LLM requests across 8 GPU replicas by a consistent hash of each prompt's first 2,000 tokens. After launch, one replica is at 100% and the other seven are idle. Most likely cause?

Go deeper

Consistent hashing ring Interactive lab
Full explanation

Consistent hashing assigns keys to nodes so that changing the node count moves only ~1/N of the keys. The naive hash(key) % N remaps almost everything on resize: going from 10 to 11 nodes moves ~91% of keys, so a cache cluster turns cold at once and the database behind it takes the full load.

How the ring works:

  1. Hash nodes and keys into the same circular space (e.g. 64-bit integers).
  2. A key belongs to the first node clockwise from its hash: a binary search over the sorted node positions.
  3. A joining node takes over only the arc just before it; a leaving node hands its arc to its successor. Every other key stays put.

One point per node gives uneven arcs, so each server gets many virtual nodes (tens to hundreds of points). Load evens out, a dead node's keys spread over many peers, and a bigger machine gets more vnodes. Replication keeps walking clockwise: the next R distinct nodes hold copies (Dynamo, Cassandra).

Alternatives: rendezvous (HRW) hashing scores hash(key, node) for every node and picks the highest — no ring, O(N) per lookup, ideal for tens of nodes. Jump hash and Maglev serve numbered shards and load balancers.

In LLM serving, hashing the session id or prompt prefix sends repeat requests to the replica that already holds their KV cache.

Code Hash ring with virtual nodes
pythonHash ring with virtual nodes
import bisect, hashlib

def h(s: str) -> int:
    # Stable across processes, unlike Python's salted built-in hash()
    return int.from_bytes(hashlib.md5(s.encode()).digest()[:8], "big")

class HashRing:
    def __init__(self, nodes: list[str], vnodes: int = 128):
        self.vnodes, self.ring = vnodes, []  # ring: sorted (token, node)
        for n in nodes:
            self.add(n)

    def add(self, node: str) -> None:
        for i in range(self.vnodes):  # many points per node evens out load
            bisect.insort(self.ring, (h(f"{node}#{i}"), node))

    def remove(self, node: str) -> None:
        self.ring = [(t, n) for t, n in self.ring if n != node]

    def get(self, key: str) -> str:
        i = bisect.bisect(self.ring, (h(key), ""))  # first token clockwise
        return self.ring[i % len(self.ring)][1]     # wrap around the ring

ring = HashRing([f"gpu-{i}" for i in range(10)])
keys = [f"session:{i}" for i in range(100_000)]
before = {k: ring.get(k) for k in keys}
ring.add("gpu-10")
moved = sum(before[k] != ring.get(k) for k in keys) / len(keys)
print(f"{moved:.1%} of sessions moved")  # ~9-10% (ideal 1/11); hash % N moves ~91%
Real example

You serve a support assistant on 8 vLLM replicas with prefix caching on. Conversations average 6 turns and reach ~20k tokens, so round-robin sends each new turn to a replica that never saw the earlier ones, and it re-prefills the whole history. Routing on a consistent hash of conversation_id keeps each conversation on one replica, so its KV cache is reused every turn. When autoscaling adds a 9th replica, ~1/9 of conversations move and pay one cold prefill; with % N, ~8/9 would. A bounded-load cap (each replica ≤1.25× the average) spills overflow to the next replica when a burst of long conversations lands on one.

Trade-offs +3 · −3

+ You gain

  • Resizing moves ~1/N of keys, so caches stay warm and rebalancing traffic stays small.
  • No central directory: any client with the member list computes the owner locally.
  • Vnodes give weighted capacity and spread a dead node's load over many peers.

− You pay

  • Hot keys still land on one node; skew needs bounded loads or key splitting.
  • Clients must agree on membership (gossip, etcd); different views route the same key differently.
  • No range scans: adjacent keys land on unrelated nodes.

Use it when

Partitioning a cache, key-value store or sticky routing (sessions, KV-cache affinity) across a node set that changes with autoscaling and failures.

Avoid it when

Range queries (use range partitioning), a fixed slot count you rebalance explicitly (Redis Cluster's 16,384 slots), or a small static pool where % N is fine.

Numbers to know 5
  • Growing from N to N+1 nodes: consistent hashing moves ~1/(N+1) of keys, % N moves ~N/(N+1). 10→11 is ~9% vs ~91%.
  • Rule of thumb: with V vnodes per node, load spread ≈ 1/√V, so 100 vnodes ≈ 10% standard deviation.
  • Cassandra: 256 vnodes per node by default before 4.0, 16 since 4.0 (paired with a smarter token allocator).
  • Redis Cluster skips the ring: 16,384 fixed slots (CRC16 of the key mod 16384) assigned to nodes.
  • Bounded loads (Google, 2016): cap each node at (1+ε)× the average load; overflow walks clockwise to the next node.
Common pitfalls 4
  • Hashing with Python's hash() or another per-process salted hash: every worker builds a different ring.
  • One point per node: with 10 nodes the largest arc is typically ~2–3× the average. Use vnodes.
  • Hashing on a prefix every request shares (one system prompt) routes the whole app to a single replica.
  • In a datastore, letting a new node serve its arc before the data has been streamed to it.
Interview questions 2

Answer out loud first, then reveal.

Why not just use `hash(key) % N`?Show answer

Because N changes. Going from 10 to 11 nodes remaps ~91% of keys: for a cache that's a cold cluster and a stampede on the database; for a datastore it's moving almost the whole dataset. Consistent hashing bounds movement to ~1/N. I'd use vnodes for balance and add bounded loads if traffic is skewed. If the shard count is fixed or I rebalance explicitly, I prefer fixed slots like Redis Cluster's 16,384: simpler to reason about.

How would you route LLM requests across GPU replicas to maximize KV-cache reuse?Show answer

First I pick the affinity key: conversation id for multi-turn chat, or a hash of the first few thousand tokens when many requests share a document. I route it with consistent hashing so autoscaling only invalidates ~1/N of the caches. Pure affinity melts a replica when one prefix is hot, so I cap load per replica and spill to the next one. At scale I'd use a cache-aware router, like SGLang's router or NVIDIA Dynamo's KV-aware routing, and watch prefix hit rate and p95 TTFT.