Skip to content

Consistent Hashing: Adding Cache Nodes Without a Miss Storm

Place keys on a hash ring with virtual nodes so that adding or removing a server moves only about 1/N of the keys, instead of nearly all of them.

19 min readSystem pattern

Map keys to a changing set of nodes so that a membership change moves only the keys that must move, about K/N of K keys. Use virtual nodes to keep the load even and to spread a departed node's keys across all survivors instead of dumping them on one neighbour.

Consistent hashing decides which server owns a key in a way that survives the server list changing. With plain hash(key) % N, adding one node reassigns almost every key. On a ring, adding one node takes roughly 1/N of the keys and leaves the rest where they are. This guide follows one invented incident: a parcel-tracking cache fleet that grew from 12 to 13 nodes and took the database down. The fix is a ring with virtual nodes. You will see how to build one, how to size it, and what to say about it in a system design interview.

The problem

A situation where the obvious design starts to hurt.

Parcelwise runs a parcel-tracking API. At holiday peak it serves about 40,000 tracking-page reads per second. Each read looks up parcel:{id} in a fleet of 12 cache nodes (64 GB each). On a miss it falls back to a Postgres cluster that was sized for about 8,000 reads per second. The hit ratio sat at 94%, so Postgres saw roughly 2,400 reads per second.

The 40 tracking-api pods picked a cache node with crc32(key) % 12. On a Monday in December, memory pressure led the on-call engineer to add cache-13 and roll the pods to % 13. For a uniformly distributed hash, a key keeps its node only when h % 12 == h % 13. That holds for 12 of every 156 values, about 7.7% of keys. The other 92.3% now pointed at a node that had never seen them.

The hit ratio fell from 94% to about 7% within a minute. Postgres went from 2,400 to roughly 37,000 reads per second. Connection pools saturated, p99 latency on the tracking page climbed from 40 ms to 2.8 s, and the API returned timeouts for 25 minutes while the cache refilled. Rolling back made things worse at first: the keys had been rewritten under the 13-node layout, so reverting to % 12 missed them again.

The root cause was not the extra node. The routing function tied every key's placement to the total node count, so any change in N reshuffled the whole keyspace.

The solution

What the pattern proposes.

Replace modulo routing with a hash ring. Hash every key into a 32-bit space, from 0 to 2^32 - 1, and treat that space as a circle. Each cache node is hashed onto the same circle at many positions called virtual nodes (vnodes). Parcelwise uses 160 per node: cache-07#0 through cache-07#159. A key belongs to the first vnode at or after its hash, going clockwise and wrapping at the top.

When cache-13 joins, its 160 points land in 160 small arcs spread around the ring. Inside each arc it takes the keys that previously went to the next vnode clockwise. No other key moves. About 1/13 of keys move, all of them to the new node. For Parcelwise that is a temporary extra 2,900 or so database reads per second, peaking near 5,300 total. That is well inside the 8,000 budget.

When a node leaves, only its own keys move. Because its 160 points sit next to vnodes of many different nodes, those keys spread over all 12 survivors rather than doubling the load on one neighbour. Virtual nodes also smooth out the random gaps that a single point per node would leave. With one point each, one node can easily own two or three times its fair share of the ring.

Every pod must build the same ring. So the membership list (node names and weights) lives in one versioned config that every pod watches, and the hash is an explicit function (the first 4 bytes of MD5), never a language's built-in hash. Lookup is a binary search over the sorted points: O(log(N x V)), about 11 comparisons for 13 x 160 = 2,080 points.

An everyday analogy

The same idea, outside software.

Picture a circular running track with numbered markers every metre, and a set of water stations placed along it. A runner who stops at metre 3,412 walks forward to the next station. If you add a new station, only the runners between it and the previous station change where they drink. Everyone else keeps their station.

Virtual nodes are like letting each team set up many small stations around the track instead of one big one. Coverage evens out, and if a team packs up, its runners spread out among many other stations instead of all crowding into the next one.

Structure

The pieces and how they relate.

