Chapter 01 · The mod N trap01 / 19
Spread keys with hash mod N
Your app caches user profiles in memory so it doesn't hit the database on every page view. One cache server isn't enough, so you run four, cache-a to cache-d. Each key must live on exactly one of them, and every app server has to agree on which.
The classic rule: hash the key to a big number, divide by the number of servers N, and use the remainder as an index. hash("user:alice") is 1,500,882,790, and 1,500,882,790 mod 4 = 2, so Alice lives on servers[2], cache-c.
One line of code, an even spread, no lookup table. The cache is warm, so every request comes back as a green hit, straight from memory.
const servers = ['cache-a', 'cache-b', 'cache-c', 'cache-d'];function serverFor(key) {return servers[murmur3(key) % servers.length];}serverFor('user:alice'); // 1500882790 % 4 = 2 → 'cache-c'