Redis › Distributed Locks with Redis
How do you implement a basic distributed lock in Redis using the SET command with NX and EX options?
BeginnerAnswer
You use the SET command with the NX option, which only sets the value if the key does not already exist, combined with the EX option to set an automatic expiration time, ensuring the lock is both exclusively acquired by only one client and automatically released after a timeout even if that client crashes before releasing it manually.
SET mylock 'unique_value_123' NX EX 30
-- If this returns OK, you have acquired the lock
-- If it returns nil, someone else already holds itReal-world example A batch processing job attempts to acquire a lock before starting its work, and if the lock already exists because another instance is currently running, it simply skips its turn and tries again during its next scheduled run.