npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

bull-redlock

v2.2.1

Published

A node.js redlock implementation for distributed redis locks

Downloads

564

Readme

npm version Build Status Coverage Status

Redlock

This is a node.js implementation of the redlock algorithm for distributed redis locks. It provides strong guarantees in both single-redis and multi-redis environments, and provides fault tolerance through use of multiple independent redis instances or clusters.

###High-Availability Recommendations

  • Use at least 3 independent servers or clusters
  • Use an odd number of independent redis servers for most installations
  • Use an odd number of independent redis clusters for massive installations
  • When possible, distribute redis nodes across different physical machines

###Using Cluster/Sentinel It is completely possible to use a single redis cluster or sentinal configuration by passing one preconfigured client to redlock. While you do gain high availability and vastly increased throughput under this scheme, the failure modes are a bit different, and it becomes theoretically possible that a lock is acquired twice:

Assume you are using eventually-consistent redis replication, and you acquire a lock for a resource. Immediately after acquiring your lock, the redis master for that shard crashes. Redis does its thing and fails over to the slave which hasn't yet synced your lock. If another process attempts to acquire a lock for the same resource, it will succeed!

This is why redlock allows you to specify multiple independent nodes/clusters: by requiring consensus between them, we can safely take out or fail-over a minority of nodes without invalidating active locks.

To learn more about the the algorithm, check out the redis distlock page.

###How do I check if something is locked? Redlock cannot tell you with certainty if a resource is currently locked. For example, if you are on the smaller side of a network partition you will fail to acquire a lock, but you don't know if the lock exists on the other side; all you know is that you can't guarantee exclusivity on yours.

That said, for many tasks it's sufficient to attempt a lock with retryCount=0, and treat a failure as the resource being "locked" or (more correctly) "unavailable",

Installation

npm install --save redlock

Configuration

Redlock can use node redis, ioredis or any other compatible redis library to keep its client connections.

A redlock object is instantiated with an array of at least one redis client and an optional options object. Properties of the Redlock object should NOT be changed after it is firstused, as doing so could have unintended consequences for live locks.

var client1 = require('redis').createClient(6379, 'redis1.example.com');
var client2 = require('redis').createClient(6379, 'redis2.example.com');
var client3 = require('redis').createClient(6379, 'redis3.example.com');
var Redlock = require('redlock');

var redlock = new Redlock(
	// you should have one client for each redis node
	// in your cluster
	[client1, client2, client3],
	{
		// the expected clock drift; for more details
		// see http://redis.io/topics/distlock
		driftFactor: 0.01, // time in ms

		// the max number of times Redlock will attempt
		// to lock a resource before erroring
		retryCount:  10,

		// the time in ms between attempts
		retryDelay:  400, // time in ms

		// the max time in ms randomly added to retries
		// to improve performance under high contention
		// see https://www.awsarchitectureblog.com/2015/03/backoff.html
		retryJitter:  400 // time in ms
	}
);

Error Handling

Because redlock is designed for high availability, it does not care if a minority of redis instances/clusters fail at an operation. If you want to write logs or take another action when a redis client fails, you can listen for the clientError event:


// ...

redlock.on('clientError', function(err) {
	console.error('A redis error has occurred:', err);
});

// ...

Usage (promise style)

###Locking & Unlocking


// the string identifier for the resource you want to lock
var resource = 'locks:account:322456';

// the maximum amount of time you want the resource locked,
// keeping in mind that you can extend the lock up until
// the point when it expires
var ttl = 1000;

redlock.lock(resource, ttl).then(function(lock) {

	// ...do something here...

	// unlock your resource when you are done
	return lock.unlock()
	.catch(function(err) {
		// we weren't able to reach redis; your lock will eventually
		// expire, but you probably want to log this error
		console.error(err);
	});
});

###Locking and Extending

redlock.lock('locks:account:322456', 1000).then(function(lock) {

	// ...do something here...

	// if you need more time, you can continue to extend
	// the lock as long as you never let it expire
	return lock.extend(1000).then(function(lock){

		// ...do something here...

		// unlock your resource when you are done
		return lock.unlock()
		.catch(function(err) {
			// we weren't able to reach redis; your lock will eventually
			// expire, but you probably want to log this error
			console.error(err);
		});
	});
});

Usage (disposer style)

###Locking & Unlocking

var using = require('bluebird').using;

// the string identifier for the resource you want to lock
var resource = 'locks:account:322456';

// the maximum amount of time you want the resource locked,
// keeping in mind that you can extend the lock up until
// the point when it expires
var ttl = 1000;

// if we weren't able to reach redis, your lock will eventually
// expire, but you probably want to do something like log that
// an error occurred; if you don't pass a handler, this error
// will be ignored
function unlockErrorHandler(err) {
	console.error(err);
}

using(redlock.disposer(resource, ttl, unlockErrorHandler), function(lock) {

	// ...do something here...

}); // <-- unlock is automatically handled by bluebird

###Locking and Extending

using(redlock.disposer('locks:account:322456', 1000, unlockErrorHandler), function(lock) {

	// ...do something here...

	// if you need more time, you can continue to extend
	// the lock until it expires
	return lock.extend(1000).then(function(extended){

		// Note that redlock modifies the original lock,
		// so the vars `lock` and `extended` point to the
		// exact same object

		// ...do something here...

	});
}); // <-- unlock is automatically handled by bluebird

Usage (callback style)

###Locking & Unlocking


// the string identifier for the resource you want to lock
var resource = 'locks:account:322456';

// the maximum amount of time you want the resource locked,
// keeping in mind that you can extend the lock up until
// the point when it expires
var ttl = 1000;

redlock.lock(resource, ttl, function(err, lock) {

	// we failed to lock the resource
	if(err) {
		// ...
	}

	// we have the lock
	else {


		// ...do something here...


		// unlock your resource when you are done
		lock.unlock(function(err) {
			// we weren't able to reach redis; your lock will eventually
			// expire, but you probably want to log this error
			console.error(err);
		});
	}
});

###Locking and Extending

redlock.lock('locks:account:322456', 1000, function(err, lock) {

	// we failed to lock the resource
	if(err) {
		// ...
	}

	// we have the lock
	else {


		// ...do something here...


		// if you need more time, you can continue to extend
		// the lock until it expires
		lock.extend(1000, function(err, lock){

			// we failed to extend the lock on the resource
			if(err) {
				// ...
			}


			// ...do something here...


			// unlock your resource when you are done
			lock.unlock();
		}
	}
});

API Docs

###Redlock.lock(resource, ttl, ?callback)

  • resource (string) resource to be locked
  • ttl (number) time in ms until the lock expires
  • callback (function) callback returning:
    • err (Error)
    • lock (Lock)

###Redlock.unlock(lock, ?callback)

  • lock (Lock) lock to be released
  • callback (function) callback returning:
    • err (Error)

###Redlock.extend(lock, ttl, ?callback)

  • lock (Lock) lock to be extended
  • ttl (number) time in ms to extend the lock's expiration
  • callback (function) callback returning:
    • err (Error)
    • lock (Lock)

###Redlock.disposer(resource, ttl, ?unlockErrorHandler)

  • resource (string) resource to be locked
  • ttl (number) time in ms to extend the lock's expiration
  • callback (function) error handler called with:
    • err (Error)

###Lock.unlock(?callback)

  • callback (function) callback returning:
    • err (Error)

###Lock.extend(ttl, ?callback)

  • ttl (number) time in ms to extend the lock's expiration
  • callback (function) callback returning:
    • err (Error)
    • lock (Lock)