intermediateRedis — Data Structures, Persistence & Pub/Sub
How do you implement a distributed lock in Redis?
The correct way: SET lock:resource:123 unique_client_id NX EX 30. NX: set only if not exists (atomicity). EX 30: expire in 30 seconds (safety: auto-release if client dies). To release: only release if you own it (check UUID matches). Use Lua script for atomic check-and-delete: local val = redis.call('get', KEYS[1]); if val == ARGV[1] then redis.call('del', KEYS[1]); return 1 else return 0 end. Pro
This is a Pro chapter
Sign in, then upgrade to Pro or Power to unlock this and the full Databases Mastery library.
How do you implement a distributed lock in Redis?