Parcelwise tracking reads: each pod routes keys through an in-process hash ring built from a shared membership config.Web and app clients calls tracking-api (GET /track/:id). tracking-api calls HashRing (in-process) (getNode(parcel:id)). HashRing (in-process) sends to cache-01 (owned arcs). HashRing (in-process) sends to cache-02 (owned arcs). HashRing (in-process) sends to cache-12 (owned arcs). HashRing (in-process) sends to cache-13 (new) (owned arcs). tracking-api calls Postgres parcels (on cache miss). Membership config sends asynchronously to HashRing (in-process) (watch, rebuild ring).Web and appclients40k tracking reads/sat peaktracking-api40 pods, cache-asidereadsHashRing(in-process)13 nodes x 160vnodes, binar…cache-0164 GB, ~1/13 of keyscache-0264 GB, ~1/13 of keyscache-1264 GB, ~1/13 of keyscache-13 (new)takes ~7.7% of keys,from all 12Membership configversioned node listand weightsPostgres parcelsbudget ~8k reads/sWhy it holdsadding a node moves ~1/N keys, not ~92%GET /track/:idgetNode(parcel:id)owned arcsowned arcsowned arcsowned arcson cache misswatch, rebuild ring
Parcelwise tracking reads: each pod routes keys through an in-process hash ring built from a shared membership config.

Participants

Hash function
Maps strings to a 32-bit position. It must be stable across processes, languages and deploys. Parcelwise uses the first 4 bytes of MD5, read big-endian, for both keys and vnode labels.
Ring (sorted points)
A sorted array of (position, node) pairs, one per virtual node. Lookup is a binary search for the first position at or after the key's hash, wrapping to index 0 past the end.
Virtual nodes
Each physical node appears V times on the ring under labels like cache-07#42. More points give more even arcs, and a departing node's keys spread over many successors. A weight multiplies V for bigger machines.
Membership config
The single source of truth for which nodes exist and their weights, with a version number. Every pod rebuilds its ring from it, so all pods agree on ownership.
Cache nodes
The physical servers that own the arcs. They do not know about the ring. Routing happens entirely in the client library.
Caller (tracking-api)
Asks the ring for the owner of parcel:{id}, reads from that node, and on a miss loads from Postgres and writes back to the same node.

Pseudocode

The solution to the scenario, language-neutral.

const SPACE = 2^32

function position(s):
    return first 4 bytes of md5(s) as unsigned big-endian int

class Ring:
    points = []            // sorted by (position, node)
    weights = {}

    addNode(node, weight):
        weights[node] = weight
        for i in 0 .. weight * VNODES - 1:
            points.append((position(node + "#" + i), node))
        sort points by (position, node)

    removeNode(node):
        delete weights[node]
        points = points where point.node != node

    getNodes(key, n):
        wanted = min(n, count(weights))
        i = first index where points[i].position >= position(key)   // binary search
        result = []
        while size(result) < wanted:
            node = points[i mod size(points)].node     // wrap around
            if node not in result: result.append(node)
            i = i + 1
        return result

// read path in tracking-api
function track(parcelId):
    key = "parcel:" + parcelId
    node = ring.getNodes(key, 1)[0]
    value = cache[node].get(key)
    if value is missing:
        value = db.loadParcel(parcelId)
        cache[node].set(key, value, ttl = 300s)
    return value

The code

The same solution in TypeScript, Python and PHP.

import { createHash } from "node:crypto";

type Point = { hash: number; node: string };

export class HashRing {
  private points: Point[] = [];
  private readonly weights = new Map<string, number>();

  constructor(private readonly vnodesPerWeight = 160) {}

  static hash(value: string): number {
    return createHash("md5").update(value).digest().readUInt32BE(0);
  }

  addNode(node: string, weight = 1): void {
    if (!Number.isInteger(weight) || weight < 1) throw new Error("weight must be a positive integer");
    if (this.weights.has(node)) throw new Error(`node ${node} is already on the ring`);
    this.weights.set(node, weight);
    for (let i = 0; i < weight * this.vnodesPerWeight; i++) {
      this.points.push({ hash: HashRing.hash(`${node}#${i}`), node });
    }
    this.points.sort((a, b) => a.hash - b.hash || (a.node < b.node ? -1 : a.node > b.node ? 1 : 0));
  }

