The mechanism
Every practical distributed lock is a lease, so a crashed holder can't block everyone forever. That makes the promise conditional. Redis's page on distributed locks says mutual exclusion "is only limited to a given window of time from the moment the lock is acquired", and that Redlock's guarantee holds "only as long as the client holding the lock terminates its work within the lock validity time".
The client can't keep that promise alone, because it can't stop the world between checking its lease and using it. Google's Chubby paper (OSDI 2006): "a process holding a lock L may issue a request R, but then fail. Another process may acquire L and perform some action before R arrives at its destination." The request can be delayed in three places:
- In the process. Martin Kleppmann's 2016 post notes that stop-the-world GC pauses "have sometimes been known to last for several minutes"; page faults and a stray
SIGSTOPfreeze a process too. The HBase troubleshooting guide names "prolonged garbage collection pauses that last longer than the default ZooKeeper session timeout" as "another very common reason" for RegionServers "committing seppuku": HBase shuts such a node down by design "so that it stops serving data that may already be assigned elsewhere". - In the network. A write sent before the lease expired can arrive after it.
- In the clock. Redis's page warns that "Redis is not using monotonic clock for TTL expiration mechanism", so "a wall-clock shift may result in a lock being acquired by more than one process."
None of this needs a bug in the lock service; the paused client simply doesn't know its lease ended.
The Redlock debate
Redlock runs on N independent Redis primaries, five in the documented example. A client sends SET resource_name my_random_value NX PX 30000 to each in parallel and holds the lock if a majority succeed within the lease. The documented minimum validity is MIN_VALIDITY=TTL-(T2-T1)-CLOCK_DRIFT. In February 2016 Kleppmann and Salvatore Sanfilippo (antirez, Redis's author) argued about whether this is safe.
Kleppmann, "How to do distributed locking" (8 February 2016). If the lock is only for efficiency, "You are better off just using a single Redis instance". For correctness, Redlock's "safety depends on a lot of timing assumptions": bounded network delay, process pauses and clock error. In his first example, client 1 locks nodes A, B and C, "The clock on node C jumps forward, causing the lock to expire", client 2 locks C, D and E, and "Clients 1 and 2 now both believe they hold the lock." In his second, client 1 sends lock requests to all five nodes and goes into a stop-the-world GC while the replies wait in its kernel buffers; the locks expire, client 2 takes all five, and client 1 wakes and reads the replies as success. And Redlock's random value can't be a fencing token, because it doesn't increase. His recommendation: "if you need locks for correctness, please don't use Redlock", use "a proper consensus system such as ZooKeeper", and "enforce use of fencing tokens on all resource accesses under the lock."
antirez, "Is Redlock safe?" (February 2016). He disputed both arguments. On the pause example, Redlock reads the clock before and after acquiring, and "after acquiring the majority we *check again* that we are not out of time", so a pause or delay during acquisition is caught. A pause after that check is real, but it is common to "*all the distributed locks implementations*" with auto-release, not a flaw of Redlock. He conceded that "Redis and Redlock implementations should switch to the monotonic time API", and said clock jumps are otherwise avoided operationally. On fencing he pushed back hardest. Distributed locks matter "exactly when we have no other control in the shared resource". A store that rejects lower tokens is already linearizable, and if you can reject a racing write, "you probably don't need a distributed lock at all". He offered a check-and-set "just for the sake of showing that Redlock can work well in this, very artificial, context": write the random value into the resource, then do the read-modify-write "only if the token is still the same when we write." He concluded that Kleppmann's advice against Redlock where mutual exclusion is needed was not justified.
The posts don't settle whether Redlock is safe; Redis's page still links both. Both accept that a lease can't stop a holder that pauses after its last check from writing after the lease ends. Where the resource can check, both put the final check in the resource, as an atomic conditional write: Kleppmann's increasing token, or antirez's check-and-set. And antirez's objection points where this guide does: a resource that can reject a stale writer often needs no strong lock. Redis's page says "You should implement fencing tokens", for "any distributed locking system."
Redlock has one more cost. Under AOF's default fsync once a second (and AOF is off by default, which loses more), a node that loses power can come back without the lock key, letting another client win a majority. Redis's page offers fsync=always, or a delayed restart: keep a crashed node out "for at least a bit more than the max TTL".
Fencing tokens, and who checks them
A fencing token is "a number that increases (e.g. incremented by the lock service)" with each grant. Every write under the lock carries it, and the resource rejects any token lower than one it has seen. In Kleppmann's example, when paused client 1 wakes and writes with token 33 after client 2 wrote with 34, "the storage server remembers that it has already processed a write with a higher token number (34), and so it rejects the request".
Steps as text
- Client 1 → Lock service: acquire lease
- Lock service → Client 1: granted, token 33
- After a pause: Client 2 → Lock service: acquire lease
- Lock service → Client 2: lease 33 expired: granted, token 34
- Client 2 → Storage: write, token 34
- Storage → Client 2: ok, highest token is now 34
- Client 1 → Storage: wakes from GC: write, token 33 (the harmful step)
- Storage → Client 1: rejected: 33 is below 34
Kleppmann adds the condition design reviews skip: "this requires the storage server to take an active role in checking tokens". If the code under the lock updates Postgres, writes to S3 and calls a payment API, all three must reject a stale token, or the late writer gets through wherever nobody checks. Chubby's sequencer carries "the lock generation number", and the receiving server "is expected to test whether the sequencer is still valid". For servers that couldn't, Chubby added an "imperfect" lock-delay: after a holder fails, nobody else may take the lock for a period "up to some bound, currently one minute".
In Postgres the check must be one statement. Reading the token, comparing in the application and then writing reopens the gap:
UPDATE seats
SET holder = $1, fence = $2
WHERE seat_id = $3 AND fence <= $2; -- 0 rows updated: a newer holder already wroteUse <= so the same holder can write more than once under its token, and declare fence NOT NULL DEFAULT 0, because NULL < $2 is never true.
ZooKeeper and etcd revisions
In ZooKeeper's lock recipe the lowest sequential znode holds the lock, and Kleppmann says "you can use the zxid or the znode version number as fencing token". In etcd every change gets "a single increasing revision". The Lock RPC returns a key that exists while you own the lock and "can be used in conjunction with transactions" so writes to etcd happen only while you hold it.
Two limits. Consensus makes the grant safe, not the holder: Apache Curator's Tech Note 10 walks through a client with a 3-second session timeout that pauses for 10 seconds, after which, "for a short period of time, BOTH CLIENT A AND CLIENT B WILL BELIEVE THEY ARE THE LOCK HOLDER". And etcd's own transaction check protects only writes to etcd. For anything else, pass the lock key's revision as the token and have that store check it; Jepsen's advice after its etcd analysis was to use "the revision of their lock key as a globally ordered fencing token".
When a constraint replaces the lock
Often the lock protects a rule the database can enforce at commit, where no pause can get between check and write: one booking per seat, one charge per order, no overlapping reservations.
- Unique constraint.
UNIQUE (event_id, seat_no). The second insert fails no matter how long its client paused, andINSERT ... ON CONFLICT DO NOTHINGturns the loss into a detectable no-op. - Exclusion constraint.
EXCLUDE USING gist (room WITH =, during WITH &&)ensures that for any two rows "at least one of these operator comparisons will return false or null": no overlapping bookings for a room.room WITH =needs thebtree_gistextension. - Conditional write. DynamoDB's
attribute_not_exists(Id)puts only if no item has that key; a condition such asfence <= :tokenrejects a stale holder's update. - A lock inside the same database.
SELECT ... FOR UPDATElocks rows "until the current transaction ends", andpg_advisory_xact_lockis "automatically released at the end of the transaction", so lock and write commit together. A session-level advisory lock, "held until explicitly released or the session ends", is a lease again.
Keep a Redis lock in front for efficiency; the constraint keeps the data right. Our episode Redis Lock Expired: Why Seat 14C Sold Twice follows one paused holder to the Postgres condition that rejects it.
Worked numbers
The lease budget (illustrative). Inputs: a Redlock TTL of 10,000 ms, 40 ms to reach a majority of five nodes, and a 1% clock-drift allowance (100 ms). The documented formula leaves 10,000 − 40 − 100 = 9,860 ms for every write to start and land. A 10-second stop-the-world GC uses all of it, and the lock can't tell the paused client.
Rare times volume (illustrative). Inputs: 2,000,000 lock-protected jobs a day, a one-in-a-million chance that a job is paused or delayed past its remaining lease, and another worker always waiting for the same lock, so every such pause becomes an overlap. That is 2 overlapping holders a day, about 730 a year; for a rarely contended key, multiply by the chance someone takes it during the pause. Without fencing, each is a potential double booking; with it, a rejected write you can count.
What the documented values allow. Each bar is a default or example for how long a holder can be gone before the lock moves on, except Chubby's lock-delay, the most a client can make others wait after that. A holder paused past its lease plus any lock-delay can wake to a second holder already writing. ZooKeeper session timeouts are requests: the server grants 2 to 20 times its tickTime, so with the sample tickTime of 2,000 ms a 60-second request gets 40.
Data as text
| Default or example (seconds) | |
|---|---|
| Chubby lease extension | 12 |
| Chubby lock-delay cap | 60 |
| Curator session timeout | 60 |
| HBase ZooKeeper session | 60 |
| Redis SET example PX | 30 |
| Redlock example TTL | 10 |
Measured, not illustrative. Jepsen's etcd 3.4.3 analysis (30 January 2020) is a fault-injection test. Five processes used etcd locks to guard updates to an in-memory set, each reading the set and writing it back about one second later. With two-second lease TTLs and process pauses every five seconds, Jepsen "could reliably induce the loss of ~18% of acknowledged updates". A 3.4.3 bug made it worse: after a client waited for a lock, the server didn't re-check its lease. Jepsen's verdict: "etcd locks (like all distributed locks) do not provide mutual exclusion." etcd's team corrected its consistency documentation and patched the missing lease check; lock-safety documentation was still "under development" at publication.
How it fails
- Both sides of a fenced pair expected to be active (GitHub, 22 December 2012). During a switch-upgrade window, the network vendor killed an agent on one aggregation switch to collect diagnostics; its MLAG peer failed over the disruptive way, and spanning-tree reconvergence blocked all traffic between access switches "for roughly a minute and a half". GitHub's active/passive fileserver pairs used STONITH "to shut power down to the active node before failing over". Many "exceeded their heartbeat timeouts" and issued STONITH, but some commands never got through. Afterwards "a number of pairs were in a state where both nodes expected to be active for the same resource"; the nodes terminated one another, leaving both stopped in a number of pairs. Recovering every pair "took over five hours". GitHub's fixes: HA maintenance mode before network changes, and a review of every HA configuration. STONITH is the other kind of fencing: it stops the old holder instead of having the resource reject it, so it rests on timeouts like a lease. A timeout can't tell a slow peer from a dead one, and a fencing command sent over the failed network may never arrive.
- A library Redis lock that failed to release (Close, postmortem of 8 January 2021). Close used tasktiger's Redis lock, whose code came from an old version of
redis-py, with a 60-second maximum hold. Under a burst of phone-verification traffic, a client that failed to acquire could overwrite the lock's value, so the holder's release check failed and the key was left to expire. Calls averaging 0.5 seconds went "closer to 60s", and Close had to "drain and replace whole Kubernetes nodes". Close says it was lucky to be hit during a low-traffic period, and there was no customer impact. The fix wasredis-py's built-in lock. Lesson: lock withSET key token NX PX, release with an atomic compare-and-delete (DELEX key IFEQ tokenfrom Redis 8.4, a Lua script before), and use your client library's current lock, not an old copy.
Decision table
| Option | What it costs | Choose it when |
|---|---|---|
Single Redis SET NX PX, compare-and-delete release | One round trip; asynchronous replication drops locks on failover; no fencing | Efficiency only: a duplicate run wastes work but harms no data |
| Redlock, N independent Redis primaries | Five servers; timing assumptions; fsync always or delayed restarts; no increasing token | Only if the lock service itself must survive losing a Redis node, and a resource-side check still guards correctness |
| ZooKeeper or etcd lock, no fencing | A consensus cluster to run; sessions still expire under pauses | Leader election that tolerates a brief overlap |
| Lease plus fencing token checked by every resource | Every store under the lock keeps and compares a token | Work spans several systems that can all do a conditional write |
| Conditional write or compare-and-set on the resource | One extra column or attribute; callers must handle the rejection | One store holds the state; often no lock is needed |
| Unique or exclusion constraint | An index and its write cost; the losing caller gets an error to handle | The rule is uniqueness or no overlap: seats, charges, bookings |
SELECT FOR UPDATE or transaction-level advisory lock | Holds a connection and transaction through the critical section | The data lives in the same database |
Two questions settle most reviews. Is the lock for efficiency or for correctness? If correctness, which resource rejects the stale holder, and is that check in the same atomic operation as the write?
A check you can run this week
Find every lock in your services:
grep -rnE --exclude-dir={.git,node_modules,vendor} "SET .*NX|SETNX|SetNX|nx=True|setIfAbsent|\.lock\(|getLock\(|[Rr]ed[Ll]ock|redsync|InterProcessMutex|concurrency\.NewMutex|pg_(try_)?advisory_lock" .Skip the in-process locks among the hits. For each shared lock, list what the code under it writes to, and whether each write carries a condition (WHERE fence <= $token, a unique key, a condition expression) that rejects it if a newer holder wrote first. A write without one is protected only by timing.
Then prove it in staging: freeze a job holding the lock with kill -STOP $PID, wait past the TTL, start a second job, then kill -CONT $PID. Any write from the first job that lands is the double booking you'd otherwise meet in production.
Sources
The primary sources this guide was checked against.
- Martin Kleppmann: How to do distributed locking (8 February 2016)
- Salvatore Sanfilippo (antirez): Is Redlock safe? (February 2016)
- Redis documentation: Distributed Locks with Redis (Redlock)
- Burrows: The Chubby lock service for loosely-coupled distributed systems (OSDI 2006)
- Jepsen: etcd 3.4.3 (30 January 2020)
- Apache Curator: Tech Note 10, JVM pauses and session timeouts
- Apache ZooKeeper: Recipes and Solutions (Locks)
- etcd documentation: KV API guarantees (revisions)
- etcd documentation: concurrency API reference (Lock RPC)
- Apache HBase: Troubleshooting (GC pauses and ZooKeeper session expiry)
- GitHub: Downtime last Saturday (incident 22 December 2012)
- Close engineering: Race to the Lock, a postmortem story (8 January 2021)
- PostgreSQL documentation: Constraints (unique and exclusion constraints)
- PostgreSQL documentation: INSERT (ON CONFLICT)
- PostgreSQL documentation: Explicit locking (row and advisory locks)
- PostgreSQL documentation: btree_gist
- Amazon DynamoDB documentation: Condition expressions
- Apache ZooKeeper: Programmer's Guide (session timeout negotiation)
- Apache ZooKeeper: Administrator's Guide (tickTime, maxSessionTimeout)
Hear it discussed
Episodes of the show that work through this decision.