Redlock Pattern
Redlock is a distributed locking algorithm designed for Redis clusters. It coordinates mutual exclusion across multiple independent Redis nodes, providing safety guarantees even when individual nodes fail. This recipe shows how to wire Redlock into a Meridian worker so concurrent jobs never trample shared state.
1.Acquire a lock across N nodes
The client attempts to acquire the same lock key on a majority of independent Redis instances (typically 5). Each acquire sets a random token with a short TTL. The lock is only valid if the client wins on at least N/2 + 1 nodes within the validity window. This quorum requirement is what makes the algorithm safe against single-node failure.
2.Compute effective validity
After acquiring the quorum, the client subtracts the elapsed wall-clock time from the requested TTL. If the remaining validity is non-positive, the lock is considered failed and must be released on every node, even the ones where the SET succeeded. This guards against the case where slow networks burn the entire lease before the worker can act.
3.Release with a token check
Release is a Lua script that only deletes the key if the stored value matches the client's token. Without this check, a client whose lease expired might accidentally delete a lock held by the next legitimate holder. The script runs atomically on each Redis instance during cleanup.
Reference implementation
import { Redlock } from 'meridian-redlock';
const redlock = new Redlock(redisNodes, {
retryCount: 3,
retryDelay: 200,
driftFactor: 0.01,
});
async function processJob(jobId: string) {
const lock = await redlock.acquire([`job:${jobId}`], 10_000);
try {
await doWork(jobId);
} finally {
await lock.release();
}
}