Distributed locks are harder than they look! Let's build this properly:
THE PROBLEM:
10 servers processing jobs from a queue. Job #42 might be grabbed by 2 servers simultaneously. Need coordination: Only one server processes this job.
NAIVE APPROACH (FAILS):
if not job.locked then job.locked equals true, processJob(job).
Both servers see unlocked at the same time, double processing!
THE SOLUTION: REDIS LOCK (Redis Distributed Lock)
Try to acquire lock using SET NX EX (only set if not exists, with expiration). Return unique identifier if acquired.
WHY THIS WORKS:
1. Atomic: SET NX is atomic in Redis
2. Safe: Auto-expire prevents deadlocks
3. Unique: Each lock holder gets unique token
RELEASING THE LOCK:
Only release if we own it (use Lua script for atomicity). Check if the lock value matches our token, if yes then delete.
Using it:
acquireLock(job-42, 30). If acquired, try processing, finally release the lock.
Want to implement the full fault-tolerant version with multiple Redis nodes?