Learn Labs
Application Patterns

Distributed Locks

SET NX PX, safe release, fencing tokens, and the Redlock debate

A distributed lock makes sure only one process across many machines does something at a time: run the nightly report, process a given order, refresh an expensive cache key. Redis locks are simple to write and famously easy to get wrong.

Acquire

SET lock:report <random-token> NX PX 30000
  • NX: only succeeds if the key doesn't exist, so exactly one caller gets it.
  • PX 30000: the lock expires after 30 seconds, so a holder that crashes doesn't block everyone forever.
  • A random token unique to this holder, used to release it safely.

Release: only your own lock

The naive release is DEL lock:report. Here's what goes wrong, from labs/lock.py:

docker compose -f compose_prod.yaml run --rm labs python lock.py

naive release (DEL):
  A acquired                    # lock TTL 1s, but A's work takes 1.5s
  B acquired                    # A's lock expired at 1s; B takes it
  A DEL'd the lock              # A finishes and deletes... B's lock
  C acquired while B still working  <-- two holders!

token-checked release (Lua):
  A acquired
  B acquired
  A released (lock was no longer ours)
  C blocked (correct: B holds it)
  B released (ok)

A's lock expired while it was still working, B took it, and A's DEL removed B's lock. Then C walked in. The fix is to delete only if the key still holds your token, atomically, which needs Lua:

worker ARedisworker Bworker CSET lock tokA NX PX 1000SET lock tokB NX PX 3000A's lock expired at 1 sDEL lock (B’s!)SET lock tokC NXB and C both hold itfix: delete only if value == tokA
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1])
end
return 0

(A GET then DEL from the client isn't safe: the lock could change hands between the two commands.)

The deeper problem: time

The token fixes the release. It doesn't fix the root cause in that demo: A kept working after its lock expired. A process can't reliably know its lock is still valid, because between checking and acting it can be paused by a GC pause, a VM migration, a slow disk, or a network partition, for longer than the TTL.

Mitigations:

  • Pick a TTL much longer than the work, and extend it while working (a watchdog that re-sets the TTL if the token still matches; Redisson does this).
  • Check the lock before each irreversible step, which narrows the window but can't close it.

Fencing tokens

The real fix is on the side of the resource being protected. Every time the lock is acquired, issue a monotonically increasing number:

token = INCR lock:report:fence     # 33 for A, 34 for B
# every write to the protected resource carries the token:
UPDATE reports SET ... WHERE id = 1 AND last_fence < 34   # storage rejects A's stale 33

If A wakes up after its lock expired and tries to write with token 33, the storage system has already seen 34 and rejects it. This requires the resource to check tokens. Many don't, which is exactly why "a Redis lock guarantees mutual exclusion" is not a safe assumption.

Redlock

A single Redis lock fails if that Redis fails: a failover to a replica that hadn't received the SET yet (replication is async) hands the lock to a second client. Redlock acquires the lock on a majority of N independent Redis primaries (typically 5), within a time budget.

It's controversial. Martin Kleppmann's critique (also in DDIA chapter 9) argues that Redlock depends on bounded clock drift and bounded process pauses, assumptions that real systems violate, and that it doesn't provide fencing tokens, so it isn't safe for correctness. Salvatore Sanfilippo (Redis's creator) argued the assumptions are reasonable in practice.

Checklist

  1. SET key token NX PX ttl. Never SETNX followed by EXPIRE.
  2. Release with a token-checking Lua script.
  3. TTL comfortably longer than the work; extend it for long jobs.
  4. Retry acquisition with backoff and jitter, not a tight loop.
  5. Know whether it's an efficiency lock or a correctness lock. If it's correctness, add fencing or use something else.

Lab

  1. Run lock.py and trace both scenarios.
  2. Add a fencing counter to lock.py: INCR lock:report:fence on each acquire, and a fake "storage" that rejects writes with an older token. Make A's late write get rejected.
  3. Add a watchdog thread that extends the lock every TTL/3 while work continues, and confirm A no longer loses its lock.

On this page