  removeNode(node: string): void {
    if (!this.weights.delete(node)) return;
    this.points = this.points.filter((p) => p.node !== node);
  }

  getNode(key: string): string {
    return this.getNodes(key, 1)[0];
  }

  getNodes(key: string, n: number): string[] {
    if (this.points.length === 0) throw new Error("ring is empty");
    const wanted = Math.min(n, this.weights.size);
    const result: string[] = [];
    let i = this.firstIndexAtOrAfter(HashRing.hash(key));
    while (result.length < wanted) {
      const node = this.points[i % this.points.length].node;
      if (!result.includes(node)) result.push(node);
      i++;
    }
    return result;
  }

  private firstIndexAtOrAfter(h: number): number {
    let lo = 0;
    let hi = this.points.length;
    while (lo < hi) {
      const mid = (lo + hi) >>> 1;
      if (this.points[mid].hash < h) lo = mid + 1;
      else hi = mid;
    }
    return lo; // may equal length; caller wraps with modulo
  }
}

// Demo: how many keys move when cache-13 joins a 12-node ring?
const ring = new HashRing();
for (let i = 1; i <= 12; i++) ring.addNode(`cache-${String(i).padStart(2, "0")}`);

const keys = Array.from({ length: 100_000 }, (_, i) => `parcel:${i}`);
const before = keys.map((k) => ring.getNode(k));
ring.addNode("cache-13");
const moved = keys.filter((k, i) => ring.getNode(k) !== before[i]).length;

console.log(`moved ${((moved / keys.length) * 100).toFixed(1)}% of keys`); // close to 1/13, about 7.7%
console.log("replicas:", ring.getNodes("parcel:42", 3));

When to use it

Situations where it pays off.

  • A cache or key-value tier where nodes are added, removed or replaced while traffic flows, and a cold miss costs real backend capacity.

    Each membership change invalidates about 1/N of the cache instead of nearly all of it, so the miss spike stays within what the database can absorb.

  • Stateful partitioning where moving a key means copying data, such as a distributed key-value store, per-user session affinity or partitioned counters.

    The amount of data to stream during a rebalance is proportional to the change (about K/N), not to the whole dataset.

  • Many independent clients must agree on placement without asking a coordinator on every request.

    Given the same membership list and hash function, every client computes the same owner locally in O(log(N x V)) with no network hop.

  • You need replicas for each key on distinct machines, for example three copies in a storage tier.

    Walking clockwise and collecting the first R distinct nodes gives a deterministic replica set that also changes minimally when membership changes.

  • Nodes have different capacities, such as mixing 64 GB and 128 GB cache machines.

    Giving a node twice the vnodes gives it about twice the keyspace, without a separate placement scheme.

How to implement it

Steps to introduce it in existing code.

  1. Pick an explicit, stable hash such as MD5 truncated to 32 bits, xxHash or Murmur3. Never use a runtime's built-in string hash, which may be randomized per process.

  2. Choose vnodes per node. 100 to 200 is a common starting point. Simulate your real key set with your real node count and check the busiest node's share against the average before committing.

  3. Store membership (node name, weight, version) in one place every client watches. Rebuild the ring atomically on change and swap the reference, so lookups never see a half-built ring.

  4. Sort points by (position, node name) so hash collisions break ties the same way on every client.

  5. Look up with a binary search for the first point at or after the key's hash, wrapping to index 0. For R replicas, keep walking and skip nodes you have already chosen.

  6. Roll out new nodes one at a time. Optionally ramp vnodes (40, then 80, then 160) so the database sees the miss burst in slices. Labels #0..#39 are a prefix of #0..#159, so ramping only adds points.

  7. Export per-node key counts, hit ratio and ring version from every pod. Alert if two pods report different ring versions for more than a minute.

Pros and cons

What you gain and what you pay.

