Back to results for “Distributed Locks with Redis”
Redis › Distributed Locks with Redis

How do you implement a basic distributed lock in Redis using the SET command with NX and EX options?

Beginner

Answer

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 it
Real-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.

Common follow-ups: Why is it important to set a unique value rather than just a fixed string like 'locked'?;What happens if the operation protected by the lock takes longer than the expiration time?