Back to results for “Distributed Locks with Redis”
Redis › Distributed Locks with Redis

Why is it important to release a distributed lock using a script that verifies you are actually the current lock owner, rather than a simple DELETE command?

Intermediate

Answer

If you simply delete the lock key without checking first, you risk accidentally releasing a lock that was actually acquired by a different client after your own lock expired, so you should use a Lua script that checks the lock's value matches your unique identifier before deleting it, ensuring you only ever release a lock you actually still own.
if redis.call('get', KEYS[1]) == ARGV[1] then
  return redis.call('del', KEYS[1])
else
  return 0
end
Real-world example A payment processing service uses a Lua script to safely release its distributed lock, preventing a rare but serious bug where a slow process could have accidentally deleted a lock that had already been acquired by a different, newer process.

Common follow-ups: Why must this check and delete operation happen atomically in a single script?;What happens if the lock has already expired by the time you try to release it?