TExcelTAD
Home › Redis › Redis Distributed Locks

Redis Distributed Locks

Sometimes only one process in your whole system may do something at a time: run the nightly billing job, rebuild a cache entry, charge a customer's card for a given order. Inside one program you would use a mutex. Across many servers you need a distributed lock, and Redis's SET ... NX makes a simple and popular one.

Acquiring a lock

The lock is a key. SET key token NX PX ms creates it only if nobody holds it (NX) and with an expiry (PX, milliseconds) so that a crashed holder cannot block everyone forever. The value is a random token unique to this holder:

redis · try it yourself
SET lock:billing:2026-10 "token-7f3a" NX PX 30000
SET lock:billing:2026-10 "token-c91e" NX PX 30000
GET lock:billing:2026-10
redis> SET lock:billing:2026-10 "token-7f3a" NX PX 30000
OK
redis> SET lock:billing:2026-10 "token-c91e" NX PX 30000
(nil)
redis> GET lock:billing:2026-10
"token-7f3a"

The first process got OK and holds the lock; the second got (nil) and must wait, retry later or give up.

Releasing safely

The obvious release, DEL lock:..., has a nasty bug. Suppose process A's work takes longer than the lock's 30 seconds: the key expires, process B acquires the lock, and then A finishes and deletes B's lock. Now a third process can enter too.

The fix: delete the key only if it still holds your token. Checking and deleting must be atomic, so it is done in Lua:

redis · try it yourself
SET lock:report "token-A" NX PX 30000
EVAL "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end" 1 lock:report token-B
GET lock:report
EVAL "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end" 1 lock:report token-A
EXISTS lock:report
redis> SET lock:report "token-A" NX PX 30000
OK
redis> EVAL "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end" 1 lock:report token-B
(integer) 0
redis> GET lock:report
"token-A"
redis> EVAL "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end" 1 lock:report token-A
(integer) 1
redis> EXISTS lock:report
(integer) 0

Process B's attempt to release A's lock returned 0 and left it alone; A's own release returned 1.

Redis 8.4 added a native compare-and-delete, DELEX key IFEQ value, which does the same without a script:

redis · try it yourself
SET lock:report "token-A" NX PX 30000
DELEX lock:report IFEQ token-B
DELEX lock:report IFEQ token-A
EXISTS lock:report
redis> SET lock:report "token-A" NX PX 30000
OK
redis> DELEX lock:report IFEQ token-B
(integer) 0
redis> DELEX lock:report IFEQ token-A
(integer) 1
redis> EXISTS lock:report
(integer) 0

Note: DELEX only exists on Redis 8.4 and newer (and not on forks such as Valkey). The Lua version works on every server.

Extending a lock

For long jobs, the holder renews the lock before it expires, again only if it still owns it:

redis · try it yourself
SET lock:import "token-A" NX PX 10000
EVAL "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('PEXPIRE', KEYS[1], ARGV[2]) else return 0 end" 1 lock:import token-A 30000
TTL lock:import
EVAL "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('PEXPIRE', KEYS[1], ARGV[2]) else return 0 end" 1 lock:import token-Z 30000
redis> SET lock:import "token-A" NX PX 10000
OK
redis> EVAL "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('PEXPIRE', KEYS[1], ARGV[2]) else return 0 end" 1 lock:import token-A 30000
(integer) 1
redis> TTL lock:import
(integer) 30
redis> EVAL "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('PEXPIRE', KEYS[1], ARGV[2]) else return 0 end" 1 lock:import token-Z 30000
(integer) 0

Simulating the expired-lock bug

This Python model shows two processes and a lock with a 10-second expiry. Process A runs for 15 seconds. With the naive DEL release, A deletes B's lock and process C gets in while B is still working; with the token check, it does not:

python · try it yourself
def simulate(safe_release):
    lock = {"holder": None, "expires": 0}
    log = []

    def acquire(name, now, ttl=10):
        if lock["holder"] is None or lock["expires"] <= now:
            lock.update(holder=name, expires=now + ttl)
            log.append(f"t={now:>2} {name} acquired")
            return True
        log.append(f"t={now:>2} {name} blocked (held by {lock['holder']})")
        return False

    def release(name, now):
        if safe_release and lock["holder"] != name:
            log.append(f"t={now:>2} {name} release ignored (not the owner)")
            return
        log.append(f"t={now:>2} {name} released the lock of {lock['holder']}")
        lock.update(holder=None, expires=0)

    acquire("A", 0)          # A works from t=0 to t=15
    acquire("B", 5)          # still held by A
    acquire("B", 11)         # A's lock expired at t=10
    release("A", 15)         # A finishes
    acquire("C", 16)         # does C get in while B is still working?
    return log

for safe in (False, True):
    print("safe release" if safe else "naive DEL")
    for line in simulate(safe):
        print("  " + line)
naive DEL
  t= 0 A acquired
  t= 5 B blocked (held by A)
  t=11 B acquired
  t=15 A released the lock of B
  t=16 C acquired
safe release
  t= 0 A acquired
  t= 5 B blocked (held by A)
  t=11 B acquired
  t=15 A release ignored (not the owner)
  t=16 C blocked (held by B)

Choosing the expiry and handling failure

Concern Advice
Expiry too short the lock may expire while the job still runs: renew it, or make the job check it still owns the lock
Expiry too long after a crash, everyone waits that long
Retrying wait a random short time between attempts to avoid all clients retrying in sync
Correctness under failover replication is asynchronous: if the primary dies right after granting a lock, a promoted replica may not know about it

For locks where a duplicate would only waste work (a cache rebuild, a periodic report) a single-instance SET NX lock is perfect. When a duplicate would cause real harm (charging a card twice), combine the lock with idempotency in the system you write to, for example a unique constraint on the order ID or a fencing token: an INCR-generated number that grows with every lock grant, which the storage layer uses to reject writes from an older holder.

redis · try it yourself
INCR fence:billing
SET lock:billing "token-A" NX PX 30000
INCR fence:billing
redis> INCR fence:billing
(integer) 1
redis> SET lock:billing "token-A" NX PX 30000
OK
redis> INCR fence:billing
(integer) 2

Each new lock holder takes the next fencing number (1, then 2, ...). If an old holder with number 1 wakes up and tries to write after holder 2 has, the database refuses it.

Libraries such as Redlock implementations (redlock-py, node-redlock, Redisson for Java) package these patterns, including a multi-instance variant.

Test yourself

Why is SET lock 1 NX without an expiry a bad lock?

  1. NX is not atomic
  2. If the holder crashes, the lock is never released
  3. It is too slow
  4. Other clients can overwrite it

Why store a random token as the lock value?

  1. To make the key longer
  2. So that a process only releases a lock it still owns
  3. Redis requires a value
  4. To encrypt the lock

Why must the 'check token, then delete' step be a Lua script?

  1. DEL does not work outside scripts
  2. GET followed by DEL from the client is not atomic: the lock could change in between
  3. Scripts are faster to type
  4. It is required by NX