Distributed locks and their limits

A pause longer than the lock: two holders, a deleted lock, a stale write as the final state — fencing tokens refusing it, the Redlock debate, and designs that need no lock.

13 min read⚡ Redis and Caching

Several instances of a service want to make sure only one of them sends invoice 1041. A lock in Java only coordinates threads in one process, so the natural reach is for a lock in Redis: a key that one instance sets and the others find already taken.

It works most of the time, and the way it fails is instructive — because the failure is not a bug in Redis. It is a property of any lock that expires, and it means a Redis lock can reduce duplicate work but cannot, on its own, guarantee that only one process acts.

Every timeline below was recorded against Redis 7.4 with three Java workers in another container.

The lock with an expiry

Acquiring is one atomic command: set the key only if it does not exist, with an expiry so that a crashed holder does not hold it forever:

plaintext
SET lock:invoice-1041 <owner> NX PX 1000

NX makes it succeed for exactly one caller; PX 1000 makes it disappear after a second. The expiry is not optional — without it, an instance that crashes while holding the lock blocks everyone until someone deletes the key by hand. And the expiry is the source of every problem that follows.

Losing the lock without knowing

Worker A acquires the lock and starts work. The work — or a garbage-collection pause, a slow disk, a network hiccup — takes 1.5 seconds, longer than the lock's one-second expiry. The lock expires while A is still inside its "critical section". Worker B acquires it. Worker C arrives later. Each worker writes the invoice and then releases the lock with a plain DEL:

plaintext
     19 ms  worker-A  acquired the lock (1 s expiry)
   1122 ms  worker-B  acquired the lock (1 s expiry)
   1530 ms  worker-A  wrote the invoice
   1531 ms  worker-A  released the lock
   1624 ms  worker-C  acquired the lock (1 s expiry)
   1729 ms  worker-B  wrote the invoice
   1731 ms  worker-B  released the lock
   1927 ms  worker-C  wrote the invoice
   1929 ms  worker-C  tried to release: it was no longer ours, nothing deleted
  final invoice:1041 = sent by worker-C

Read it carefully, because there are two separate failures:

  1. Two holders. From 1,122 ms, A and B both believe they hold the lock. A never learned it had expired — nothing tells a process that its lock is gone.
  2. Deleting someone else's lock. At 1,531 ms, A's DEL removed B's lock. C acquired it at 1,624 ms while B was still working, and B's later DEL removed C's. Three workers wrote the invoice.

The second failure has a simple fix: store a unique value when acquiring, and release only if the value is still yours — atomically, in a Lua script, since a GET followed by a DEL is itself a race:

plaintext
if redis.call('GET', KEYS[1]) == ARGV[1] then
  return redis.call('DEL', KEYS[1])
else
  return 0
end

With that release, the same timings:

plaintext
     22 ms  worker-A  acquired the lock (1 s expiry)
   1132 ms  worker-B  acquired the lock (1 s expiry)
   1534 ms  worker-A  wrote the invoice
   1540 ms  worker-A  tried to release: it was no longer ours, nothing deleted
   1734 ms  worker-B  wrote the invoice
   1736 ms  worker-B  released the lock
   1780 ms  worker-C  acquired the lock (1 s expiry)
   2081 ms  worker-C  wrote the invoice
   2082 ms  worker-C  released the lock

A no longer deletes B's lock, and C correctly waits until B has finished. But A still wrote the invoice at 1,534 ms, while B held the lock. The first failure — a holder that does not know its lock expired — is untouched, because nothing in the lock can reach into a paused process.

The stale write

That first failure does damage in a specific way. Worker A acquires the lock and pauses; B acquires it after the expiry, does its work quickly, writes, and releases; then A wakes up and writes what it computed before the pause:

plaintext
     29 ms  worker-A  acquired the lock (1 s expiry)
   1141 ms  worker-B  acquired the lock (1 s expiry)
   1347 ms  worker-B  wrote the invoice
   1349 ms  worker-B  released the lock
   1540 ms  worker-A  wrote the invoice
   1542 ms  worker-A  tried to release: it was no longer ours, nothing deleted
  final invoice:1041 = sent by worker-A

The final state is A's stale result, overwriting B's newer one, and every worker followed the locking protocol correctly. A longer expiry makes this rarer, not impossible: pauses have no upper bound. Stop-the-world GC, a VM migrated between hosts, a process suspended by the operating system, a network partition that delays a request for seconds — any of them outlasts any expiry you are willing to set.

