Intermediate LevelSystem Design & Architecture
How does the Redlock Algorithm acquire distributed locks across multiple Redis instances?
β Interview Prompt: Explain Distributed Locks, Redlock Algorithm, multi-master Redis quorums, drift factor, lock TTLs, and fencing tokens.
The Redlock Algorithm acquires distributed locks across $N$ (typically 5) independent, un-replicated Redis master nodes:
How Redlock Works:
1
Captures current timestamp $T_1$.
2
Attempts to acquire the lock sequentially on all 5 Redis instances with a short timeout.
3
If the client acquires locks from a majority quorum ($\ge 3$ instances) and total elapsed time $T_2 - T_1 < \text{Lock TTL}$, the lock is granted!
β’
Fencing Tokens: Pass monotonically increasing fencing tokens to storage resources to reject stale lock holders.
Code Implementation Example
typescript
import Redlock from 'redlock';
import { redis1, redis2, redis3 } from './redis-nodes';
const redlock = new Redlock([redis1, redis2, redis3], {
driftFactor: 0.01,
retryCount: 3
});
// Acquire lock on resource across Redis instances
const lock = await redlock.acquire(['locks:account:101'], 5000);π‘Acquiring a multi-node distributed lock using Redlock.
π― Interview Key Takeaway
Use Redlock with fencing tokens to coordinate distributed locks across independent Redis master nodes safely.
#System Design#Redlock#Distributed Locks#Redis#Intermediate
Back to all System Design & Architecture Questionsβ