SET lock:order:42 9f1c2e7a NX PX 30000
-- release.lua
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
else
return 0
end
Take the lock with SET lock:<resource> <token> NX PX 30000.
NXsets the key only if it does not exist yet, so only one client wins.PXadds an expiry time in milliseconds, in the same atomic command. So if the holder crashes, the lock still expires and does not block everyone forever.- The token must be a unique random value, new for every time you take the lock.
Release the lock with a Lua script. The script deletes the key only if it still holds your token. The check and the delete must be atomic (one step). Why? With a separate GET and then DEL, your lock could expire between the two calls. Another client could take it. Then your DEL would delete their lock.
If SET returns nil, someone else holds the lock. Retry with growing waits (backoff) and a deadline, or give up. Pick a TTL that is clearly longer than the work. Remember that the lock is only advisory: it works only if every client uses it.
- Take the lock with
SET key token NX PX ttlin one command. - Use a unique random token each time you take the lock.
- Release with a Lua script that compares the token, then deletes.
- Retry with backoff when another client holds the lock.
- The TTL must be longer than the work.