Fencing tokens

The fix, described by Martin Kleppmann, moves the check to the only place that can enforce it: the resource being written. Each time the lock is granted, the holder also gets a fencing token — a number that only ever increases, here from INCR lock:tokens. Every write to the resource carries the token, and the resource refuses any token lower than the highest it has already accepted:

plaintext
local last = tonumber(redis.call('GET', KEYS[2]) or '0')
if tonumber(ARGV[1]) < last then return 0 end
redis.call('SET', KEYS[2], ARGV[1])
redis.call('SET', KEYS[1], ARGV[2])
return 1

The same stale-write timing, with tokens:

plaintext
     41 ms  worker-A  acquired the lock (1 s expiry), token 1
   1153 ms  worker-B  acquired the lock (1 s expiry), token 2
   1360 ms  worker-B  wrote the invoice
   1362 ms  worker-B  released the lock
   1562 ms  worker-A  write REFUSED: token 1 is older than one already used
   1563 ms  worker-A  tried to release: it was no longer ours, nothing deleted
  final invoice:1041 = sent by worker-B

A woke up, tried to write with token 1, and was refused — the resource had already accepted token 2. The final state is B's.

Two limits on what fencing does:

  • It orders writes; it does not prevent overlap. In a first run with tokens, using the three-worker timings from earlier (not shown above), A — holding token 1 — still wrote at a moment when B held token 2, because B had not written yet, so the resource had not seen token 2. What fencing guarantees is that an older holder can never overwrite a newer holder's write.
  • The resource has to cooperate. A database can check the token in a WHERE clause; a Redis key can check it in a script; an email provider or a payment gateway cannot check anything. For those, fencing is unavailable, and the protection has to come from idempotency — the same key sent twice has one effect.

Redlock and its critics

A single Redis instance is a single point of failure: if it fails over to a replica that had not yet received the lock key, a second client can acquire the lock. Redlock, proposed by Redis's creator, acquires the lock on a majority of independent Redis nodes to survive that.

Martin Kleppmann's critique, How to do distributed locking, argued that Redlock depends on bounded pauses, bounded network delay and clocks that do not jump — exactly the assumptions the timelines above break — and that it provides no fencing token. Salvatore Sanfilippo published a response defending its assumptions for practical systems. The debate is worth reading in full; the practical conclusion most engineers draw from it is:

  • For efficiency — avoiding duplicate work that is harmless if it occasionally happens twice, such as rebuilding a cache entry — a single-instance Redis lock is fine.
  • For correctness — where two holders would corrupt data or double-charge a customer — a lock that expires is not enough on its own, whatever its algorithm. Use a coordination service that provides fencing tokens (ZooKeeper, etcd), or better, design the write so that the lock is not what guarantees correctness.

The design that does not need the lock

Most "we need a distributed lock" problems are really "we need this change to happen once", and a database can guarantee that directly:

  • A conditional update: UPDATE invoices SET status = 'SENT', sent_by = ? WHERE id = 1041 AND status = 'PENDING'. Exactly one instance gets 1 row affected; the others get zero and stop. No lock, no expiry, no pause problem.
  • A unique constraint on the thing that must happen once — an invoice_sent row keyed by invoice id. The second insert fails.
  • An idempotency key passed to the external system, so a duplicate call has no second effect.
  • Partitioning the work so that each item has one owner — a Kafka partition consumed by one member of a group, or a job claimed by a conditional update — and no two instances ever compete for it.

A Redis lock is then what it is good at: a cheap way to make duplicate work rare. The guarantee lives in the data.

Under the hood: what Redlock actually checks, and where the disagreement really is

