Scrivio Interview library
InternalsIntermediate7 min read · updated 13 November 2026

Redlock is the algorithm proposed for Redis locks that must survive the failure of one Redis node, using several independent Redis primaries instead of one primary with replicas.

Describe the Redlock algorithm step by step, including how lock validity is calculated, and explain the assumptions it depends on.

Redlock uses N independent Redis primaries, usually five. The client records the time, tries SET key <random value> NX PX <ttl> on each node with a short timeout, and holds the lock only if a majority succeeded and the time spent is less than the TTL; the remaining validity is the TTL minus the elapsed time minus an allowance for clock drift. If it fails, it releases on every node with a compare-and-delete script and retries after a random delay. It assumes bounded clock drift and pauses and nodes that do not forget locks after a restart, and like any lease it still needs fencing or idempotency for correctness.

Why this question is asked

A lock on a single Redis primary is only as available as that primary, and replicas do not help because replication is asynchronous. Redlock was proposed to tolerate the loss of some nodes, and it is also the subject of a well-known debate about what distributed locks can promise. Interviewers ask about it to see whether we can describe the algorithm precisely and, more importantly, state the assumptions under which it is safe. In this answer, we will see why a single primary with replicas is not enough, walk through acquisition step by step, calculate the validity time, cover release and retry, and then examine the assumptions and what they mean in practice.

1Why One Primary With Replicas Is Not Enough

The single-node lock is SET lock:job <random value> NX PX 30000: create the key only if it does not exist, with a 30-second expiry, and store a random value so that only the owner can release it. To survive the primary failing, it is tempting to add a replica with failover. But Redis replicates asynchronously: the primary acknowledges the SET before the replica has it. If the primary crashes in that gap and the replica is promoted, the lock is gone and a second client can acquire it. Two clients now hold the same lock.

Redlock avoids replication altogether. It writes the lock independently to several primaries that know nothing about each other, and counts votes.

2Acquiring the Lock Step by Step

With five independent nodes, a client does the following. First, it reads the current time in milliseconds. Second, it tries the same SET with the same random value and TTL on each node in turn, using a per-node timeout much shorter than the TTL, for example 5 to 50 milliseconds for a 10-second TTL, so that a dead node does not eat the lease. Third, it reads the time again and computes how long acquisition took.

The lock is acquired only if two conditions hold: the SET succeeded on a majority, N/2 + 1, which is 3 of 5, and the elapsed time is less than the TTL. A majority matters because two clients cannot both have three of five nodes; at least one node would have to have granted the key to both, which NX prevents while the key exists.

Java
long start = System.currentTimeMillis();
int ok = 0;
for (RedisNode n : nodes) { // 5 independent primaries
if (n.setNxPx("lock:job", token, 10_000, 50)) ok++; // SET lock:job <token> NX PX 10000, 50 ms timeout
}
long elapsed = System.currentTimeMillis() - start; // e.g. 120 ms
long drift = 10_000 / 100 + 2; // about 1% of TTL + 2 ms = 102 ms
long validity = 10_000 - elapsed - drift; // 10000 - 120 - 102 = 9778 ms
boolean held = ok >= 3 && validity > 0; // true: 3 or more nodes and time left
Step throughRedlock acquisition
  1. Record start timemilliseconds
  2. SET key token NX PX ttl on each nodeshort timeout per node
  3. Compute elapsed timenow - start
  4. Majority (3 of 5) and elapsed < TTL?
    YesHold the lock for TTL - elapsed - driftNoRelease on all nodes
  5. Retry after a random delayavoid clients failing in lockstep

5 steps in order. Play them, or step through them one at a time.

The node interface here is illustrative pseudocode in Java form; in practice Redisson provides the multi-node lock types (check your version, as recent Redisson releases have changed how they expose Redlock). The drift allowance of about one percent of the TTL plus a couple of milliseconds follows the reference description of the algorithm.

3Validity Time: How Long We Really Hold It

The keys were set at different moments, the first one up to 'elapsed' milliseconds before the last, and all of them count down from that moment. So we do not own the lock for the full TTL. We own it for validity = TTL - elapsed - drift. In the example, 10,000 ms becomes about 9,778 ms. The work must finish within that window, or the client must stop and re-acquire; continuing after validity ends means we may no longer be the only holder.

4Releasing and Retrying

