Nodejitsu

Save time managing and deploying your node.js app

Nodejitsu has joined GoDaddy

We are excited to join GoDaddy to help spearhead their largest Node.js product: Website Builder. Please read our blog post to learn more about customer transition plans and our continued support for Open Source within the node community.

Want to know all the details?
Read the full blog post or read the GoDaddy Announcement.

npmawesome: consistent hashing with HashRing

About the author

Name
Location
Worldwide
nodejitsu nodejitsu

Other popular posts

- Scaling Isomorphic Javascript Code - Keep a node.js server up with Forever - Package.json dependencies done right
- npm cheat sheet - 6 Must Have Node.js Modules

This is a guest post from Alex Gorbatchev over at npmawesome.com. Nodejitsu loved what npmawesome.com was doing and is now supporting the project.

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!