StackExchange.Redis – LockTake / LockRelease Usage

There are 3 parts to a lock:

  • the key (the unique name of the lock in the database)
  • the value (a caller-defined token which can be used both to indicate who “owns” the lock, and to check that releasing and extending the lock is being done correctly)
  • the duration (a lock intentionally is a finite duration thing)

If no other value comes to mind, a guid might make a suitable “value”. We tend to use the machine-name (or a munged version of the machine name if multiple processes could be competing on the same machine).

Also, note that taking a lock is speculative, not blocking. It is entirely possible that you fail to obtain the lock, and hence you may need to test for this and perhaps add some retry logic.

A typical example might be:

RedisValue token = Environment.MachineName;
if(db.LockTake(key, token, duration)) {
    try {
        // you have the lock do work
    } finally {
        db.LockRelease(key, token);
    }
}

Note that if the work is lengthy (a loop, in particular), you may want to add some occasional LockExtend calls in the middle – again remembering to check for success (in case it timed out).

Note also that all individual redis commands are atomic, so you don’t need to worry about two discreet operations competing. For more complexing multi-operation units, transactions and scripting are options.

Leave a Comment