Consistent Hash Ring Distribution

Build a consistent hash ring with virtual nodes for even key distribution and minimal remapping when nodes join or leave.

JavascriptData Fetching

Code

javascriptsnippet
1 line
export function consistentHash(nodes,{replicas=150}={}){const ring=new Map();function hash(s){let h=0;for(let i=0;i<s.length;i++)h=((h<<5)-h+s.charCodeAt(i))|0;return h;}for(const n of nodes)for(let i=0;i<replicas;i++)ring.set(hash(n+':'+i),n);const sorted=[...ring.keys()].sort((a,b)=>a-b);function get(key){if(sorted.length===0)return undefined;const h=hash(key);for(const s of sorted)if(s>=h)return ring.get(s);return ring.get(sorted[0]);}get.ring=ring;return get;}

How it works

The working surface is the functions consistentHash, hash and get — everything else is wiring.

What to watch for

  • The guard sorted.length===0 short-circuits the flow with an early return when its condition holds.

Applying it

Entry signature: export function consistentHash(nodes,{replicas=150}={})

Import consistentHash from the file and call it — the rest of the code is implementation detail.

Interactive Tools for This Topic

FAQ

What has to be installed first?
Nothing — the runtime itself provides everything the code touches. The file defines `consistentHash`, `hash`, `get` at load time.