Consistent Hash Ring Distribution
Build a consistent hash ring with virtual nodes for even key distribution and minimal remapping when nodes join or leave.
Code
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===0short-circuits the flow with an earlyreturnwhen 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
SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Webhook HMAC Signature VerifierVerify and generate HMAC-SHA256 webhook signatures for Stripe, GitHub, and raw hex headers locally using Web Crypto and constant-time comparison.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.