Implementing Distributed Locks

1. Setting Lock with SETNX

CommandReturns
SETNX lock:res token1 acquired, 0 held LEGACY

2. Using SET with NX and EX Options

CommandDescription
SET lock:res token NX PX 30000Atomic acquire + auto-expiry (preferred)

3. Implementing Lock Expiration

PropertyRecommendation
TTLSlightly > max work duration
RenewalBackground watchdog extends TTL

4. Releasing Locks Safely (Lua Script)

Example: Token-checked release

EVAL "if redis.call('GET', KEYS[1]) == ARGV[1] then \
  return redis.call('DEL', KEYS[1]) else return 0 end" \
  1 lock:res <token>
Warning: Never DEL directly — you may delete a lock held by someone else after your TTL expired.

5. Handling Lock Timeouts

ScenarioMitigation
Work exceeded TTLRenew with Lua CAS; if renewal fails, abort and rollback

6. Implementing Redlock Algorithm

StepDetail
1Get current time (ms)
2Try SET NX PX on N independent masters (small timeout)
3Lock valid if acquired on majority AND elapsed < TTL
4Effective TTL = original − elapsed
5On failure release on ALL nodes

7. Preventing Deadlocks

TechniqueDetail
Always set TTLAuto-release on crash
Unique tokenUUID per acquisition
Lock orderingAcquire multi-locks in fixed order

8. Using WATCH for Optimistic Locking

PatternUse
WATCH + MULTI/EXECNo explicit lock; retry on contention
Best forLow contention

9. Handling Lock Renewal

Example: Renewal Lua

EVAL "if redis.call('GET', KEYS[1]) == ARGV[1] then \
  return redis.call('PEXPIRE', KEYS[1], ARGV[2]) else return 0 end" \
  1 lock:res <token> 30000

10. Understanding Lock Granularity

GranularityTradeoff
Coarse (one global lock)Simple, low concurrency
Fine (per-resource)High concurrency, more keys