Pros

  • Adding or removing one of N nodes moves about 1/N of the keys. For Parcelwise that is 7.7% instead of 92.3%.
  • With vnodes, a failed node's load spreads across all survivors instead of landing on one neighbour.
  • Placement is computed locally by every client, with no lookup service on the hot path.
  • Weights let mixed hardware share load in proportion to capacity.
  • Replica selection falls out of the same structure by walking clockwise.

Cons

  • Balance is statistical. With too few vnodes, some nodes own noticeably more of the keyspace than others.
  • It does nothing for hot keys. One popular key still lands on exactly one node.
  • Every client must have identical membership and hash functions. A disagreement silently splits the cache.
  • Range queries are impossible, because adjacent keys are scattered across the ring by design.
  • Removing a node still leaves its keys cold on their new owners. The ring limits the blast radius but does not warm anything.

Trade-offs

Decisions you'll have to make, each with its price.

  • 160 vnodes per node instead of 1 or 1,000

    You gainEven arcs and a departed node's keys spread over all 12 survivors. The ring stays at 2,080 points, about 11 comparisons per lookup, and rebuilds in well under a millisecond.

    You pay1,000 per node would balance slightly better but make every rebuild sort 13,000 points per pod. A single point per node would leave some nodes owning several times their share.

  • Client-side ring in every tracking-api pod instead of a routing proxy tier

    You gainNo extra network hop and no proxy fleet to scale for 40,000 reads per second.

    You payAll 40 pods must agree on membership. A pod that misses a config update routes a slice of keys to the wrong node until it catches up.

  • MD5 truncated to 32 bits instead of xxHash or Murmur3

    You gainAvailable in the standard library of TypeScript, Python and PHP with identical output, so mixed-language clients agree without extra dependencies.

    You payMD5 is slower per call than non-cryptographic hashes. At 40,000 lookups per second spread over 40 pods this is negligible, but in a hot loop with millions of lookups per second you would switch.

  • Eject a failed cache node only after 3 failed health checks over 15 seconds

    You gainA 2-second network blip does not reshuffle 1/13 of the keyspace twice, once on removal and again on rejoin.

    You payFor up to 15 seconds, requests for that node's keys miss and go to Postgres. That is about 2,900 extra reads per second, which the caller must survive with tight timeouts.

  • Ramp a new node's vnodes 40, 80, 160 over 30 minutes

    You gainThe miss burst arrives in thirds, keeping Postgres far below its 8,000 reads per second budget even at peak.

    You payThe rollout takes longer. Until it finishes, the new node carries only part of its share, so the memory relief you added it for arrives gradually.

How it fails

What goes wrong in production and how to prevent it.

  • Pods disagree on membership: half the fleet has cache-13 on the ring and half does not, so the same key is cached in two places and invalidations hit only one.

    What to doVersion the membership config and have every pod export its ring version as a metric. Alert when versions differ for over 60 seconds. On writes or invalidations, delete from both the old and the new owner while a change is in flight.

  • A Python service used built-in hash() for placement, so each restart produced a different ring and the hit ratio dropped after every deploy.

    What to doUse an explicit hash such as the first 4 bytes of MD5. Add a cross-language test that checks a fixed list of 1,000 keys maps to the same nodes in every client.

  • The new node starts cold and its 7.7% of keys all miss at once during peak traffic.

    What to doAdd nodes off-peak. Ramp vnodes from 40 to 160, or pre-warm by copying the moving keys from their old owners before switching the ring version.

  • Too few vnodes, for example 8 per node, so one cache node owns about twice its fair share and evicts aggressively while others sit half empty.

    What to doSimulate placement with production key samples before rollout. Raise vnodes until the busiest node is within your headroom, and track per-node key count and memory as dashboards.

  • A flapping node is removed and re-added every few seconds, moving its keys back and forth and keeping both sides cold.

    What to doSeparate fast failure handling (per-node circuit breaker, 50 ms timeouts, fall through to the database) from slow membership changes (ejection after sustained failure, re-add only after a stable period such as 2 minutes).

In a system design interview

When to bring it up and how to explain it.

Bring it up when the design has a partitioned tier whose membership changes: a distributed cache, a key-value store, sticky routing of users to workers, or partitioned queues. It is especially relevant when the interviewer asks what happens when you add a node or a node dies.

