Distributed Locks
Ensuring only one process accesses a resource across multiple nodes.
1The Bathroom Key Analogy
A distributed lock ensures mutual exclusion across multiple nodes. Only one process can hold the lock at a time. Critical for preventing race conditions.
2Use Cases
Cron Jobs
Only one instance should run scheduled task
Rate Limiting
Coordinate rate limits across instances
Leader Election
Only one node is the leader
Cache Updates
Prevent thundering herd on cache miss
Inventory
Prevent overselling the last item
Payment Processing
Process each payment exactly once
3Redis Lock Implementation
Simple Redis Lock with SETNX
SET lock_key unique_value NX PX 30000NX = only if not exists, PX = expire in 30 seconds
// Critical sectionProcess that requires exclusive access
DEL lock_key (if value matches)Only delete if you own the lock (check value first)
Warning: Check Before Delete
Always verify the lock value before deleting. Otherwise, you might delete someone else's lock if yours expired.
4Real-World Dry Run
Scenario: Two workers processing same job
5Redlock Algorithm
Redlock by Redis author: acquire lock on majority of Redis instances (N/2+1). Safer for distributed deployments but more complex.
Steps
- 1. Get current time
- 2. Try to acquire lock on all N instances
- 3. Calculate elapsed time
- 4. Lock valid if majority acquired + time left
Requirements
- • Odd number of Redis instances (3, 5, 7)
- • Independent failure domains
- • Clock drift consideration
- • Controversial: some experts disagree
6Key Takeaways
?Quiz
1. Worker A's lock expires while still processing. Worker B acquires. A finishes and deletes. What happens?
2. Redlock requires lock on how many Redis instances for N=5?