How does distributed locking work in Redis?
Answer
A Redis distributed lock uses the atomic SET key value NX PX milliseconds command (Set if Not eXists, with expiry). If it returns OK, the caller acquired the lock; if nil, the lock is held by someone else. The value should be a unique random token (UUID) per lock holder, so only the holder can release it. To release, a Lua script atomically checks that the key's value matches the caller's token before deleting — preventing a process from releasing another's lock. The expiry is a safety net: if the lock holder crashes, the lock auto-expires and prevents deadlock. Redlock is Redis's algorithm for distributed locking across multiple independent Redis nodes (typically 5), providing stronger guarantees when no single Redis instance should be a single point of failure. Libraries like Redisson (Java) and node-redlock implement this.
Previous
How do you implement rate limiting in Redis?
Next
What is the cache-aside pattern vs write-through caching?
More Redis Questions
View all →- Intermediate What is Redis Cluster and how does it shard data?
- Intermediate What is the difference between Redis Sentinel and Redis Cluster?
- Intermediate How do MULTI and EXEC work in Redis transactions?
- Intermediate What is WATCH and optimistic locking in Redis?
- Intermediate What is Lua scripting in Redis and when should you use it?