Three replicas of a billing worker run the same nightly job, and only one may charge customers. The usual answer is a distributed lock: take a lock in Redis, ZooKeeper or etcd, do the work, release it. But a lock across a network does not behave like a mutex inside one process. The holder can pause, its messages can be delayed, and the lock service has to decide on its own that the holder is gone.
This post explains what a distributed lock can and cannot guarantee: leases, the Redis single-instance pattern and Redlock, ZooKeeper's ephemeral sequential znodes, etcd's leases and revisions, and fencing tokens, the piece that makes a lock safe to rely on. The diagram shows the failure that fencing tokens prevent.
Efficiency locks and correctness locks
Martin Kleppmann's analysis, How to do distributed locking, starts with the question to ask before choosing any tool: what happens if two processes hold the lock at the same time?
| Efficiency lock | Correctness lock | |
|---|---|---|
| Purpose | Avoid doing the same work twice | Protect shared state from concurrent writes |
| If two holders overlap | An extra email, a recomputed report | Corrupted data, a double charge, a lost update |
| Good enough | A single Redis instance with a TTL | A consensus-based lock service plus fencing tokens |
Most locks in real systems are efficiency locks, and that is fine: leader election in a job scheduler only decides which instance polls for due jobs, while row locks and a unique run key stop duplicate runs. The mistake is to use one for a correctness problem and discover during an incident that "only one at a time" was never guaranteed.
Every distributed lock is a lease
A lock service cannot tell a crashed holder from a slow one or from a network partition. If it waited forever, one crashed worker would block everyone. So every practical lock expires: a TTL in Redis, a session timeout in ZooKeeper, a lease in etcd. It is a lease, an idea that goes back to Gray and Cheriton's 1989 paper on leases for distributed file caches.
The expiry is also the weak point. The service decides by its own clock that the lock has expired, while the holder still believes it holds it. Three things open that gap:
- Process pauses. A garbage collection pause, a VM migration or swapping can stop a process for longer than the lease.
- Network delay. A write sent while the lease was valid can reach the storage after it expired.
- Clock jumps. A server whose clock jumps forward expires keys early; the Redis documentation notes that Redis does not use a monotonic clock for TTL expiry.
Checking "do I still hold the lock?" right before writing does not help, because the pause can happen between the check and the write. Renewing the lease more often shrinks the window but cannot close it. Only the resource itself can reject a write from a holder that has lost the lock, and that is what fencing tokens are for.
Redis: one key with NX and a TTL
The single-instance pattern from the Redis documentation sets a key only if it does not exist, with an expiry and a random value unique to this holder:
SET lock:invoice-run 3f9c1e7a0b2d NX PX 30000
To release, delete the key only if it still holds your value, atomically, so you never delete a lock that expired and was taken by another client:
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
else
return 0
end
Redis 8.4 adds DELEX key IFEQ value, which does the same in one command. This makes a good efficiency lock, with two limits. Redis replication is asynchronous, so if the primary fails before the replica has the key, the promoted replica lets a second client take the same lock. And the value is random, not ordered, so it cannot serve as a fencing token.
Redlock, and the argument about it
Redlock, described on the same page, removes the single point of failure without replication. The client sets the same key and value on N independent Redis primaries, five in the documentation's example:
- Read the current time.
- Send
SET NX PXto all five instances in parallel, each with a short timeout. - The lock is acquired only if at least three accepted it and the time spent is less than the TTL.
- The remaining validity is the TTL minus the time spent, minus an allowance for clock drift.
- On failure, release the key everywhere and retry after a random delay.
An instance that restarts without the key can let a second client reach a majority, so the documentation recommends fsync=always or keeping a crashed instance down for longer than the maximum TTL.
Kleppmann's criticism is that Redlock's safety depends on timing assumptions (bounded network delay, process pauses and clock error) that real systems violate, and that it cannot produce fencing tokens. Salvatore Sanfilippo, the creator of Redis, replied in Is Redlock safe?, and the Redis documentation links both; its own disclaimer now tells you to implement fencing tokens. A practical reading: Redlock adds availability to an efficiency lock, but does not make Redis a correctness lock.
ZooKeeper: ephemeral sequential znodes
An ephemeral znode exists only while the session that created it is alive. A sequential znode gets a 10-digit counter appended to its name, unique under its parent and always increasing. The locks recipe combines them:
- Create an ephemeral, sequential child under the lock node, such as
/locks/invoice-run/lock-0000000033. - List the children without setting a watch.
- If your node has the lowest sequence number, you hold the lock.
- Otherwise, watch only the node just below yours, and repeat from step 2 when it goes away.
To unlock, delete your node. If the holder crashes, its session expires and ZooKeeper deletes the node, which wakes the next waiter. Watching only the predecessor avoids the herd effect, where every waiter wakes on every release.
The session timeout is the lease; the server keeps it between 2 and 20 times its tickTime (programmer's guide). For the fencing token, Kleppmann suggests the zxid or the znode version; since the recipe grants the lock in sequence order, the node's sequence number also works. On the JVM, Apache Curator's InterProcessMutex implements this recipe.
etcd: leases, lock keys and revisions
An etcd client creates a lease with a TTL and keeps it alive with heartbeats. The Lock RPC creates a key under the lock name, attached to that lease, and returns it once the caller owns the lock; waiters are ordered by the creation revision of their keys. If the lease expires or is revoked, the key disappears and the next waiter gets the lock.
Every change in etcd gets a revision from one increasing counter, and the etcd documentation treats the revision as the fencing token. The same page warns that a lease alone does not guarantee mutual exclusion and that the lock only protects etcd keys; any other resource must validate the token itself. The command-line tool exposes it:
# Hold the lock while the script runs; etcdctl releases it when the script exits
etcdctl lock --ttl 10 invoice-run ./run-invoices.sh
# The script sees ETCD_LOCK_KEY (the holder key) and ETCD_LOCK_REV (the revision)
# and sends ETCD_LOCK_REV with every write as the fencing token
Revisions count every write in the cluster, so tokens usually skip numbers (the diagram's 33 and 34 are simplified); only their order matters. etcd agrees on that order with Raft, explained in the Raft consensus diagram. A lock needs that agreement, because taking one is a compare-and-set, which quorum reads and writes in a Dynamo-style key-value store cannot provide on their own.
Fencing tokens: making the resource say no
A fencing token is a number that increases every time the lock is granted. The holder sends it with every write, and the resource rejects any token lower than the highest it has accepted. Google's Chubby lock service used the same idea in 2006: Burrows's paper describes a sequencer with the lock name, the mode and a lock generation number, which servers check before acting.
In a database, the check is one conditional write:
-- orders.fence holds the highest token accepted for this row
UPDATE orders
SET status = 'paid', fence = :token
WHERE id = :order_id AND fence <= :token;
-- 0 rows updated: a newer holder already wrote, so stop
Three rules make it work:
- The check and the write are atomic, in one statement or transaction.
- Every write carries the token, including retries and background threads.
- The resource must support it. Third-party APIs and email providers cannot check your token; use their conditional requests or idempotency keys.
Kubernetes leader election shows the gap. Controllers elect a leader through a Lease object, and the client-go leader election package states that it does not guarantee that only one client is acting as leader (what it calls fencing). With its defaults for core components, a 15-second lease and a 10-second renew deadline, a leader that pauses longer than its lease can still act after another replica takes over.
Choosing a lock service
| Redis SET NX | Redlock | ZooKeeper | etcd | PostgreSQL advisory lock | |
|---|---|---|---|---|---|
| Expiry | Key TTL | Key TTL on each instance | Session timeout | Lease TTL | End of session or transaction |
| Survives a server failure | No: replication is asynchronous | While a majority is up | Yes: Zab quorum | Yes: Raft quorum | No: locks end with the session |
| Fencing token | None | None | Sequence number or zxid | Revision | None; use a version column |
| Best for | Efficiency locks | Efficiency locks that survive a node failure | Correctness locks | Correctness locks | Work in the same database |
PostgreSQL advisory locks are easy to overlook: a session-level lock lasts until it is released or the session ends, and pg_advisory_xact_lock until the transaction ends. If the data lives in the same database and the work runs in that transaction, a lost connection aborts the work along with the lock.
Before choosing any of these, ask whether you need a lock at all. A unique constraint or a conditional update often enforces "only once" on its own, as the ticket booking design does for seat holds.
The distributed lock diagram
Diagram contents
- Worker A
- Lock service (etcd)
- Worker B
- Orders DB
- stale holder: token 33 < 34
- acquire lock, lease TTL 10 s
- granted, token 33
- acquire lock
- granted, token 34
- write order 9, token 34
- OK, highest token 34
- write order 9, token 33
- rejected: 33 < 34
How to read it:
- Four lifelines: two workers, the lock service and the database that holds the data. Time runs downward.
- Top: Worker A acquires the lock with a 10-second lease and gets token 33. The yellow notes show A's 15-second GC pause and the lease expiring at 10 seconds.
- Middle: Worker B acquires the lock, gets token 34 and writes order 9, in green. The database now knows 34 as the highest token.
- Red break fragment: A wakes up and writes with token 33. The database rejects the write, and A stops.
- Notes on the right: the SQL fence check, token sources and lease rules.
Drawing distributed lock diagrams clearly
- Use a sequence diagram for the race. Locks fail in time, not in topology; lifelines show the pause and the expiry, which boxes and arrows cannot.
- Draw the resource as a participant. Safety is won or lost at the write to the data store.
- Put the token on every message so readers can tell the holders apart.
- Show the unhappy path in a fragment or a warning color.
- State the timings: lease TTL, renewal interval and the pause that breaks them.
Common mistakes are leaving out the expiry and showing a lock "protecting" an API that never sees the token. The sequence diagram example covers the notation, the two-phase commit diagram applies it to a coordinator, and the database replication diagram covers split brain, the same problem one level down.
Build it in Archboard
- Sign in with Google or GitHub and create a diagram.
- From the Sequence pack, add four Lifeline nodes in a row: Worker A, Lock service (etcd), Worker B and Orders DB, each with its own accent color.
- Draw the messages as edges, top to bottom: acquire lock and "granted, token 33" for Worker A, acquire lock and "granted, token 34" for Worker B, then B's write with token 34 and the OK reply. Make the replies dashed.
- Add a Fragment from the Sequence pack with the operator
breakand the guard "stale holder: token 33 < 34", and draw A's write with token 33 and the rejection inside it in red. - Add two Core Note nodes for the GC pause and the lease expiry.
- Add a Markdown block from the Core pack with the fence check, the token sources and the lease rules, plus two Core Text lines above and below the lifelines.
The example uses 6 diagram nodes (the notes and text lines count separately), well within the Free plan's limit of 15 diagram nodes per diagram.
FAQ
What is a fencing token? A number that increases each time a lock is granted. The holder sends it with every write, and the resource rejects tokens lower than one it has already accepted, so a holder that lost its lock cannot overwrite newer work.
Is a Redis lock safe? As an efficiency lock, yes. As a correctness lock, no: neither the single-instance pattern nor Redlock produces fencing tokens, and failover or clock jumps can let two clients hold the lock at once.
Should I use ZooKeeper or etcd for locks? Both replicate locks through a quorum and give you an ordered token. Pick the one your team already runs: ZooKeeper is common in JVM stacks through Curator, etcd in Kubernetes-centered platforms.
How long should a lock's TTL be? Longer than the work normally takes, with a margin, and renewed well before it runs out. No TTL covers every pause: the TTL provides liveness, the fencing token provides safety.
Do I need a distributed lock at all? Often not. If the work writes to one database, a unique constraint or a conditional update can enforce "only once" without a lock service.