What it is
A distributed lock gives one process at a time, anywhere in a cluster, the right to do something: modify a record, process a file, run a migration. It is stored in a shared service (Redis, etcd, ZooKeeper, Consul, a database) that every process can reach. Because the holder can crash, the lock always comes with an expiry, which makes it a lease: the right to act for a limited time.
Why it exists
Concurrent read-modify-write cycles lose updates: two processes read the same value, both change it, and the second write erases the first. Inside one process a mutex prevents that; across machines you need a lock everyone agrees on. Locks are used for two different purposes, and the distinction drives every design choice:
- Efficiency: avoid doing the same work twice (sending the same report, recomputing the same cache entry). An occasional overlap costs a little extra work.
- Correctness: an overlap corrupts data or double-charges a customer. The lock must hold under crashes, pauses and partitions.
How it works
Acquire. The client atomically creates the lock key only if it does not exist, with a value unique to this attempt and a TTL. In Redis: SET resource_lock <random-id> NX PX 30000. In etcd: a transaction that creates the key under a lease if its create revision is 0 (the concurrency.Mutex helper does this). In ZooKeeper: an ephemeral sequential znode; the lowest sequence number holds the lock.
Release. Delete the key only if its value is still yours, atomically. In Redis this is a short Lua script (if get == my-id then del). Without the check, a client whose lock already expired would delete the next holder's lock.
Expiry. If the holder crashes, the TTL frees the lock. Long-running work must extend the lease before it runs out (a watchdog thread, etcd keep-alives, ZooKeeper session heartbeats).
The pause problem. A lease can expire while its holder is still running but not making progress: a stop-the-world garbage collection, a VM paused for live migration, a process swapped out, or a write stuck in a network queue. When the holder resumes, it believes it still holds the lock and writes. Checking the lock right before writing does not help, because the pause can fall between the check and the write. Martin Kleppmann's 2016 essay "How to do distributed locking" uses exactly this example.
Fencing tokens. The lock service returns a number that increases with every grant. The client includes it in every operation on the protected resource, and the resource rejects any operation whose token is lower than the highest it has accepted. A holder whose lease expired carries an old token and is turned away, however late its write arrives. Consensus-backed services provide such numbers naturally (etcd revisions, ZooKeeper zxids or znode versions). The resource has to cooperate: a conditional update (UPDATE … SET …, fence = :t WHERE id = :id AND fence < :t), a version column, or an object-store precondition.
Redlock. Redis's algorithm for a lock that survives the failure of Redis nodes uses N independent masters (typically 5). The client records the start time, tries to set the key on each node in turn with a short per-node timeout, and holds the lock if it succeeded on a majority and the elapsed time is less than the TTL. The lock is then valid for the TTL minus the elapsed time minus a clock-drift allowance (the reference implementation uses 1% of the TTL plus 2 ms). On failure it releases the key on all nodes.
The Redlock debate. Kleppmann argued that Redlock's safety depends on bounded network delay, bounded pauses and bounded clock drift; that a clock jump on a Redis node can expire a key early; and that it does not produce fencing tokens, because independent nodes cannot generate one monotonic counter. Salvatore Sanfilippo (antirez), Redis's author, replied in "Is Redlock safe?" that these timing assumptions are reasonable in practice, that the algorithm checks elapsed time after acquisition, that Redis should use monotonic time for expiry, and that a pause after acquisition affects every auto-releasing lock, which a unique value combined with check-and-set on the resource can address. Both agree that pauses exist; they disagree on how much to rely on timing.
When to use it
- Preventing duplicate work across instances (efficiency): a single Redis lock is usually enough, and Redlock adds tolerance of Redis node failures.
- Protecting a resource from concurrent modification (correctness): use a consensus-backed lock service and fencing tokens the resource checks.
- Short critical sections around external systems that cannot do transactions themselves, again with fencing if correctness matters.
When not to
- When the database can enforce the rule itself: a transaction,
SELECT … FOR UPDATE, a unique constraint or an optimistic version check is simpler and safer. - When the operation can be made idempotent: process it as many times as you like and let deduplication handle overlaps.
- When work can be partitioned so that each item has one owner (a queue, consistent hashing) and nobody needs to lock.
- Do not use a lock to hide a missing transaction or a race in your own data model.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Single Redis node | Very fast, simple | Lock lost if the node fails over (async replication); no fencing token |
| Redlock (5 Redis masters) | Survives minority node failures | More round trips; safety depends on timing assumptions; no fencing token |
| etcd / ZooKeeper / Consul lock | Consensus-backed; monotonic tokens for fencing | Slower (a consensus write per acquire); another critical cluster |
| Database row or advisory lock | Uses infrastructure you already run; transactional | Couples locking load to your primary database; session-scoped locks vanish on connection loss |
| Short TTL | Fast recovery after holder crashes | More renewals; leases expire under slow-but-alive holders |
| Long TTL | Fewer spurious expiries | Long waits after a holder crashes |
Alternatives
- Optimistic concurrency: read a version, write with
WHERE version = :v, retry on conflict. No lock service at all. - Database transactions and row locks when all the data lives in one database.
- Single-owner partitioning: route all work for a key to one consumer (Kafka partitions, consistent hashing) so no two workers touch the same key.
- Idempotency keys: let duplicates happen and make them harmless.
- Leader election when one process should own a whole job rather than lock individual resources.
Failure modes
- Expired lease, live holder: GC pauses, VM freezes, slow I/O or clock jumps let a former holder act after someone else acquired the lock. Only fencing at the resource prevents damage.
- Releasing someone else's lock with an unconditional delete after your own lease expired.
- Lock lost on failover: a Redis primary acknowledges a lock, crashes before replicating it, and the promoted replica grants it again.
- Lock service outage: nobody can acquire; design for a fallback or for the work to wait safely.
- Forgotten renewals: a long task outlives its TTL because the watchdog thread was blocked by the task itself.
In production
Decide first whether the lock is for efficiency or correctness and say so in the code. For efficiency, a Redis lock with a unique value, a TTL several times the expected work time and a compare-and-delete release is common. For correctness, use etcd, ZooKeeper (Apache Curator's InterProcessMutex) or Consul, pass the fencing token to every write, and make the resource check it; combine with idempotency so retries are safe. Measure how long work takes compared with the TTL, alert on lock wait times, and test by pausing a holder (kill -STOP) past its TTL.
Common misconceptions
- "If I check that I still hold the lock just before writing, I am safe." A pause or network delay after the check breaks it.
- "Redlock is unsafe" or "Redlock is safe": its safety depends on timing assumptions; whether they are acceptable depends on what a violation costs you.
- "A lock without a TTL is safer." It deadlocks the system the first time a holder crashes.
- "The lock service protects the data." It only tells clients who should act; the data is protected only if the resource checks a token.
Interview angle
When a design needs mutual exclusion, first ask whether a transaction, a unique constraint, optimistic versioning or single-owner partitioning removes the need. If a distributed lock is still needed, explain acquire with a unique value and TTL, owner-checked release, and why the TTL makes it a lease. Then bring up the pause problem and fencing tokens unprompted, and position Redlock neutrally: fine for efficiency, debated for correctness. That sequence shows depth.
Model assumptions
This lesson is a scripted illustration, not a simulation: the simulator has no lock, lease, pause or fencing model, so every acquire, release, read and write is a packet placed by hand, and lock state, tokens and pauses are annotations. Time is compressed: a 600 ms lock TTL, a 700 ms pause, 30 ms one-way between a client and the lock service or storage, 5 ms between a client and a Redis node, a 20 ms per-node timeout and about 1 ms of processing. Real TTLs are typically seconds to minutes. Token values (33, 34) are illustrative.