Database / REDIS
How do you implement a distributed lock using Redis?
The basic pattern uses a single atomic command to both acquire the lock and set a safety expiration in one step, so a crashed client can never hold a lock forever:
SET lock:resource-1 "unique-client-token" NX PX 30000
NX means the key is only set if it doesn't already exist (so only one client can "win" the lock at a time), and PX 30000 gives it a 30-second auto-expiring safety net in case the client that acquired it crashes before releasing it explicitly. Releasing the lock safely requires checking that the client releasing it is the one that actually holds it — done via a small Lua script so the check-and-delete is atomic:
if redis.call("GET", KEYS[1]) == ARGV[1] then return redis.call("DEL", KEYS[1]) else return 0 end
This basic pattern is sufficient for most single-instance use cases, but it has a known weakness against a master failing over to a replica that hadn't yet received the lock write, which is what the more elaborate Redlock algorithm (acquiring the lock across a majority of independent Redis instances) is designed to address for scenarios where lock correctness genuinely can't tolerate that edge case — though Redlock's own guarantees have been debated in the distributed-systems community, and many applications find the simpler single-instance pattern an acceptable trade-off in practice.
More Related questions...
