Preview — Pro guide
You are seeing a portion of this guide. Sign in and upgrade to unlock the full article, quizzes, and interview answers.
Sections
Related Guides
Distributed Systems Patterns
High-Level Design
Caching: Strategy, Redis Internals & Distributed Patterns
High-Level Design
Databases: Sharding, Indexing & Replication
High-Level Design
Microservices Architecture: Decomposition, Service Mesh, Circuit Breakers & Saga Pattern
High-Level Design
Consistency Models: Strong vs Eventual vs Causal, Linearizability, CRDTs & CAP Theorem
High-Level Design
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.
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:
-
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.
-
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.
-
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?"