If acquisition fails, either too few nodes or too much elapsed time, the client releases on all nodes, including those where it thinks it failed, because a SET may have succeeded even though the reply timed out. Release uses a compare-and-delete script so a client only deletes a key that still holds its own random value.

SQL
-- release: delete only if the value is ours
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1]) -- 1: released
end
return 0 -- 0: not ours (expired, or taken by another client)

Then it waits a random delay before retrying. If several clients start together and each gets two of five nodes, nobody wins; random delays break the symmetry so one of them gets a majority on the next attempt. After successful work, the client releases the same way on all nodes.

5The Assumptions It Depends On

Redlock's safety rests on timing. Each node expires keys using its own clock, so the algorithm assumes clocks run at roughly the same rate, with bounded drift. A node whose clock jumps forward, for example after a bad NTP correction, expires the key early and can grant it to someone else. Operators should prevent clock steps on those nodes.

It also assumes bounded process pauses and network delays. The client checks elapsed time, then starts working; if it pauses for 20 seconds in garbage collection after that check, its lock can expire on all nodes while it still believes it holds it.

Finally, nodes must not forget locks. If a node holding our key crashes and restarts empty, it may vote for another client, turning our 3 of 5 into 2 of 5 and giving the other client 3. The fixes are persistence with fsync on every write, which is slow, or keeping a crashed node down for longer than the maximum TTL before it rejoins, so every lock it knew about has expired anyway.

Because of the pause problem in particular, Redlock, like every lease-based lock, cannot stop a paused client from acting after its lease ends. For efficiency, to avoid doing work twice, that is acceptable. For correctness, the resource must protect itself, with a fencing token it checks on every write or with idempotent operations.

6Follow-up questions

Why would using replicas instead of independent primaries break the algorithm?

Because replicas copy the primary asynchronously and can be promoted. A lock acknowledged by a primary may not have reached its replica when the primary fails; after promotion, that node no longer has our key and can grant it to someone else. With independent primaries, each vote is a separate, local fact, and the majority argument holds only if each node's answer is not silently rewritten by failover.

Is Redlock worth it compared with one Redis primary?

For efficiency locks, a single primary is usually enough: an occasional duplicate after failover is acceptable, and it is much simpler to run. For correctness, Redlock does not remove the need for fencing, so many teams use a consensus system such as etcd or ZooKeeper, or database locks, with fencing tokens instead. Redlock sits in between and costs five independent nodes.

Why use a random value per acquisition rather than the client name?

So that release only removes our own acquisition. If the lock expired and another client, or another attempt by the same client, now holds it, a value that is unique per acquisition ensures our compare-and-delete does nothing.

7Conclusion

In this answer, we walked through Redlock: N independent primaries, a timed SET NX PX with a random value on each, success only with a majority and elapsed time under the TTL, and a validity window of TTL minus elapsed time minus a drift allowance. Failed attempts release everywhere with compare-and-delete and retry after a random delay. The algorithm assumes bounded clock drift, bounded pauses and nodes that do not forget locks after a crash, and because a paused client can still act after expiry, correctness-critical work needs fencing tokens or idempotency in the resource.

What to say in the interviewAbout 90 seconds aloud

Open with

Redlock runs against N independent Redis primaries, typically five, not a primary and its replicas, because asynchronous replication can lose a lock on failover. The client records the current time, then tries SET key with a random value, NX, PX ttl on each node in turn, with a per-node timeout that's small compared with the TTL so a dead node doesn't consume the lease.

Then, if they want more

Then it measures the elapsed time. It holds the lock only if a majority, three of five, succeeded and the elapsed time is less than the TTL. The validity is the TTL minus the elapsed time minus an allowance for clock drift, roughly one percent of the TTL plus a couple of milliseconds, and the work must finish within that.

If it fails, it releases on all nodes with a compare-and-delete Lua script, even where the reply timed out, and retries after a random delay so competing clients don't keep splitting the votes.

The assumptions are what matter: clocks drift only a little and don't jump, pauses and network delays are bounded, and nodes don't forget locks on restart, so either fsync every write or keep a crashed node down longer than the maximum TTL.

And like any lease, it can't stop a paused client acting after expiry, so for correctness I'd still use fencing tokens or idempotent operations.

About this answer

Last updated
13 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Redis documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Describe the Redlock algorithm step by step, including how lock validity is calculated...": https://scrivio-interview-library.netlify.app/databases/redis-patterns/f5b9104b94/