Video in progress

How does the Redlock algorithm work, and which weak point did Martin Kleppmann point out? What does a fencing token give you?

Redlock tries to acquire a lock on a majority of N independent Redis instances within a time limit. The criticism: because of a GC pause, a network delay or a clock jump, the lock holder can keep working without knowing the lock has expired. A fencing token is a number that increases with every lock, and the resource rejects writes with an older number.

📖 Answer

Redlock in brief: 5 independent masters. The client sends SET lock token NX PX 10000 to all of them. If it got the lock on 3, with the time spent well under the TTL, the lock is its, and the validity time is TTL - time spent - clock drift.

Kleppmann's main argument isn't specific to Redlock; it applies to any lock with a TTL:

  1. A takes the lock.
  2. A has a 15-second stop-the-world GC pause.
  3. The lock expires, B takes it and writes to storage.
  4. A wakes up, still thinks "I hold the lock", and writes to storage, corrupting B's work.

A can't check this: another pause can happen between the check and the write. On top of that, Redlock depends on timing assumptions (clocks run at the same rate, delays are bounded), which is not a guarantee in a distributed system.

The fencing token solution: the lock service returns a monotonically increasing number with every lock it grants, and the resource rejects any number smaller than the last one it has seen.

UPDATE invoice SET status = 'PAID', fence = :token
WHERE id = :id AND fence < :token;   -- 0 rows = an old lock holder

Redis itself can't hand out such a token safely (INCR lives on one node and can go backwards on failover). ZooKeeper's zxid or etcd's revision fit this.

My decision is usually this:

  • if the lock is for efficiency (don't do the work twice, and it's harmless if it happens twice), a plain SET NX PX on a single Redis is enough, and you don't need Redlock's complexity;
  • if the lock is for correctness (money, inventory), I don't rely on the lock but on a check in the resource itself: an optimistic version in the DB, a unique constraint, or fencing. In that case the lock only reduces contention.

In his reply, Antirez defended Redlock as sufficient with a monotonic clock and a properly configured environment. In an interview, the expected answer is to know both sides and steer the discussion to "which failures can you tolerate".