🔴 Redis Intermediate

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.