What you could say

For the cache tier I would not route with hash mod N, because adding one node to N remaps about N/(N+1) of keys. Going from 12 to 13 nodes that is over 92%, which turns into a miss storm on the database. Instead I would put nodes on a hash ring. Keys and nodes hash into the same 32-bit space, and a key belongs to the first node clockwise from it. Adding a node then moves only about 1/N of keys, and removing one moves only that node's keys.

Each physical node gets around 150 virtual nodes on the ring. That evens out the arcs, and when a node dies its keys spread over all the survivors instead of doubling one neighbour's load. Weights are just more vnodes for bigger machines.

The ring lives in the client library. Lookup is a binary search over a couple of thousand points, so it is effectively free. The things I would be careful about are operational: every client must use the same explicit hash and the same versioned membership list, I would eject failed nodes slowly to avoid flapping, and I would ramp new nodes in so the database sees the miss burst in pieces. Consistent hashing does not solve hot keys, so I would handle those separately.

Likely follow-ups

How do you pick replicas for a key?

Keep walking clockwise from the key's position and take the first R distinct physical nodes, skipping vnodes of nodes already chosen. With rack or zone awareness, also skip nodes in a zone you already have. The replica set is deterministic and changes minimally on membership changes.

What is the lookup and rebuild cost?

Lookup is a binary search over N x V sorted points, O(log(N x V)). With 13 nodes and 160 vnodes that is 2,080 points and about 11 comparisons. A rebuild is O(N x V log(N x V)) for the sort. It happens only on membership changes, and you build the new ring off to the side and swap a reference.

A node fails. What happens to its keys and to load?

Only its keys move, to the next vnode clockwise from each of its points. Because those points are interleaved with vnodes of many different nodes, the keys spread roughly evenly over the survivors. Each survivor gains about 1/(N-1) of the departed node's share. Those keys start cold, so the database sees roughly 1/N of the cached traffic as extra misses until they refill.

When would you not use a hash ring?

When you need range scans over ordered keys, use range partitioning. When nodes are numbered and only grow or shrink at the end, jump hash is simpler and better balanced. When there are only a handful of nodes and lookups are not hot, rendezvous hashing is simpler and needs no vnodes.

Relations with other guides

Patterns it's often confused or combined with.

Common questions

Short answers to the usual doubts.

Why does modulo hashing move so many keys?

With h % N, a key's node depends on N itself. Going from N to N+1 keeps a key in place only when h % N == h % (N+1), which for uniform hashes happens for about 1/(N+1) of keys. So roughly N/(N+1) of keys move: 92.3% when going from 12 to 13 nodes.

How many virtual nodes should each server get?

Enough that the busiest node's share in a simulation of your real keys is within the headroom you are willing to provision. 100 to 200 per node is a typical start. The ring itself is cheap: 13 nodes at 160 vnodes is 2,080 points, and lookup takes about 11 comparisons. The cost of more vnodes is mostly rebuild time and a bigger ring to keep consistent.

Does consistent hashing fix hot keys?

No. It balances the keyspace, not the traffic. If one key gets 5% of all reads, its owner carries that alone. Handle hot keys separately, for example with a short in-process cache on the API pods or by replicating that key under suffixed names and reading from a random copy.

What about jump hash or rendezvous hashing?

Jump consistent hash needs no ring and gives near-perfect balance, but nodes must be numbered 0 to N-1 and you can only add or remove at the end. Rendezvous (highest random weight) hashing scores every node per key, which is O(N) per lookup and fine for dozens of nodes. A ring with vnodes is the most flexible for arbitrary named nodes and weights.

Can I use my language's built-in hash function?

Not for anything shared between processes. Python randomizes hash() for strings per process unless PYTHONHASHSEED is fixed, and other runtimes make no cross-version promises. Two pods would build different rings. Use a named, specified hash and test that every client language produces the same owner for a fixed set of keys.

Next guide6 of 8 · DataCache-Aside: Invalidation, Stampedes, TTLs and Stale ReadsRead the next one