← Math
Math

Load distribution and hashing

A quarter of the keys move. Is that a quarter of the traffic?

Measure a hash-ring change by the traffic it moves as well as the keys that change owners.

Outcome

Find each key’s node on a hash ring, measure a join by the traffic it moves, and ramp a new node’s weight without moving more than the budget.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Hash ring
A circle of 32-bit hash positions; each node takes several points on it and owns the keys up to its points.
Clockwise successor
The first node point at or after a key’s position, wrapping from the end of the ring to the start.
Virtual node
One of several points a single server takes on the ring, usually by hashing its address with a counter; more points means more weight.
Moved work
The requests per second on keys that change owner; they miss on the new owner until it warms.
Hot key
A single key carrying a large share of the traffic, which no placement can split.

Why this matters

Adding a cache node should be routine. A changed key may be absent from a cold new owner and trigger origin work. Moved traffic measures exposure to that cold cache, not a guaranteed sustained origin request rate; warming, request coalescing and preexisting copies change actual misses. Hash rings keep that small on average, but averages say nothing about which keys move.

This lesson assumes modulo, sorting and weighted sums.

What a hash ring distributes

A hash ring maps keys and node points into the same ordered position space. Each key has one owner under a shared placement rule. Adding points changes ownership for part of that space. Direct placement by a key’s hash modulo the node count changes the divisor when that count changes.

Keys can carry very different request rates. Count changed owners, then weight those changes by the work each key brings to estimate exposure to a cold cache. This is a static placement calculation; warming and actual misses require additional observations.

01Clockwise to the next point

Clockwise to the next point

A web shop’s product pages are cached in memcached on three nodes, and the clients shard keys with a hash ring. Before a sale the team adds a fourth node. The runbook allows a change that moves at most 25% of the cached traffic to a cold node, and the join moves 3 of 12 product keys. One of them is the featured product.

Positions on the ring are unsigned 32-bit numbers. As Ketama-style memcached clients do, each node takes several points by hashing its address with a counter, 10.0.1.11:11211-0 to -3 for cache-1, and each product key is placed by hashing product:<id>. A key belongs to the first point at or after its position; past the last point it wraps to the smallest.

Use six selected products to inspect ownership and changed-owner work in this short program. The full replay below has twelve products totaling 830 requests/s; the short probe does not compute that full denominator. All displayed node points are unique. Real clients also need a shared collision policy, hash version, input bytes and membership view.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
type Point = [number, string];

// Ketama-style points: the first 4 bytes of MD5("10.0.1.11:11211-0") and so on, as unsigned 32-bit values.
const ring: Point[] = [
  [4037426743, "cache-1"],
  [466636989, "cache-1"],
  [3868369911, "cache-1"],
  [27988513, "cache-1"],
  [1723143637, "cache-2"],
  [4223217900, "cache-2"],
  [772661859, "cache-2"],
  [2984585505, "cache-2"],
  [3769411101, "cache-3"],
  [2107152803, "cache-3"],
  [4130353048, "cache-3"],
  [3890707553, "cache-3"]
];
const cache4 = [4132926451, 3880134546, 3691747687, 568364440]; // the new node's four points
const products = [
  [3030147485, 400],
  [4132392213, 20],
  [3874053415, 30],
  [187361881, 90],
  [1481399463, 50],
  [4111066980, 30]
]; // position of MD5("product:<id>"), requests per second

function owner(points: Point[], key: number): string {
  const sorted = [...points].sort((a, b) => a[0] - b[0]);

  return (sorted.find(([point]) => point >= key) ?? sorted[0])[1]; // wrap past the last point
}

console.log(products.map(([key]) => owner(ring, key)).join(" "));
const joined: Point[] = [...ring, ...cache4.map((point): Point => [point, "cache-4"])];
const moved = products.filter(([key]) => owner(ring, key) !== owner(joined, key));

console.log(
  moved.length,
  moved.reduce((sum, [, rate]) => sum + rate, 0)
); // products and req/s that cache-4 takes

node:crypto’s createHash("md5") gives the digest; the first four bytes, read as an unsigned little-endian integer, are a ring position.

