Programming
We provide developers and engineers the guides and tutorials they...
Search
We provide developers and engineers the guides and tutorials they...
Content is king. It's not just about how you're going to write, b...
Looking for an engaging connection with thousands of other people...
How distributed locks work with Redis, ZooKeeper and etcd, why leases expire at the wrong moment, how fencing tokens fix it, and safer alternatives.
Quick answer: A distributed lock lets processes on different machines agree that only one of them may do something at a time. It is implemented by having each process try to create a record in a shared store, such as Redis, ZooKeeper or etcd; whoever succeeds holds the lock. Because the holder might crash, the lock must expire automatically. And that is the problem: a holder that is merely paused or slow can have its lock expire and be given to someone else while it still believes it is in charge. A safe design therefore attaches an increasing fencing token to each lock, and the protected resource rejects any request carrying an old token.
Inside a single process, a mutex stops two threads touching the same data. See processes vs threads. Across machines there is no shared memory, so you need a shared service to arbitrate.
Martin Kleppmann's article How to do distributed locking separates two very different purposes:
| Purpose | Example | If the lock fails |
|---|---|---|
| Efficiency | Avoid two workers generating the same report | Some wasted work; a duplicate email |
| Correctness | Prevent two processes writing the same file or charging the same account | Corrupted data, lost updates, real harm |
The first can tolerate an imperfect lock. The second cannot, and needs far more care.
With Redis, a simple lock looks like this:
SET lock:invoice-42 <random-value> NX PX 30000
NX means "only set if the key does not exist". Exactly one client succeeds.PX 30000 sets an expiry of 30 seconds.To release, delete the key only if it still holds your value. That check-and-delete must be atomic, so it is done in a small Lua script. Without the check, a client whose lock had expired could delete a lock now held by someone else.
The Redis documentation on distributed locks describes this pattern.
If a client takes a lock and then crashes, the lock would be held forever. So every practical distributed lock is really a lease: it is valid for a limited time and then lapses.
But a lease assumes the holder knows when its time is up. Consider:
Both clients now believe they hold the lock, and both write. The lock did not provide mutual exclusion.
No timeout value fixes this. A process cannot detect that it was paused between checking the lock and performing the write. Clock problems make it worse: if the holder's clock or the lock service's clock jumps, the lease may be shorter or longer than intended. See why clocks can't be trusted.
The solution is to stop trusting the lock holder's opinion and let the resource enforce exclusion.
Replaying the failure:
The stale client is fenced off. Correctness no longer depends on timing.
This requires the resource to support such a check. A database can do it with a conditional write, such as UPDATE ... WHERE version < 34. Many storage services offer conditional writes or version checks that serve the same purpose.
A lock in one Redis instance has a further weakness: if that instance fails over to a replica, the lock may not have been replicated yet, because Redis replication is asynchronous. The new primary has no record of it and grants it again.
Redlock is an algorithm proposed by Redis's creator to address this. The client tries to acquire the lock on several independent Redis nodes, typically five, and considers it held if a majority succeed within a time limit.
Its safety has been publicly debated. Kleppmann's critique argues that Redlock depends on assumptions about timing, bounded clock drift, pauses and network delay, that real systems violate, and that it produces no fencing token. The practical summary:
ZooKeeper and etcd replicate their state with a consensus protocol (ZAB and Raft respectively), so an acknowledged lock survives node failures and cannot be granted twice by a split cluster.
ZooKeeper's recipe
The sequence number, or the node's transaction ID, can serve as a fencing token.
etcd offers leases and transactions, and each key has a revision number that increases with every change, which works well as a fencing token.
Even these are still leases underneath. A paused client can outlive its session, so fencing remains necessary for correctness.
If everything you need to protect lives in one database, you do not need a separate lock service.
SELECT ... FOR UPDATE inside a transaction.These are simpler and safer, because the lock and the data are covered by the same transaction. See how database transactions handle concurrent users.
Often the better answer is to remove the need:
A lock that must be perfectly correct across machines is one of the harder things to build. Avoiding it is frequently easier than getting it right.
A mechanism that lets processes on different machines ensure only one of them performs a particular action at a time, using a shared coordination service.
It is fine for avoiding duplicate work. For protecting correctness, it is not sufficient on its own, because failover and expired leases can allow two holders.
A number that increases each time a lock is granted. The protected resource rejects requests with a token older than the newest it has seen, which blocks stale lock holders.
A lease is a lock with a time limit. Distributed locks are leases in practice, since the holder may crash and never release.
A distributed lock is easy to acquire and hard to trust. Expiry is necessary to recover from crashes, yet expiry is exactly what lets a paused holder overlap with a new one. If duplicated work is merely wasteful, a simple lock will do. If it would corrupt data, combine a consensus-backed lock with fencing tokens, or better, design the lock away.