<antirez>
8 hours ago
- Distributed locks require mutual exclusion, deadlock freedom, and fault tolerance.
- A single Redis instance with replication has a safety violation due to asynchronous replication, causing potential lock conflicts during failover.
- For a single instance, a safe locking method uses SET with NX, PX, and a unique random value, releasing via a Lua script to avoid removing others' locks.
- The distributed algorithm uses N independent Redis masters (e.g., 5), where a client acquires locks on a majority (N/2+1) within a validity time, releasing unused locks promptly.
- Safety relies on ensuring a majority of keys exist simultaneously; liveness depends on auto-release of keys, client cooperation, and retries with random delays.
- Performance can be maintained by avoiding fsync, accepting a small risk of safety violation during crash-recovery, or enabling fsync=always for full safety but lower performance.
- Crash recovery without persistence can still be safe if restarted servers are kept unavailable until all previous locks expire.
- Clients can extend locks via scripts if operations take too long, preventing premature release.