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: distributed locking with redislock

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.

redislock (GitHub: danielstjules/redislock, License: MIT) by Daniel St. Jules is a module for distributed locking powered by Redis. This utility is very helpful when you are building a distributed application, or even a basic CPU cluster to take advantage of multiple cores. One of the cool features is ability to set maximum number of retries and amount of time between them.

npm install redislock  

Usage

Locking is performed using the following redis command:

SET key uuid PX timeout NX

If the SET returns OK, the lock has been acquired on the given key, and an expiration has been set. Then, releasing a lock uses the following redis script:

if redis.call('GET', KEYS[1]) == ARGV[1] then
  return redis.call('DEL', KEYS[1])
end
return 0

This ensures that the key is deleted only if it is currently holding the lock, by passing its UUID as an argument.

Example below creates a lock and then tries to acquire it second time. The second attempt will fail.

var redis = require('redis');  
var redislock = require('redislock');

var client = redis.createClient();  
var lock = redislock.createLock(client, {  
  timeout: 20000,
  retries: 3,
  delay: 100
});

function doStuff(done) {  
  lock.acquire('my:lock-name', function (err) {
    if (err) {
      console.log('Failed to get a lock...', err.message);
      return;
    }

    // tring to get the same lock second time will trigger an error. 
    doStuff(done);

    lock.release(function (err) {
      console.log('Do work here...');
      done();
    });
  });
}

doStuff(function() {  
  console.log('Done working...');
  client.end();
});

What Else?

Checkout the runnable example and github example repository.