Redis › Distributed Locks with Redis

How would you design a distributed lock implementation that supports safely extending the lock's expiration time if the protected operation needs more time than originally expected?

Advanced

Answer

You would implement a renewal function using a Lua script that checks the requesting client still owns the lock by matching the stored value, and if so, extends the key's expiration time atomically, allowing a long running process to periodically renew its lock while it is still actively working, without risking accidentally extending a lock it no longer actually owns.
if redis.call('get', KEYS[1]) == ARGV[1] then
  return redis.call('expire', KEYS[1], ARGV[2])
else
  return 0
end
Real-world example A long running video processing job periodically renews its distributed lock every few seconds while actively working, ensuring the lock does not expire prematurely during an unusually large video file that takes longer than the original lock duration.

Common follow-ups: How often should a long running process renew its lock to stay safe?;What happens if the renewal call itself fails due to a network issue?