Suryanand/ Bootcamp
suryanand.com ↗Let's talk
Frame · dsa / ai-algorithms / 19-consistent-hashing-model-replicas.jsJavaScript

Consistent Hashing for Routing Requests to Model Replicas

Use the tabs to read the prompt, implementation, and tests separately. Syntax uses Shiki; tests can be executed on the server with node --test.

Same file as in the repo · ~20s timeout

From file header (JSDoc)

Consistent Hashing for Routing Requests to Model Replicas

Problem: An inference gateway routes each conversation to the same model
replica so its KV/prompt cache stays warm, and adding or removing a replica
should move as few conversations as possible. Implement a hash ring:
- `new HashRing(replicas, vnodes = 100)`: each replica is placed on a
  32-bit ring at `vnodes` points, hash(`${replica}#${i}`), to even out load.
- `getNode(key)`: the replica owning the first ring point clockwise from
  hash(key) (wrapping around).
- `getNodes(key, count)`: the first `count` distinct replicas clockwise,
  for fallbacks or replication.
- `addNode(replica)` / `removeNode(replica)`.
Use 32-bit FNV-1a followed by a murmur3 finaliser as the hash.

Constraints:
- 1 <= replicas <= 1000, 1 <= vnodes <= 1000

Example:
  ring = new HashRing(["gpu-a", "gpu-b", "gpu-c"])
  ring.getNode("conversation-42") -> same replica on every call
  ring.removeNode("gpu-b") -> only keys owned by gpu-b move

Approach: Keep ring points as a sorted array of [hash, replica] and binary
search for the first point >= hash(key). Lookup O(log(R * V)); add/remove
O(R * V log(R * V)) to rebuild the sorted array; space O(R * V). With
consistent hashing roughly 1/R of keys move when membership changes,
instead of almost all keys with `hash % R`.
@param {string[]} replicas
@param {number} [vnodes]
Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.