What Is Distributed Locking? Managing Resources Across Servers
Multiple servers accessing the same resource simultaneously? Two instances decrementing stock at once? Distributed locking provides safe, serialized access in distributed environments.
The Problem
Single-server mutexes don't work across multiple instances. Without distributed locks, concurrent operations cause data inconsistencies.
Redis Distributed Lock
// Acquire: SET key value NX PX ttl
const acquired = await redis.set(`lock:${resource}`, token, 'NX', 'PX', 10000);
// Release: Lua script (atomic, only owner can release)
const script = `
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
end
`;
Redlock Algorithm
Uses 5+ independent Redis instances. Lock acquired when majority (3/5) agree. Survives single instance failure.
Fencing Tokens
Prevent stale lock holders from executing operations after TTL expires using monotonically increasing tokens.
Tools
| Tool | Mechanism | Best For | |------|-----------|----------| | Redis | SET NX PX | Fast, simple | | Redlock | Multi-Redis | More reliable | | ZooKeeper | Ephemeral nodes | Strong guarantees | | etcd | Leases | Kubernetes-native |
Best Practices
- TTL required — Prevent deadlocks
- Atomic release — Only the owner can release
- Retry with backoff — Exponential backoff on failure
- Fencing tokens — Block stale operations
- Minimize lock duration
- Monitor — Lock wait times and timeouts
Conclusion
Distributed locking prevents resource conflicts in distributed systems. Use Redis for simple cases, Redlock or ZooKeeper for critical systems. Always use TTL and fencing tokens.
Learn distributed locking on LabLudus.