How do you implement a distributed lock with Redis?
A common implementation is SET key value NX PX ttl. NX sets the key only if it does not exist, and PX gives the lock an expiry so a crashed holder cannot deadlock the system. The value should be a unique token so only the owner releases the lock.
token = str(uuid.uuid4())
if redis.set("lock:order:42", token, nx=True, px=10000):
try:
process_order(42)
finally:
redis.eval(
"if redis.call('get', KEYS[1]) == ARGV[1] then "
"return redis.call('del', KEYS[1]) else return 0 end",
1, "lock:order:42", token)
The Lua script makes check-and-delete atomic, preventing one client from deleting another's lock. For failover safety use Redlock across independent nodes, but note it is contested and cannot give strict fencing guarantees. Long tasks should renew the TTL and pass fencing tokens downstream.