A Redis backed distributed global lock

This code uses the formula here:

It provides several improvements over the original version based on:

It provides a few improvements over the one present in the Python redis library, for example since it utilizes the Lua functionality, it no longer requires every client to have synchronized time.


class retools.lock.Lock(key, expires=60, timeout=10, redis=None)[source]
__init__(key, expires=60, timeout=10, redis=None)[source]

Distributed locking using Redis Lua scripting for CAS operations.


with Lock('my_lock'):
    print "Critical section"
  • expires – We consider any existing lock older than expires seconds to be invalid in order to detect crashed clients. This value must be higher than it takes the critical section to execute.
  • timeout – If another client has already obtained the lock, sleep for a maximum of timeout seconds before giving up. A value of 0 means we never wait.
  • redis – The redis instance to use if the default global redis connection is not desired.


exception retools.lock.LockTimeout[source]

Raised in the event a timeout occurs while waiting for a lock