Hashring

hashring (GitHub: 3rd-Eden/node-hashring, License: MIT) by Arnout Kazemier is a JavaScript implementation of the Consistent Hashing algorythm. If you don’t know exactly what that is and not into reading dry Wikipedia articles, watch this 3 minute video for a pretty good overview of what’s going on.

 

hashring also compatible with the original libketama library that was developed at last.fm as well as with the hash_ring module for Python.

npm install hashring

Usage

'use strict';

var HashRing = require('hashring');

var ring = new HashRing({
  '127.0.0.1:11211': { vnodes: 50 },
  '127.0.0.2:11211': { vnodes: 200 },
  '127.0.0.3:11211': { vnodes: 100 }
});

console.log(ring.get('npmawesome'));
// 127.0.0.2:11211

console.log(ring.get('http://...'));
// 127.0.0.3:11211

console.log(ring.range('http://...', 2));
// [ '127.0.0.3:11211', '127.0.0.1:11211' ]

This can be immensly useful for caching or distributing data to multiple servers. Weights or vnodes are used to give servers a bigger distribution in the hashring. For example if you have 3 servers where you want to distribute your keys over but not all servers are equal in capacity as 2 of those machines have 200mb of memory and the other has 3.2 gig of memory. The last server is substantially bigger and there for should receive a greater distrubtion in the ring.

What Else?

Unfortunately hashring relies on C imlementation and therefore can’t be used in the browsers.

The module now requires a C++ compiler to be installed on your server as hashing the value requires support for 64bit bitshifting and JavaScript as a language only supports 32bit bitshifting.

Checkout the runnable example and github example repository. Have you seen other modules along these lines? Please let us know in the comments!

Post navigation

Leave a comment

Leave a Reply

Your email address will not be published.