02Count the work that moves

Count the work that moves

Requests per second on each node, before and after cache-4 joins
NodeBeforeAfter
cache-1190190
cache-2120100
cache-352090
cache-4–450

cache-4’s points take three products: 3 of 12 keys, 25%. Their traffic is 450 of 830 requests per second, 54.22%, because one of them is product:10000, the featured product at 400. That 450 requests/s is a cold-traffic exposure estimate. It does not mean all later requests miss after those three products are cached.

Which share should the runbook compare with its 25% limit?

03Modulo moves most keys

Modulo moves most keys

With node = h mod N, going from 3 nodes to 4 keeps a key on the same node only when h mod 3 equals h mod 4, which happens when h mod 12 is 0, 1 or 2. Under uniformly distributed hash residues and stable node labels, about 3 in 12 stay and 75% move. With exchangeable uniform point placement and enough points, a new equal-weight fourth node receives about a quarter of ring space in expectation. A particular finite ring, key sample and traffic mix can differ substantially.

A cache of 1,000,000 evenly hashed keys goes from mod 3 to mod 4. About how many keys move?

04Ramp the new node

Ramp the new node

A new node can join with part of its weight: its first point, then two, and so on, so its cache warms a slice at a time. Each candidate below is compared with the original three-node placement: its budget is cumulative moved traffic, not just the next step’s delta. A real warm-up must remeasure traffic and cache state between steps. The budget is 25% of 830, which is 207.5 requests per second.

cache-4’s weight, one point at a time
PointsMoved trafficBudgetBusiest node
120 (2.41%)withincache-3 520
250 (6.02%)withincache-3 490
3450 (54.22%)overcache-4 450
4450 (54.22%)overcache-4 450

05The hot key

The hot key

Weight 2 is as far as the budget allows, and cache-3 still serves 490 requests per second. Relieving it further means moving product:10000, which alone is about twice the budget. More points cannot split one key’s reads across owners in this single-owner model. Serving replicas with an explicit routing/consistency policy, or prewarming that key before moving ownership, changes the operational problem; either needs verification beyond this static placement calculation.

Can any weight within the budget bring cache-3 below 490 req/s?

06Add a cache node before the sale

Add a cache node before the sale

Before changing clients’ membership, the shop must reproduce each product’s clockwise owner. The join report then needs request-weighted movement rather than key share. The final planner searches the ordered point prefixes that meet that cumulative movement budget and minimizes the busiest node, including the new node; simply moving the fewest keys does not solve the load problem.

In the frontend Sticky regional routing in Next.js and Svelte Optional

A client can pick a regional endpoint by hashing the user ID onto a ring. With the same user ID bytes, hash and membership version, the selection repeats across sessions. This example uses FNV-1a over UTF-8 bytes rather than the reading’s MD5 positions, so all participating clients must explicitly agree on that different scheme. Adding a point changes the arcs it takes; this selector alone does not send the request or measure the traffic moved.

Estimate.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// Sticky routing: hash the user onto a ring of regional endpoints, with stable UTF-8 hashing and a shared membership version.
const ring = [
  { point: 0x2000_0000, url: "https://eu.example" },
  { point: 0x9000_0000, url: "https://us.example" },
  { point: 0xd000_0000, url: "https://ap.example" }
].sort((a, b) => a.point - b.point);

function fnv1a(text: string): number {
  let hash = 0x811c9dc5;

  for (const byte of new TextEncoder().encode(text))
    hash = Math.imul(hash ^ byte, 0x01000193);

  return hash >>> 0;
}

export function endpointFor(userId: string): string {
  const position = fnv1a(userId);

  return (ring.find((node) => node.point >= position) ?? ring[0]).url; // wrap past the last point
}

Check this idea later
A join moves 10% of the keys. What do you still need before approving it?
A key hashes exactly onto a node’s point. Which node owns it?
Sources

Ring positions were computed with MD5 in Python and the values run in Node 22, Go 1.27, Rust 1.99 and Apple clang 17. The shop and its traffic are a worked model.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.