Skip to main content

Preview — Pro guide

You are seeing a portion of this guide. Sign in and upgrade to unlock the full article, quizzes, and interview answers.

Distributed Locks: Redlock, ZooKeeper, Fencing Tokens & Exactly-Once Guarantees

Distributed locks are the mechanism behind inventory reservations, payment deduplication, and leader election. Master Redis SET NX EX, the Redlock algorithm and its controversy, ZooKeeper ephemeral znodes, fencing tokens for safe expiry, and when distributed locks are the wrong tool entirely.

35 min read 2 sections 1 interview questions
Distributed LockRedlockZooKeeperRedis SET NXFencing TokenMutexLeader ElectionIdempotencyExactly-OnceDistributed SystemsMartin KleppmannRace ConditionInventory ReservationPayment Deduplication

Why Distributed Locks Are Hard

A mutex in a single process is straightforward: lock.acquire(), do work, lock.release(). In a distributed system, this simple contract breaks down because of three realities:

  1. Clocks are unreliable. A lock with a 10-second TTL in Redis measures time on the Redis server's clock. The client that holds the lock measures time on its own clock. These can diverge by seconds under NTP slippage, GC pauses, or VM migration.

  2. Processes pause unpredictably. A Java process holding a distributed lock can pause for 30 seconds on a GC stop-the-world event. The lock expires. Another client acquires the lock. The first client resumes and continues writing — now two clients are in the critical section simultaneously.

  3. Networks partition. A client acquires a lock, then loses network connectivity. The lock holder can't release the lock. The system must time out and recover. How long do you wait?

The result: a distributed lock that your system relies on for correctness under all conditions is very hard to build correctly. The first question in any interview is not "how do you implement it" but "do you actually need it?"

IMPORTANT

Premium content locked

This guide is premium content. Upgrade to Pro to unlock the full guide, quizzes, and interview Q&A.