jakejscott / hrw-hash

HRW / Rendezvous hashing in JS

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

HRW (Highest Random Weight) hashing / Rendezvous hashing

https://en.wikipedia.org/wiki/Rendezvous_hashing.

npm install hrw-hash
import { hrwHash } from 'hrw-hash'
// or const { hrwHash } = require('hrw-hash')
const servers = ['image-server-1.example.com', 'image-server-2.example.com']
const domainToUse = hrwHash('example.png', servers)[0] // always 'image-server-2.example.com'

Advantage of this hashing over other sticky load balancing algorithms is that:

  1. it does not use a shared lookup table / ring
  2. it is independent of the order of destinations (hrwHash('john', ['a', 'b']) is same as hrwHash('john', ['b', 'a']))
  3. it distributes keys evenly (probabilistically) when a destination is added or removed

Disadvantage of this hashing method:

  1. Replacing a destination with another one will re-route keys unnecessarily as the algo is order insensitive

The implementation is small (0.5 kb minified) and with no 3rd party dependencies. It uses bigint, unescape and encodeURIComponent, so it supports modern browsers, node.js >= 12 and cloudflare workers.

It uses mulberry32(fnv1a32('key')) as hash function internally for the random hash. In my tests, this gives better distribution than fnv1a-32 alone and still keeps the implementation fast and small.

// for advanced use cases you can import the hash function
import { hashFunc } from 'hrw-hash'
hashFunc('string') // returns positive integer < 2^32

About

HRW / Rendezvous hashing in JS

License:MIT License


Languages

Language:JavaScript 100.0%