The algorithm, precisely. Redlock runs against N independent Redis instances (Antirez's original description uses 5). A client trying to acquire the lock: (1) records the current time; (2) tries to acquire the same key, with the same random value, on each of the N instances in turn, using a small connect/response timeout so one dead instance does not stall the whole attempt; (3) computes how much time elapsed doing that; (4) considers the lock acquired only if it got the lock on a majority of instances (N/2 + 1) and the elapsed time is meaningfully less than the lock's validity time — the remaining time being what the client is now allowed to hold the lock for. If it failed to reach a majority, it releases the lock on every instance it did acquire, even the successful ones, rather than leaving a partial lock standing.

What that buys over one instance, precisely. A single Redis node that fails over to a replica which had not yet replicated the lock key lets a second client acquire the same lock — a majority quorum across independent nodes means an attacker would need a majority of nodes to be simultaneously wrong for that to happen, which is a materially stronger (though not absolute) guarantee than trusting replication timing on one node.

Where Kleppmann's critique actually lands. It is not that the quorum logic is wrong arithmetic — it is that step (4)'s "elapsed time is meaningfully less than validity time" check assumes the client's own clock and process are not doing anything strange between acquiring the lock and finishing its work: no long GC pause, no VM live-migration freeze, no thread suspended by the OS scheduler, no NTP step that jumps the clock. Every one of those breaks the assumption silently — the client believes it still holds a valid lock, uses stale time to reason about that, and none of the timelines earlier in this lesson depend on Redlock's quorum being wrong; they depend on exactly this same class of pause, which Redlock does nothing to prevent because no lock can observe a paused holder. Kleppmann's second point is separate and, by Sanfilippo's own acknowledgment, correct as stated: Redlock as originally specified does not hand out a fencing token, so even a "correctly" held Redlock cannot stop the stale-write failure mode demonstrated above — only a resource-side check (fencing, a conditional update) can.

Why this is a real, unresolved disagreement and not a solved question. Sanfilippo's response argued Redlock's assumptions (bounded clock drift, bounded delay) are reasonable for most real deployments, and that a system without any synchrony assumptions is not practically buildable. Kleppmann's position is that a lock used for correctness should not rely on assumptions that can be silently violated in a way the algorithm can't detect — and that if you need real safety, you need a system (like a consensus store with fencing) built for it. Both are talking about a real trade-off between practicality and provable safety; treat any claim you read that flatly declares one side "right" with suspicion — the original exchange between the two, freely available online, is worth reading directly rather than through a summary, including this one.

Try it yourself

Trace where a pause breaks each version

Using the three-worker stale-write timeline in "The stale write" above (worker A pauses for 1.5 s after acquiring a 1 s lock; worker B acquires it after expiry, finishes, and releases it; A then wakes up and writes), work through what would change, if anything, in the final outcome if the lock had been acquired through a 5-node Redlock quorum instead of a single Redis instance — and separately, what would change if fencing tokens were added on top of the single-instance lock. Which one actually prevents A's stale write from landing?

Redlock changes how the lock is acquired, not what a pause does to the holder

Swapping a single Redis instance for a 5-node Redlock quorum changes how robustly the lock is acquired — it defends against one node's replication lag letting two clients believe they hold the lock — but it says nothing about what happens to a client that is paused after it has already, correctly, acquired the lock. Worker A's 1.5 s pause happens after A holds the lock validly, however it was acquired; Redlock has no mechanism to reach into a paused process and tell it its time is up, because nothing can. So the outcome is unchanged: A wakes up believing it still holds a valid lock (its local expiry check, if it even makes one, is based on the same clock that a GC pause does not stop) and writes anyway. Adding fencing tokens on top of the single-instance lock, by contrast, does prevent the stale write — not by stopping A from waking up and trying to write, but by having the resource itself refuse A's write because it carries an older token than one already accepted. This is exactly the lesson's point: Redlock and fencing solve different problems (safer acquisition across nodes vs. safe writes despite a stale holder), and only the second one actually prevents the failure in this scenario.

Misconceptions

  • "Redlock gives the same guarantee as a consensus algorithm like Raft or Paxos." It does not: Redlock is a quorum lock with no leader election, no log replication and no fencing token in its original form — it reduces (but, per Kleppmann's critique, does not eliminate) the chance of two clients believing they hold the same lock. A system that genuinely needs consensus-level safety is reaching for the wrong tool if it reaches for Redlock instead of an actual consensus store.
  • "A distributed lock, correctly implemented, guarantees mutual exclusion." No expiring lock can guarantee that, on its own, against an unbounded pause — this is the entire subject of the stale-write timeline above, and it is true of Redlock exactly as it is true of a single instance. Mutual exclusion under pauses needs the resource itself to check something (a fencing token, a conditional update), not a better lock.

Sources

  • Salvatore Sanfilippo (Antirez), "Distributed locks with Redis" (the Redlock algorithm specification) and "Is Redlock safe?" (his response to the critique below) — redis.io / antirez.com.
  • Martin Kleppmann, "How to do distributed locking" — the critique of Redlock's clock and pause assumptions, and the case for fencing tokens.
Progress is saved on this device and to your account when signed in.