Distributed Locking: Redis, Redlock, Fencing Tokens, Leases
"The fix for this problem is actually pretty simple: you need to include a fencing token with every write request to the storage service." — Martin Kleppmann, How to do distributed locking (2016)
Summary: A distributed lock is a promise made by a separate service that only one process may do some work right now. The promise has an expiry, the process holding it can freeze at any moment, and the network can delay its messages, so the lock alone can never guarantee that two processes do not act at the same time. It becomes safe only when the protected resource itself checks a number that grows with every acquisition: the fencing token. Focus: Why distributed locks are hard (no shared memory, process and GC pauses, clock drift, partitions, advisory enforcement), Kleppmann's efficiency-versus-correctness split, the single-instance Redis lock (SET NX PX, Lua compare-and-delete, Redis 8.4 DELEX and SET IFEQ), TTL versus work duration and the watchdog, Redlock and the Kleppmann/antirez debate, fencing tokens, leases, consensus-based locks (ZooKeeper, etcd, Consul), database locks (pg_advisory_lock, FOR UPDATE SKIP LOCKED, lease rows), lock-free alternatives, the classic bugs, Laravel's Cache::lock, onOneServer, withoutOverlapping and WithoutOverlapping, Kubernetes Lease objects and observability. Learning goal: Decide whether a job needs a lock at all; if it does, say whether it is an efficiency or a correctness lock, pick the store that matches, set TTL and renewal from measured work time, release only your own lock, and make every protected write carry and enforce a fencing token, with Go and Laravel code and tests that replay a paused holder.
This chapter owns mutual exclusion across processes and machines. Row locks, lock modes and pg_locks inside one database are taught in Locks & Concurrency Control; version columns and compare-and-set retry loops in Optimistic vs Pessimistic Locking; Redis data structures and persistence in Redis; consensus algorithms (Raft, Paxos) in Distributed SQL, Consensus & 2PC; what "linearizable" promises in Consistency Models. Choosing one active node for a whole service is Leader Election, the next chapter, which builds on the leases and fencing taught here. Making a request safe to repeat (often the better answer than a lock) is API Idempotency.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why a lock across machines is not a mutex | Why it exists |
| Leases 1989, Chubby, Redlock, the 2016 debate | Where it comes from |
| What "advisory" means | What a distributed lock is |
| Do I need a correct lock or a cheap one? | Efficiency vs correctness |
SET key value NX PX 30000 | Single-instance Redis lock |
Safe release, DELEX, the Lua script | Release |
| How long the TTL should be, watchdogs | TTL and watchdog |
| GC, SIGSTOP, page faults, 90-second packets | Pauses |
NTP steps, gettimeofday, drift | Clocks |
| Five Redis masters and a majority | Redlock |
| Who was right in 2016 | The debate |
| The one thing that makes a lock safe | Fencing tokens |
| Time-bounded ownership | Leases |
| ZooKeeper, etcd, Consul | Consensus-based locks |
pg_advisory_lock, SKIP LOCKED, lease rows | Database locks |
| Avoiding the lock entirely | Lock-free alternatives |
Cache::lock, onOneServer, WithoutOverlapping | Laravel locks |
coordination.k8s.io Lease | Kubernetes Lease |
| What to graph and alert on | Observability |
| Redis, Redisson, etcd, ZooKeeper, Consul, PostgreSQL side by side | Products |
| Exact commands, replies, error texts | Mechanics |
| Working code | Go, Laravel, SQL |
| Classic failures and fixes | Solving the classic problems |
| Which tool for which job | Choosing |
| Monolith to distributed system | In architecture |
| Hands-on experiments | Lab |
| Beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
What can go wrong, and what stops it.
| Failure | Plain words | Tiny example | What stops it |
|---|---|---|---|
| Check-then-act race | Two workers both see "free" and both take it | EXISTS lock then SET lock | One atomic command: SET key v NX PX ttl |
| Unlocking someone else's lock | Your lock expired, another took it, you delete theirs | Plain DEL lock after a slow job | Random owner value + compare-and-delete (Lua or DELEX IFEQ) |
| Lock expires mid-work | The job runs longer than the TTL | 10 s TTL, 30 s job | Measured TTL, renewal by a watchdog, stop work when renewal fails |
| Paused holder | The process freezes, wakes up after expiry, keeps writing | 15 s GC pause, 10 s lease | Fencing token checked by the resource |
| Failover loses the lock | Async replica promoted without the key | Redis primary crash | Consensus store (etcd, ZooKeeper) or accept it (efficiency lock) |
| Clock jump | Server clock steps forward, key expires early | NTP step on one Redlock node | Monotonic clocks, slewing NTP, fencing |
| Forever lock | Holder dies and the lock never expires | Cache::lock('x') with 0 seconds on Redis | Always a TTL; leases instead of locks |
The tools, from cheapest to strongest.
| Tool | Guarantee | Typical use | Fencing token available |
|---|---|---|---|
Single Redis SET NX PX | Mutual exclusion while one primary lives and clocks behave | Cron dedup, cache rebuild, rate of expensive work | Not built in; INCR beside it (this page) |
| Redlock (5 masters) | Majority-based, still timing-dependent | Little: heavier than needed for efficiency, not enough for correctness | No |
Laravel Cache::lock | Same as the cache driver underneath | Jobs, scheduler, controllers | No |
| PostgreSQL advisory lock | Exclusive while the session lives | Migrations, one-at-a-time batch jobs | No (session ends = lock gone) |
| Database lease row | Linearizable on the primary, expiry by now() | Job ownership, partition ownership | Yes, a fence_token column |
| etcd lease + Mutex | Linearizable (Raft) | Correctness locks, leader election | Yes, the key's create revision |
| ZooKeeper ephemeral sequential node | Linearizable writes (Zab) | Correctness locks, Kafka-era coordination | Yes, zxid or znode version |
| Consul session + KV acquire | Raft-backed, advisory | Service-level locks, leader election | Yes, LockIndex in the sequencer |
| Kubernetes Lease | Stored in etcd through the API server | Controller leader election, node heartbeats | leaseTransitions counts, client-go does not fence |
The four rules.
| Rule | Why |
|---|---|
| Ask "what breaks if two run at once?" before choosing | Efficiency locks can be cheap; correctness locks need consensus plus fencing |
| Every lock has an expiry and an owner token | Without expiry a crash locks forever; without owner you release other people's locks |
| The resource checks the token, not the client | A paused client cannot check anything at the moment that matters |
| Prefer no lock: idempotency, compare-and-set, single writer | A lock is the most fragile way to get exclusion |
Why it exists
Inside one process a mutex works because all threads share memory, the operating system knows which thread holds it, and a crashed process takes its threads and its mutex with it. Across machines none of that is true. The lock lives in another service; the holder learns that it holds it through a message; it learns nothing when the lock silently expires; and the holder can stop executing for seconds without being dead.
Process with a mutex Two machines with a "distributed lock"
1 mu.Lock() 1 A: SET lock A NX PX 10000 -> OK
2 // no other thread can enter 2 A: starts work
3 write shared map 3 A: GC pause 15 s (A is alive, but frozen)
4 mu.Unlock() 4 lock expires at 10 s on Redis
5 crash = whole process gone, no holder 5 B: SET lock B NX PX 10000 -> OK, B works
6 A: wakes at 15 s, continues writing: two writers| Mutex in one process | Lock across machines |
|---|---|
| Shared memory, the lock is a word in RAM | The lock is a key in another service, reached over a network |
| Holder failure frees the lock (process dies) | Holder failure is indistinguishable from a slow holder |
| No expiry needed | Expiry is required, so ownership can end while the holder still works |
| The OS enforces it for code that uses it | Purely advisory: nothing stops a write that ignores it |
| Clock irrelevant | TTLs depend on clocks on the lock server, and sometimes the client |
| Cost: nanoseconds | Cost: one or more network round trips, plus a consensus write for strong stores |
Everyday picture: a hotel key card for a meeting room. The front desk (the lock service) gives you a card valid until 15:00. If you fall asleep in the corridor until 15:20, the desk has already given a card to the next group, and your card still looks fine in your hand. The only thing that stops you walking in on them is a door that reads the card's issue number and refuses any number lower than the last one it opened for. That door is the fencing check; the card number is the fencing token.
Three common misunderstandings, up front
- "Redis
SET NXgives me a mutex." It gives you a key that exists for a while. Whether only one process acts depends on the TTL being longer than the work, the holder never pausing, Redis never failing over, and nobody deleting the key. Those are assumptions, not guarantees. - "With a watchdog that renews the lock, expiry cannot happen while I work." The watchdog runs in the same process. When the process freezes, the watchdog freezes too; when it wakes, the lease may already belong to someone else.
- "Redlock fixes the single-node problems, so it is safe for money." Redlock tolerates node crashes, but it still depends on bounded pauses, delays and clock drift, and it issues no number that a resource can check. For correctness you need fencing, whatever lock you use.
Where it comes from
The idea of time-bounded ownership is older than any of today's lock services. Cary Gray and David Cheriton's 1989 SOSP paper Leases: An Efficient Fault-Tolerant Mechanism for Distributed File Cache Consistency introduced the lease: a grant that expires by itself, so a crashed holder cannot block others forever. Every modern lock with a TTL is a lease, which is why Kleppmann describes Redlock as implementing distributed locks "or rather, leases".
Google's Chubby (Mike Burrows, OSDI 2006) made the lock service a product: coarse-grained locks on a Paxos-replicated store, with a sequencer the holder passes to servers so they can reject stale requests, and a lock-delay that keeps a lock unavailable for a while after its holder disappears. HashiCorp says plainly that Consul's session semantics are "heavily borrowed from Chubby". Apache ZooKeeper published the lock recipe with ephemeral sequential nodes; etcd exposed leases, revisions and a concurrency package in its v3 API.
On the Redis side, the official Distributed Locks with Redis page describes the single-instance pattern and proposes Redlock, asking for feedback. On 8 February 2016 Martin Kleppmann published How to do distributed locking, arguing that Redlock is "neither fish nor fowl". Salvatore Sanfilippo (antirez) replied the next day with Is Redlock safe?. Kleppmann's update notes the rebuttal and says "I stand by my conclusions". Today the Redis page itself carries a "Disclaimer about consistency" that tells readers to implement fencing tokens.
| Year | Event | Source |
|---|---|---|
| 1989 | Gray and Cheriton, Leases (SOSP) | Reference [1] in Kleppmann's post |
| 2006 | Burrows, The Chubby lock service (OSDI): sequencers, lock-delay | Google Research paper page; Consul docs |
| ZooKeeper era | Lock recipe: ephemeral + sequence flags, watch the next-lowest node | ZooKeeper recipes |
| 2016 (8 Feb) | Kleppmann critiques Redlock, introduces fencing tokens to most readers | martin.kleppmann.com |
| 2016 (9 Feb) | antirez replies: monotonic clocks yes, the rest disputed | antirez.com |
| v1.26 | Each kube-apiserver publishes an identity Lease in kube-system | Kubernetes Leases docs |
| Redis 8.4 | DELEX key IFEQ value and SET ... IFEQ make compare-and-delete and compare-and-renew native | redis.io command docs |
The concept catalogue
What a distributed lock really is, and why it is advisory Must-know
In plain words: a distributed lock is a record in some shared service that says "process X may do job J until time T". Everyone agrees to look at it before doing J. Nobody is forced to.
Common misunderstanding: "If I hold the lock, nobody else can touch the data." The data store does not know your lock exists. Any code path that forgets to take it, an operator running a script, or your own process after the lock expired, can write freely.
Definition: a distributed lock is an advisory mutual-exclusion protocol between processes that do not share memory, implemented on a shared store that offers an atomic conditional write (create-if-absent, compare-and-set) and an expiry. Its safety property is mutual exclusion ("At any given moment, only one client can hold a lock", in the Redis docs' words); its liveness properties are freedom from deadlock (expiry) and fault tolerance (the store survives node loss).
Who enforces what
1 Lock service: decides who holds key "invoice-run" (atomic create-if-absent)
2 Holder: promises to touch the resource only while holding
3 Resource: (database, S3, payment API) knows nothing about the lock
4 Other code: a migration script writes the same rows without asking: allowed
5 -> exclusion holds only among clients that cooperate, and only while time assumptions holdReal scenario: a nightly invoice run on three app servers; one importer per tenant; one resize job per uploaded image; one process reindexing a search alias; one consumer per Kafka-less legacy queue.
| Store | Atomic conditional write | Expiry | Enforced on the data? |
|---|---|---|---|
| Redis | SET NX, Lua scripts, SET IFEQ (8.4) | Key TTL (PX, EX) | No |
| PostgreSQL | INSERT ... ON CONFLICT, advisory lock functions | Session end, or a lease column | Only if the protected table checks a token |
| etcd | Txn with Compare on revision/version/value | Lease TTL, kept alive by the client | Only through a guarded Txn or a token |
| ZooKeeper | create fails if the node exists; sequential names | Ephemeral node dies with the session | Only through a token (zxid) |
| Consul | KV ?acquire= session check-and-set | Session TTL, health checks | No; Consul says "this locking system is purely advisory" |
Fix / how to use it: treat the lock as a coordination hint and put the final guard in the resource: a fenced write, a unique constraint, an idempotency key, or a version check. The fencing block and the Go code show it.
Efficiency lock vs correctness lock Must-know
In plain words: some locks only save money (do not compute the same report twice); others protect the truth (do not charge a card twice, do not corrupt a file). Decide which kind you have first.
Common misunderstanding: "A lock is a lock; I will just use the strongest one everywhere." The strongest store costs latency, operations and availability, and still needs fencing. Using it for a cache rebuild wastes all three; using a cheap lock for payments loses money on the first failover.
Definition: Kleppmann's test is "what would happen if the lock failed". Efficiency: "If the lock fails and two nodes end up doing the same piece of work, the result is a minor increase in cost ... or a minor inconvenience". Correctness: the result is "a corrupted file, data loss, permanent inconsistency, the wrong dose of a drug administered to a patient, or some other serious problem."
Same lock, two outcomes on failure
1 efficiency: rebuild "top-sellers" cache; lock lost on failover; two nodes rebuild -> 2x CPU for 5 s
2 correctness: append to ledger file in S3; lock lost; two writers interleave -> file corrupted
3 decision: (1) single Redis is fine; (2) consensus lock + fencing, or no lock (single writer)Real scenario: efficiency: dedupe a cron across servers, prevent a thundering rebuild of a cache key, throttle a costly ML batch. Correctness: move money, assign a unique seat, write a shared file, change a DNS record, send a robot to a shelf.
| Question | Efficiency lock | Correctness lock |
|---|---|---|
| Cost of two holders | Extra work, a duplicate email | Corruption, double charge, inconsistency |
| Store | Single Redis, Cache::lock, advisory lock | etcd, ZooKeeper, Consul, database lease row |
| Fencing token | Optional | Required |
| Redlock worth it? | No: "unnecessarily heavyweight" (Kleppmann) | No: "not sufficiently safe" (Kleppmann) |
| What to document in code | "Approximate; may occasionally fail" | Which token the resource checks |
Fix / how to use it: label every lock in code (// efficiency lock or // correctness lock, fenced by documents.fence_token). The decision flow turns the question into a choice.
Single-instance Redis lock: SET NX PX Must-know
In plain words: one Redis command creates the lock key only if it does not exist and gives it an expiry, in one atomic step.
Common misunderstanding: "SETNX and then EXPIRE is the same thing." Two commands leave a gap: crash between them and the key lives forever. The SET options NX and PX do both atomically, and the SET docs note that its options "can replace SETNX, SETEX, PSETEX, GETSET".
Definition: the Redis docs give the acquire as SET resource_name my_random_value NX PX 30000: set "only if it does not already exist (NX option), with an expire of 30000 milliseconds (PX option)". The value "must be unique across all clients and all lock requests"; the docs assume "20 bytes from /dev/urandom". The reply is OK on success and a null reply when NX was not met.
Client A Client B Redis
1 SET lock:invoices a7f3... NX PX 30000 -> OK (key, ttl 30 s)
2 SET lock:invoices 19c0... NX PX 30000 -> (nil)
3 sleep 50-200 ms with jitter, retry
4 ... work ...
5 EVAL compare-and-delete lock:invoices a7f3... -> 1 (deleted)
6 SET lock:invoices 19c0... NX PX 30000 -> OKReal scenario: a scheduler on four servers where one should send the daily digest; a cache-aside rebuild that should hit the database once (Caching); a webhook processor that should not process the same payload twice in parallel.
| Detail | Choice | Why |
|---|---|---|
| Value | 128-160 random bits, per acquisition | Release and renew must prove ownership |
| Expiry option | PX (ms) or EX (s); PXAT for absolute | NX and expiry must be one command |
| Replica reads | Never read the lock from a replica | Replication is asynchronous |
| Redis Cluster | Lock key and companion keys share a hash tag, e.g. lock:{invoices} and lock:{invoices}:fence | Multi-key scripts must hit one slot |
| Retry | Random delay; the Redis docs recommend it "to desynchronize multiple clients" | Avoids lock-step contention |
| Persistence | Efficiency lock: default; correctness: not Redis alone | A crash or failover can forget the key |
Fix / how to use it: in Go, the acquireScript in redislock.go runs SET NX PX and INCR of a fence counter in one Lua script; in Laravel, Cache::lock('name', 120) does SET name owner EX 120 NX on the redis driver (framework source RedisLock::acquire).
Releasing safely: Lua compare-and-delete and DELEX Must-know
In plain words: only delete the lock if it still holds your random value. Otherwise you may be deleting the next holder's lock.
Common misunderstanding: "My code always finishes before the TTL, so plain DEL is fine." One slow query, one GC pause, or one retry loop is enough; the Redis docs warn: "Using just DEL is not safe as a client may remove another client's lock."
Definition: release is a compare-and-delete executed atomically on the server. Before Redis 8.4 it is a Lua script (if redis.call("get",KEYS[1]) == ARGV[1] then return redis.call("del",KEYS[1]) else return 0 end); "Redis guarantees the script's atomic execution". Redis 8.4 adds DELEX key IFEQ value, which returns 1 if deleted and 0 "if not deleted (the key does not exist or a specified IFEQ/IFNE/IFDEQ/IFDNE condition is false)". The same release added SET key value IFEQ old PX ms, a native compare-and-renew.
A (TTL 10 s) B Redis key lock:x
1 SET lock:x A NX PX 10000 A
2 slow work 12 s ... (t=10 s) key expires -
3 SET lock:x B NX PX 10000 B
4 DEL lock:x <-- BUG: deletes B's lock -
5 C acquires too: B and C both run
4' EVAL compare-and-delete A -> 0 (value is B): B keeps its lock, A logs "lost lock"Real scenario: a report job releasing in finally; a queue worker whose release runs after a 40 s HTTP call; a Laravel job releasing a lock acquired in a web request (pass the owner token, see Laravel locks).
| Release method | Atomic | Checks owner | Available |
|---|---|---|---|
DEL key | Yes | No | All versions: unsafe |
GET then DEL from the client | No (race between them) | Yes, but too late | Never do this |
Lua compare-and-delete via EVAL/EVALSHA | Yes | Yes | Redis 2.6+, all clients |
DELEX key IFEQ value | Yes | Yes | Redis 8.4+ |
Laravel $lock->release() | Yes (Lua on redis driver; WHERE owner = ? on database driver) | Yes | Laravel 13 |
Laravel forceRelease() | Yes | No (intentional, for operators) | Laravel 13 |
Fix / how to use it: go-redis redis.NewScript(...).Run (it "optimistically uses EVALSHA"); report a 0 reply as ErrNotOwner, never ignore it: it means your lock was lost and the work you just did ran without exclusion.
TTL vs work duration, auto-extension and the watchdog Must-know
In plain words: the TTL is how long a dead holder blocks everyone. Too short and the lock expires while you work; too long and a crash stalls the system. Renewal (a watchdog) lets you hold a short TTL for a long job, as long as your process keeps running.
Common misunderstanding: "Set the TTL to the p99 job time and you are safe." p99 means 1 in 100 runs is longer; GC, slow disks and retries make the tail heavier. And a watchdog only shortens the risk window: it renews from inside the process that might freeze.
Definition: the Redis docs call the TTL the "lock validity time": "both the auto release time, and the time the client has in order to perform the operation required before another client may be able to acquire the lock again". Auto-extension renews the TTL with a compare-and-pexpire while the owner value matches. Redisson's watchdog "prolongs lock expiration while lock holder Redisson instance is alive", default lockWatchdogTimeout 30 seconds. Laravel offers $lock->refresh(), which "If no number of seconds is provided, the lock's original duration will be used."
TTL 30 s, renew every 10 s (ttl/3)
1 t=0 acquire, lease to t=30
2 t=10 renew ok -> lease to t=40
3 t=20 renew ok -> lease to t=50
4 t=22 process paused (GC / VM steal / SIGSTOP) -- watchdog paused too
5 t=50 lease expires; node B acquires at t=51
6 t=58 A wakes: watchdog's next renew fails -> cancels work context
7 but A's in-flight write was sent at t=58 before it noticed -> only fencing stops itReal scenario: a 20-minute export with a 60 s lock renewed every 20 s; a report generator calling refresh() after each batch; a Redisson-based Java service whose GC pause exceeded the 30 s watchdog timeout.
| Setting | Rule of thumb | Reason |
|---|---|---|
| TTL without renewal | Well above measured max work time, plus headroom | Expiry mid-work is the main failure |
| TTL with renewal | 10-60 s | Bounds how long a crashed holder blocks others |
| Renewal interval | TTL / 3 | Two missed renewals still leave time |
| Renewal call timeout | Below the interval | A hung renewal must not look like success |
| On renewal failure | Cancel work immediately, do not retry the renewal forever | The lock is gone; continuing is unsafe |
| Max total hold | A ceiling (e.g. 1 h) | The Redis docs: limit "the maximum number of lock reacquisition attempts" for liveness |
Fix / how to use it: in Go, Lock.KeepAlive returns a context cancelled with ErrNotOwner when a renewal fails or the local deadline passes; in Laravel, check the boolean from refresh() and stop.
Process pauses, GC pauses and network delay Must-know
In plain words: a process can stop for seconds or minutes and then carry on as if nothing happened. During that time its lock can expire and be given to someone else.
Common misunderstanding: "Go (or PHP) has short GC pauses, so this is a Java problem." Kleppmann lists other causes: a page fault on a swapped page, a disk that is really network storage (EBS), CPU contention, SIGSTOP. A VM migration or a container CPU throttle does the same. And a write can sit in the network: "in a famous incident at GitHub, packets were delayed in the network for approximately 90 seconds".
Definition: a process pause is any interval during which a live process executes no instructions while the world's clock advances. A network delay is the same effect on a message already sent. Both mean that "check the lock, then write" can never be made safe by the client alone: "GC can pause a running thread at any point, including the point that is maximally inconvenient for you (between the last check and the write operation)."
Client 1 Lock (TTL 10 s) Storage
1 acquire -> ok held by 1
2 check: still held? yes
3 ---- pause 15 s ---- t=10 expires
4 client 2 acquires
5 client 2 writes v2
6 write v1 (sent now) v1 overwrites v2 <-- corruptionReal scenario: HBase used to have this problem, according to Kleppmann's post; a PHP worker on an overloaded host throttled by cgroups; a Kubernetes node under memory pressure swapping; a laptop lid closed during a local test.
| Cause of the pause | Typical length | Detected by the client? |
|---|---|---|
| Stop-the-world GC (JVM, .NET) | ms to minutes ("several minutes" cited by Kleppmann) | Only afterwards |
| Page fault, swap, network disk | ms to seconds | No |
| CPU throttling (cgroup quota), noisy neighbour | ms to seconds | No |
VM live migration, SIGSTOP, debugger | seconds to minutes | No |
| Network delay of an already-sent write | seconds; ~90 s in the GitHub incident | No |
Fix / how to use it: there is no client-side fix. Use a fencing token checked at the resource, or redesign so the resource itself is the lock (a conditional write, see lock-free).
Clock drift and clock jumps Important
In plain words: TTLs are measured by clocks. If a server's clock jumps or runs fast, a lock can expire early or late.
Common misunderstanding: "We run NTP, so time is fine." NTP can step the clock when it is far off, an administrator can set it by hand, and Kleppmann notes that Redis uses gettimeofday, "not a monotonic clock, to determine the expiry of keys". The Redis docs agree in their disclaimer: "Redis is not using monotonic clock for TTL expiration mechanism. That means that a wall-clock shift may result in a lock being acquired by more than one process."
Definition: clock drift is the rate difference between clocks (one counts 10 s as 9.5 s); a clock jump is a discontinuous step. Redlock assumes "the local time in every process updates at approximately at the same rate, with a small margin of error compared to the auto-release time of the lock". antirez frames the requirement as being able to "be able to count 5 seconds with a maximum of 10% error". A monotonic clock never jumps backwards and ignores wall-clock steps.
Redlock, five nodes A..E, TTL 10 s
1 client 1 locks A, B, C (D, E unreachable) -> majority
2 C's clock steps forward 10 s -> C's key expires immediately
3 client 2 locks C, D, E -> also a majority
4 clients 1 and 2 both hold the lockReal scenario: a VM resumed from suspend; NTP stepping after a long partition from the time server; a leap-second smear configured on some hosts and not others; a container with a mis-set timezone does not matter (TTL uses epoch), but a mis-set epoch does.
| System | Clock that decides expiry | Note |
|---|---|---|
| Redis key TTL | Wall clock of the Redis server | Per Redis docs disclaimer |
| etcd lease | The leader's timer; the requested TTL is "the advisory time-to-live" and the server returns its own "server selected time-to-live" | Refreshed by keep-alives |
| Consul session TTL | Servers; TTL is "a lower bound for invalidation" | Consul: "clients should be aware of clock skew issues" |
| PostgreSQL lease row | now() on the primary | One clock decides; clients' clocks irrelevant |
| Kubernetes client-go leader election | Local timestamps of each candidate | "tolerant to arbitrary clock skew, but is not tolerant to arbitrary clock skew rate" |
Fix / how to use it: let one clock decide (the store's), measure elapsed time with a monotonic clock in the client (Go's time.Now() carries a monotonic reading; time.Since uses it), configure NTP to slew, and fence anyway.
Redlock Important
In plain words: instead of one Redis, use five independent Redis masters and count the lock as yours only if you got it on at least three, quickly enough.
Common misunderstanding: "Redlock is Redis Cluster or a replicated Redis." The nodes are "totally independent, so we don't use replication or any other implicit coordination system". The algorithm runs in the client library (Redsync for Go, Redisson for Java, node-redlock and others).
Definition: per the Redis docs, the client (1) reads the current time in ms; (2) tries SET NX PX with the same key and random value on all N instances in parallel, each with a timeout "small compared to the total lock auto-release time" (for a 10 s TTL, "~ 5-50 milliseconds"); (3) the lock is acquired "if and only if the client was able to acquire the lock in the majority of the instances (at least 3), and the total time elapsed to acquire the lock is less than lock validity time"; (4) validity is "the initial validity time minus the time elapsed"; (5) on failure it unlocks all instances. The safety argument bounds the overlap with MIN_VALIDITY=TTL-(T2-T1)-CLOCK_DRIFT.
T1 = now()
1 SET k v NX PX 10000 -> A: OK (3 ms) B: OK (4 ms) C: OK (6 ms) D: timeout 50 ms E: timeout 50 ms
2 T2 = now(); elapsed = 52 ms
3 3/5 >= N/2+1 and elapsed < 10000 -> acquired, validity = 10000 - 52 - drift ~ 9.9 s
4 work must finish inside ~9.9 s
5 release: compare-and-delete on all five (even D and E)Real scenario: teams that outgrew a single Redis lock after a failover incident and reached for Redsync; a multi-tenant SaaS where the lock budget is hundreds of thousands per second (antirez's argument: "it's possible to process hundreds of thousands locks per second with a few Redis instances").
| Redlock knob | Value in the docs | Effect |
|---|---|---|
| N | 5 | Tolerates 2 failed nodes |
| Per-node timeout | 5-50 ms for a 10 s TTL | A dead node does not eat the validity |
| Retry | "after a random delay" | Reduces split votes |
| Crash recovery | Delayed restart for "a bit more than the max TTL", or fsync=always | Otherwise a restarted node forgets keys |
| Extension | Lua extend on all nodes, majority within validity | Same algorithm as acquire |
| Fencing | None | The main objection |
Fix / how to use it: if the lock is for efficiency, a single instance is simpler and Kleppmann recommends it; if it is for correctness, use a consensus store and fencing. Redlock fits a narrow middle: you need the lock to survive one Redis node loss, and occasional double execution is tolerable.
The Kleppmann critique and antirez's reply Important
In plain words: Kleppmann said Redlock has no fencing tokens and relies on timing that real systems violate. antirez said the time checks in the algorithm catch delays during acquisition, that a random value can serve as a check-and-set token, and that strong locks are mostly used where no other guard exists.
Common misunderstanding: "The debate proved Redlock broken" or "antirez proved it safe". Both agree on more than people think: both say the client must check elapsed time, antirez agreed to move Redis to monotonic time, and both say the lock cannot protect work that outlives it. They disagree on whether a system model with bounded clock rate error is acceptable and on how useful fencing is.
Definition: the two claims and the replies, quoted from the saved posts:
| Point | Kleppmann | antirez |
|---|---|---|
| Fencing | Redlock "does not have any facility for generating fencing tokens" | A store that enforces increasing tokens is, in his words, "a linearizable store", so you could generate IDs there; a random token can drive check-and-set |
| Timing model | Redlock assumes "bounded network delay", "bounded process pauses", "bounded clock error" | Needs only that processes count time at roughly the same rate (a bounded rate error, his example 10%) |
| Delay during acquire | GC between request and reply breaks it | Steps 1 and 3 re-read the time, so "the lock will always be considered not valid if too much time elapsed" |
| Delay after acquire | Unsafe without fencing | Agreed: common to "all the distributed locks implementations" |
| Clock jumps | gettimeofday jumps | Agrees: Redis "should switch to the monotonic time API" |
| Recommendation | Efficiency: single Redis. Correctness: "a proper consensus system such as ZooKeeper" plus fencing | Redlock is fine when mutual exclusion is needed |
The case both accept as a failure (lock outlived by work)
1 client acquires on 3/5, validity 9.9 s
2 client pauses 12 s after step 3 of the algorithm
3 keys expire, another client acquires
4 paused client resumes and writes
5 -> antirez: a problem of every lock with expiry; Kleppmann: hence fencingReal scenario: design reviews that cite the debate to justify either choice; the Redis docs, which now say "You should implement fencing tokens" and link both posts.
| Takeaway | Applies to |
|---|---|
| Any lock with expiry can be outlived by its holder | Redis, Redlock, etcd, ZooKeeper, Consul, database leases |
| The only general defence is a check at the resource | Fencing tokens, conditional writes, idempotency |
| Redlock's majority helps availability, not the paused-holder problem | Redlock |
Fix / how to use it: decide by Kleppmann's efficiency/correctness test, and if the resource cannot check a token (an email, a physical robot), accept that no lock is correct and design for duplicates on the receiving side.
Fencing tokens Must-know
In plain words: every time someone gets the lock, they also get a number bigger than all earlier numbers. They send the number with every write. The storage remembers the biggest number it has accepted and refuses anything smaller.
Common misunderstanding: "My lock's random value is a token." A random value proves who you are; it does not say whether you are newer than the writer the storage last saw. Kleppmann: "The unique random value it uses does not provide the required monotonicity."
Definition: a fencing token is a strictly monotonically increasing number issued with each lock acquisition. The protected resource stores the highest token accepted per resource and rejects writes "on which the token has gone backwards". With ZooKeeper "you can use the zxid or the znode version number as fencing token"; etcd gives the lock key's create revision; Consul's (Key, LockIndex, Session) tuple acts as a unique "sequencer" (Consul's term); Redisson's RFencedLock "returns a monotonically increasing token on each acquisition"; a database lease row increments a column.
Client 1 Lock service Client 2 Storage (highest=0)
1 acquire -> token 33
2 ---- pause ----
3 lease expires
4 acquire -> token 34 -> gets 34
5 write(v2, 34) -> 34 >= 0: ok, highest=34
6 write(v1, 33) -----------------------------------------------> 33 < 34: REJECTEDReal scenario: writing a shared file in S3 through a service that checks a metadata token; updating a document row with WHERE fence_token <= $token; a storage node that keeps last_epoch per partition (Kafka's leader epochs work on the same principle); a payment service that refuses commands from an older leader epoch.
| Token source | Monotonic across failover? | How the resource checks |
|---|---|---|
| etcd create revision | Yes (Raft, cluster-wide revision) | Store column or guarded Txn with IsOwner() |
| ZooKeeper zxid / znode version | Yes (Zab) | Store column |
Consul LockIndex | Yes (Raft) | Compare with the last seen index |
Database lease fence_token | Yes on one primary; with sync replication across failover | Same database: UPDATE ... WHERE fence_token <= $1 |
Redis INCR on one primary | Only while no failover loses writes (Kleppmann: "that node may fail") | Store column |
| Redlock | No token | Not possible |
Fix / how to use it: fencing/store.go shows both an in-memory check and the SQL UPDATE ... WHERE id = $1 AND fence_token <= $2; LeaseRepository::fencedWrite is the Laravel version. The check and the write must be one atomic statement, or you have rebuilt check-then-act inside the resource.
Leases Must-know
In plain words: a lease is a lock with an end time built in. You hold it until it expires unless you renew it. If you crash, it ends by itself.
Common misunderstanding: "When my lease ends, I will notice and stop." You notice only if you are running and checking. A paused holder notices nothing; that is why a lease is always paired with fencing for correctness.
Definition: a lease is time-bounded ownership granted by a server, renewed by the holder before expiry, and revoked automatically when not renewed. etcd: "Leases are a mechanism for detecting client liveness. The cluster grants leases with a time-to-live. A lease expires if the etcd cluster does not receive a keepAlive within a given TTL period", and "When a lease expires or is revoked, all keys attached to that lease will be deleted." Kubernetes: Lease objects "provide a mechanism to lock shared resources and coordinate activity between members of a set." A lease column is the same idea in a database table: expires_at plus holder.
Holder side Server side (lease TTL 15 s)
1 LeaseGrant(TTL=15) -> lease 0x2a lease 0x2a, deadline t+15
2 Put /locks/job/0x2a lease=0x2a key attached to lease
3 KeepAlive every 5 s -----------------------> deadline pushed to now+15
4 process killed (OOM)
5 no keepalive for 15 s -> lease expires
6 key /locks/job/0x2a deleted, next waiter wakesReal scenario: etcd session per service instance; Kubernetes kubelets renewing a Lease in kube-node-lease (each heartbeat updates spec.renewTime); a job_leases table for partition ownership; a lease per shard in a stream processor.
| Lease system | Grant | Renew | Expiry effect |
|---|---|---|---|
| etcd | LeaseGrant (TTL seconds) | LeaseKeepAlive stream | Attached keys deleted |
| ZooKeeper | Session (timeout negotiated at connect) | Client heartbeats | Ephemeral nodes deleted |
| Consul | Session create (TTL, checks, behavior, lock-delay) | session/renew | Locks released (default) or deleted |
| Kubernetes | Create/Update a Lease object | Update renewTime | Others may take over after leaseDurationSeconds |
| PostgreSQL lease row | INSERT ... ON CONFLICT with expires_at | UPDATE ... SET expires_at by holder | Others' claim WHERE expires_at < now() succeeds |
Fix / how to use it: grant, renew at a third of the TTL, stop work on renewal failure, carry the lease's token into every write. pglock.ClaimLease and the SQL schema show a lease row.
Consensus-based locks: ZooKeeper, etcd, Consul Must-know
In plain words: these stores replicate every write through a consensus algorithm, so a lock taken on one node is seen by all and is not lost on failover. They also give you a number you can use as a fencing token.
Common misunderstanding: "Linearizable lock store means no fencing needed." Linearizability means the store itself never shows two holders at the same moment. Your paused client still believes it is the holder after its session expired; the store being correct does not stop that client's write to a different system.
Definition:
- ZooKeeper: "Call create( ) with a pathname of "locknode/guid-lock-" and the sequence and ephemeral flags set"; the client with the lowest sequence number holds the lock; others call
exists()with a watch on the next-lowest node only, which avoids the herd effect ("each node is watched by exactly one client"). The ephemeral node disappears when the session ends. The guid handles acreate()that succeeded but whose reply was lost. Apache Curator'sInterProcessMutexpackages the recipe. - etcd:
concurrency.NewSessioncreates a lease (default TTL 60 s: "If TTL is <= 0, the default 60 seconds TTL will be used") and keeps it alive;NewMutex(s, pfx).Lock(ctx)writes a key under the prefix and waits for keys with lower create revision to go;TryLockreturnsErrLocked("mutex: Locked by another session");IsOwner()returns aCmpusable inTxn(...).If(...). The server-side Lock RPC returns a key "that exists so long as the lock is held by the caller. This key can be used in conjunction with transactions to safely ensure updates to etcd only occur while holding lock ownership." - Consul: create a session (node, health checks, behavior
releaseordelete, TTL, lock-delay 0-60 s, default 15 s), thenPUT /v1/kv/<key>?acquire=<session>; the acquire "acts like a Check-And-Set operation";LockIndexincrements per acquisition. Consul states: "this locking system is purely advisory."
ZooKeeper lock recipe
1 A: create /lock/guidA-lock- (EPHEMERAL|SEQUENTIAL) -> /lock/guidA-lock-0000000007
2 B: create /lock/guidB-lock- (EPHEMERAL|SEQUENTIAL) -> /lock/guidB-lock-0000000008
3 A: getChildren(/lock) -> 7 is lowest -> A holds the lock
4 B: getChildren -> 8, not lowest -> exists(/lock/...-0000000007, watch=true)
5 A's session expires (or A deletes its node) -> watch fires for B only
6 B: getChildren -> 8 is lowest -> B holds the lock (token: zxid of node 8's creation)Real scenario: HBase and Kafka (before KRaft) coordinating through ZooKeeper; Kubernetes control plane state in etcd; Vault HA and service locks on Consul; Apache Curator locks in JVM shops.
| Feature | ZooKeeper | etcd v3 | Consul |
|---|---|---|---|
| Consensus | Zab | Raft | Raft |
| Liveness object | Session | Lease (TTL, keep-alive) | Session (TTL and/or health checks) |
| Lock record | Ephemeral sequential znode | Key with lease under a prefix | KV key with Session field |
| Waiting | Watch the predecessor (no herd) | Wait for lower create revisions to be deleted | Blocking query on the key |
| Fencing token | zxid, znode version | Create revision / mod_revision | LockIndex (sequencer) |
| Guarded write | multi with version check | Txn().If(m.IsOwner()) | Check LockIndex + session |
| Post-expiry safeguard | None built in | None built in | lock-delay (default 15 s) |
| Go client | github.com/go-zookeeper/zk | go.etcd.io/etcd/client/v3/concurrency | github.com/hashicorp/consul/api |
Fix / how to use it: etcdlock.RunExclusive takes a session, locks, reads its own key's create revision as the token and cancels work when sess.Done() closes; GuardedPut writes to etcd only if IsOwner() still holds.
Database locks: advisory locks, SKIP LOCKED, lease columns Must-know
In plain words: if all your workers already share a PostgreSQL primary, it can be the lock service: named advisory locks for "one at a time", SKIP LOCKED for "each worker takes different rows", and a lease table for ownership with expiry and a token.
Common misunderstanding: "Advisory locks are like row locks and go away on rollback." Session-level advisory locks "do not honor transaction semantics: a lock acquired during a transaction that is later rolled back will still be held following the rollback". And they belong to a connection: through a connection pool (PgBouncer in transaction mode, Go's *sql.DB) the unlock may run on a different connection than the lock.
Definition: PostgreSQL advisory locks are "locks that have application-defined meanings ... the system does not enforce their use". Session level: pg_advisory_lock(bigint) waits, pg_try_advisory_lock(bigint) returns boolean immediately, pg_advisory_unlock(bigint) returns false and a warning if not held; they are reentrant ("for each completed lock request there must be a corresponding unlock request"). Transaction level: pg_advisory_xact_lock / pg_try_advisory_xact_lock, released at transaction end with no unlock function. SELECT ... FOR UPDATE SKIP LOCKED skips rows other transactions have locked: "not suitable for general purpose work, but can be used to avoid lock contention with multiple consumers accessing a queue-like table". A lease column is a row with holder, expires_at and fence_token.
Session A (conn 1) Session B (conn 2)
1 SELECT pg_try_advisory_lock(42); -> t
2 SELECT pg_try_advisory_lock(42); -> f (skip this run)
3 BEGIN; ... ROLLBACK; -- lock still held (session level)
4 conn 1 dies (network) -> lock released by the server at session end
5 SELECT pg_try_advisory_lock(42); -> t
-- meanwhile A's app code, unaware, may still run: no fencing in advisory locksReal scenario: a migration runner that must not run twice at deploy; Laravel's database queue driver claiming jobs with FOR UPDATE SKIP LOCKED (see Laravel Queue Internals); a tenant-level pg_advisory_xact_lock around a reindex; partition ownership in a job_leases table.
| Tool | Scope | Released by | Fencing | Pitfall |
|---|---|---|---|---|
pg_advisory_lock / pg_try_advisory_lock | Session | pg_advisory_unlock, session end | No | Pooled connections; reentrant count; survives rollback |
pg_advisory_xact_lock | Transaction | COMMIT / ROLLBACK | No | Long transaction holds it and blocks VACUUM cleanup |
SELECT ... FOR UPDATE | Row, transaction | Transaction end | No | Holding a transaction open during a network call |
FOR UPDATE SKIP LOCKED | Row, transaction | Transaction end | No | "inconsistent view": queues only |
FOR UPDATE NOWAIT | Row | Transaction end | No | Error 55P03 lock_not_available instead of waiting |
Lease row (expires_at, fence_token) | Named resource | Expiry by now() or delete | Yes | Needs a renewal loop; table on the primary |
MySQL GET_LOCK(name, timeout) | Session | RELEASE_LOCK, session end | No | Same pooling caveat as PostgreSQL |
Fix / how to use it: use pg_advisory_xact_lock inside a transaction when the work fits in it; otherwise pin a connection (db.Conn(ctx) in Go, as in pglock.WithAdvisoryLock); for anything long-running or correctness-critical, a lease row with a fencing column. Advisory lock capacity is limited by max_locks_per_transaction and max_connections, "typically in the tens to hundreds of thousands".
Lock-free alternatives Must-know
In plain words: most "we need a lock" problems disappear if the write itself is conditional, repeatable or owned by one process.
Common misunderstanding: "Without a lock, concurrent workers will corrupt data." Only if each write blindly overwrites. A write that says "only if the version is still 12" or "insert this key once" is safe under any concurrency, with no expiry and no pause problem.
Definition: four families. Idempotency: the operation carries a key and a repeat has no extra effect (API Idempotency, Idempotent Consumers). CAS / optimistic concurrency: compare-and-set on a version or value (UPDATE ... WHERE version = 12, etcd Txn on mod_revision, Redis WATCH/MULTI, S3 conditional writes with If-Match); see Optimistic vs Pessimistic Locking. Single writer per key: partition the keyspace so exactly one consumer owns each key (Kafka partition per key, actor per aggregate); see Sharding at System Level. Queues: turn "only one may do it" into "put one message on a queue with competing consumers" (Competing Consumers).
Lock version CAS version (no lock)
1 acquire lock(account 7) SELECT balance, version FROM accounts WHERE id=7 -> 500, v12
2 read balance 500 UPDATE accounts SET balance=400, version=13
3 write 400 WHERE id=7 AND version=12 -> 1 row: done
4 release -> 0 rows: someone else won; re-read and retry
5 pause between 2 and 3 = lost update pause anywhere = a retry, never a lost updateReal scenario: wallet debits with a version column; stock decrement as UPDATE ... SET stock = stock - 1 WHERE stock > 0; one Kafka partition per order id so one consumer serialises an order's events; an outbox relay that is safe to run on two nodes because publishing is idempotent.
| Alternative | Replaces a lock when | Cost |
|---|---|---|
| Idempotency key | Duplicated work, not concurrent writes, is the risk | A dedup store and TTL |
| CAS / version column | Read-modify-write of one record | Retries under contention |
| Atomic single statement | The change can be expressed in one UPDATE | None; best option |
| Unique constraint | "Create once" (one invoice per month per customer) | Handle the duplicate-key error |
| Single writer per partition | Many keys, ordered work per key | Partitioning and rebalancing |
| Queue with competing consumers | "Run each job once" | At-least-once: still needs idempotency |
Fix / how to use it: the SQL block at the end of schema.sql shows the version-column CAS; reach for a lock only when the protected effect spans systems that cannot do a conditional write.
Laravel: Cache::lock, onOneServer, withoutOverlapping, WithoutOverlapping Important
In plain words: Laravel wraps the single-store lock pattern: Cache::lock for code, onOneServer and withoutOverlapping for the scheduler, WithoutOverlapping middleware for queued jobs. All of them are efficiency locks on your cache store.
Common misunderstanding: "WithoutOverlapping and withoutOverlapping are always safe defaults." The job middleware's lock has no expiry unless you call expireAfter(): its constructor defaults expiresAfter to 0, and on the redis driver a 0-second lock is a plain SETNX with no TTL (framework source RedisLock::acquire). A worker killed mid-job leaves that key forever. The docs warn the job "may unexpectedly fail or timeout in such a way that the lock is not released".
Definition: from the Laravel 13 docs and source:
Cache::lock($name, $seconds)withget(),get(Closure),block($seconds)(throwsIlluminate\Contracts\Cache\LockTimeoutException),release(),owner(),Cache::restoreLock($name, $owner),forceRelease(),refresh($seconds = null),isOwnedByCurrentProcess(),betweenBlockedAttemptsSleepFor($ms)(default 250 ms), plusCache::withoutOverlapping()andCache::funnel()for concurrency limiting. Drivers with locks: "memcached, redis, dynamodb, database, file, or array"; "all servers must be communicating with the same central cache server."- The owner is
Str::random()by default; release compares it (Lua on redis,WHERE owner = ?on database). - Scheduler:
->onOneServer()requires the "database, memcached, dynamodb, or redis" driver; the mutex name includes the scheduled minute (Hi) and is held 3600 s, so a second server checking in the same minute skips.->withoutOverlapping($minutes): "By default, the lock will expire after 24 hours";schedule:clear-cacheclears stuck locks.Schedule::useCache('redis')picks the store. - Job middleware
WithoutOverlapping($key)withreleaseAfter($seconds),dontRelease(),expireAfter($seconds),shared(); releases count as attempts, so raise$tries.
Laravel scheduler on three servers, Schedule::command('report:generate')->dailyAt('02:00')->onOneServer()
1 02:00:00.120 server-1: lock "framework/schedule-<hash>0200" for 3600 s -> acquired, runs
2 02:00:00.180 server-2: same name -> taken, skips
3 02:00:00.950 server-3: same name -> taken, skips
4 report takes 70 min; next day at 02:00 the minute key differs -> runs again (no overlap protection)
5 add ->withoutOverlapping(90) to also block a run while yesterday's is still goingReal scenario: a SaaS with six web nodes and one billing command; queue jobs per user that must not overlap; an HTTP endpoint that starts an export and a job that finishes it and releases the lock with the owner token.
| Laravel feature | Underlying lock | Default expiry | Watch out |
|---|---|---|---|
Cache::lock('x', 10) | Driver lock (SET NX EX on redis) | 10 s | Cache::lock('x') = 0 s = no expiry on redis |
block(5) | Polls acquire() | Waits up to 5 s | LockTimeoutException; release in finally |
refresh() | Lua compare-and-expire | Original duration | Returns false when lost: stop work |
restoreLock($name, $owner) | Same lock, given owner | Unchanged | Pass owner() to the job |
onOneServer() | Scheduling mutex per minute | 3600 s | Not overlap protection across days |
withoutOverlapping() | Event mutex | 24 h (1440 min) | Stuck after a crash: schedule:clear-cache |
WithoutOverlapping middleware | Cache::lock($key, expiresAfter) | 0 = forever on redis | Always add expireAfter() |
database cache driver lock | cache_locks table row with owner, expiration | Given seconds; 0 becomes 86400 s | Pruned by lottery (2 in 100) |
Fix / how to use it: Laravel code: ChargeMonthlyInvoices uses block() and refresh(); RecalculateCreditScore sets expireAfter(180); console.php combines onOneServer() and withoutOverlapping(); LeaseRepository adds a fencing token for correctness.
Kubernetes Lease and leader election Good to know
In plain words: Kubernetes has a built-in Lease object. Controllers update it to say "I am the leader until about now plus 15 seconds"; others wait for it to go stale and take over.
Common misunderstanding: "Kubernetes leader election guarantees one active leader." client-go's own documentation says: "This implementation does not guarantee that only one client is acting as a leader (a.k.a. fencing)."
Definition: Lease in API group coordination.k8s.io/v1, spec fields holderIdentity, leaseDurationSeconds ("a duration that candidates for a lease need to wait to force acquire it. This is measured against the time of last observed renewTime"), acquireTime, renewTime, leaseTransitions, and alpha strategy / preferredHolder for coordinated leader election. Kubelet heartbeats update spec.renewTime of a Lease per Node in kube-node-lease. client-go's leaderelection package uses LeaseDuration, RenewDeadline, RetryPeriod and ReleaseOnCancel; it is "tolerant to arbitrary clock skew, but is not tolerant to arbitrary clock skew rate".
1 pod-a: create Lease my-controller holderIdentity=pod-a renewTime=t0
2 pod-a: update renewTime every RetryPeriod
3 pod-b: sees renewTime change -> waits
4 pod-a: frozen; renewTime stops changing
5 pod-b: after LeaseDuration without change -> update holderIdentity=pod-b, leaseTransitions+1
6 pod-a: unfreezes, still acting until its RenewDeadline passes -> brief two-leader windowReal scenario: kube-controller-manager and kube-scheduler with --leader-elect; an operator with two replicas; a CronJob replacement controller that must run once per cluster. The full design lives in Leader Election; cluster basics in Containers & Kubernetes.
| Field | Meaning | Use as |
|---|---|---|
holderIdentity | Current holder | Who to page |
leaseDurationSeconds | How long others wait after last observed renewal | Failover time bound |
renewTime | Last renewal | Liveness signal |
leaseTransitions | Number of holder changes | Monotonic, usable as an epoch/fencing number |
Fix / how to use it: pass leaseTransitions (or a counter you increment on takeover) as an epoch to the systems the leader writes to, and have them reject lower epochs.
Observability Good to know
In plain words: measure how long locks are held, how often acquisition fails, how often renewal fails, and how often a fenced write is rejected. The last two are the ones that tell you exclusion was violated.
Common misunderstanding: "If there is a lock, there is nothing to monitor." Lost locks are silent: the holder that lost it keeps running unless something counts the 0 from compare-and-delete.
Definition: lock telemetry is the set of counters, histograms and logs around acquire, hold, renew, release and fenced write, labelled by lock name (bounded cardinality: the name, not the resource id).
Signals in a healthy vs unhealthy hour
1 acquire_total{result="ok"} 3600 acquire_total{result="busy"} 12 -> fine
2 hold_seconds p99 = 41 s with TTL 60 s -> headroom shrinking
3 renew_total{result="lost"} 3 -> exclusion was at risk 3 times
4 fenced_write_rejected_total 1 -> a paused holder was stopped: investigate GC/CPU
5 release_total{result="not_owner"} 2 -> work outlived the lock twiceReal scenario: an alert when release not_owner appears, because it means work ran without exclusion; a dashboard of hold_seconds against TTL; PostgreSQL pg_locks WHERE locktype = 'advisory' joined with pg_stat_activity; Redis TTL lock:* sampled; etcd etcdctl lease list and lease timetolive --keys; Kubernetes kubectl get lease -A.
| Signal | Source | Alert when |
|---|---|---|
| Hold time vs TTL | Client histogram | p99 above 50% of TTL |
| Acquire wait / busy rate | Client counter | Sudden rise: a stuck holder |
| Renewal failures | Watchdog | Any |
Release not_owner | Compare-and-delete reply 0 | Any |
| Fenced write rejected | Resource | Any (good catch, but investigate pauses) |
| Stale locks | pg_locks, TTL key, etcdctl lease list | Holder gone, lock present |
Fix / how to use it: the Go code returns ErrNotOwner and ErrStaleToken as typed errors so they can be counted; log the lock name, owner prefix and token, never the full owner value of a lock you still hold.
How the products compare Important
In plain words: pick a product by what it guarantees when a node dies and whether it gives you a token.
Common misunderstanding: "Our cloud's managed Redis is replicated, so locks survive failover." Replication in Redis is asynchronous; the Redis docs spell out the race: "The master crashes before the write to the key is transmitted to the replica ... Client B acquires the lock ... SAFETY VIOLATION!"
Definition: a comparison of what each product's lock does on failure.
Failover with async replication (Redis primary + replica)
1 A: SET lock A NX PX 30000 on primary -> OK
2 primary crashes before replicating
3 replica promoted (no key)
4 B: SET lock B NX PX 30000 -> OK: two holdersReal scenario: a team migrating from Redis locks to etcd after a failover double-ran a billing job; a Java shop choosing Redisson RFencedLock for its token; a PostgreSQL-only shop using lease rows.
| Product | Lock primitive | On holder crash | On store node failure | Token |
|---|---|---|---|---|
| Redis (single primary) | SET NX PX + Lua release | TTL expiry | Failover can lose the lock | INCR beside it, not failover-safe |
Redis + Redlock (Redsync, Redisson RedissonRedLock) | Majority of N masters | TTL expiry | Tolerates minority loss | None |
Redisson RLock / RFencedLock | Lua scripts, pub/sub wait, watchdog 30 s | Watchdog stops, TTL expiry | As Redis | RFencedLock yes |
| etcd | Lease + Mutex (concurrency) | Lease expiry (default 60 s session TTL) | Raft majority keeps state | Create revision |
| ZooKeeper / Curator | Ephemeral sequential znode | Session timeout | Zab quorum keeps state | zxid / version |
| Consul | Session + KV acquire | Session TTL/health check, lock-delay | Raft quorum | LockIndex |
| PostgreSQL | Advisory lock, lease row, SKIP LOCKED | Session end / expires_at | Primary failover: sync replication or loss | Lease fence_token |
| MySQL | GET_LOCK, SELECT ... FOR UPDATE SKIP LOCKED (8.0+) | Session end | As replication | Column you add |
| Kubernetes | Lease object | leaseDurationSeconds | etcd behind the API server | leaseTransitions |
DynamoDB (Laravel dynamodb lock) | Conditional put with expiry attribute | Expiry | Regional, managed | Column you add |
Fix / how to use it: match the table to the decision table.
Mechanics
Exact commands and replies
| Operation | Command / call | Success | Failure |
|---|---|---|---|
| Redis acquire | SET lock:{x} <rand> NX PX 30000 | OK | (nil) |
| Redis release (any version) | EVAL "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end" 1 lock:{x} <rand> | (integer) 1 | (integer) 0 |
| Redis release (8.4+) | DELEX lock:{x} IFEQ <rand> | (integer) 1 | (integer) 0 |
| Redis renew (8.4+) | SET lock:{x} <rand> IFEQ <rand> PX 30000 | OK | (nil) (key missing or value differs) |
| Redis renew (Lua) | if get == ARGV[1] then return pexpire(KEYS[1], ARGV[2]) | 1 | 0 |
| etcd lease | etcdctl lease grant 15 | lease 694d... granted with TTL(15s) | |
| etcd lock CLI | etcdctl lock /locks/job | prints the lock key, holds until exit | blocks |
| PostgreSQL try lock | SELECT pg_try_advisory_lock(42); | t | f |
| PostgreSQL unlock not held | SELECT pg_advisory_unlock(42); | t | f plus a WARNING |
| Consul acquire | PUT /v1/kv/locks/job?acquire=<session-id> | true | false |
| Kubernetes | kubectl get lease -n kube-system | holder, age |
Timing arithmetic
| Quantity | Formula | Example |
|---|---|---|
| Redlock validity | TTL - (T2 - T1) - drift | 10 000 - 52 - 100 = 9 848 ms |
| Safe work budget | validity - max expected pause - write latency | 9 848 - 2 000 - 200 = 7 648 ms |
| Renewal interval | TTL / 3 | 30 s TTL: every 10 s |
| Worst blocked time after crash | TTL (+ lock-delay on Consul) | 30 s; Consul 30 + 15 s |
| Kubernetes failover | about leaseDurationSeconds + retry period | client-go example 60 s / 30 s for 2x skew rate tolerance |
| Lock throughput, single Redis | 1 RTT acquire + 1 RTT release | 0.5 ms RTT: about 1 ms overhead per critical section (back-of-envelope) |
| etcd lock | Raft write (fsync on a majority) per acquire/release | Milliseconds; much lower ceiling than Redis (no figure measured here) |
Errors and messages
| Message | Where | Meaning | Action |
|---|---|---|---|
mutex: Locked by another session (concurrency.ErrLocked) | etcd TryLock | Busy | Skip or retry later |
mutex: session is expired (ErrSessionExpired) | etcd | Lease gone | New session; treat lock as lost |
Illuminate\Contracts\Cache\LockTimeoutException | Laravel block() | Not acquired in time | Skip, release in finally |
Illuminate\Cache\Limiters\LimiterTimeoutException | Laravel funnel() | No slot | Back off |
SQLSTATE 55P03 lock_not_available | PostgreSQL NOWAIT, lock_timeout | Row/table lock not available | Retry or skip |
SQLSTATE 40P01 deadlock_detected | PostgreSQL | Two lockers wait on each other | Retry; order lock acquisition (Deadlocks) |
CROSSSLOT Keys in request don't hash to the same slot | Redis Cluster | Lock and fence key in different slots | Use a hash tag {x} |
redis: nil (redis.Nil) | go-redis | SET NX not applied / script returned false | ErrNotAcquired |
Knobs
| Knob | Product | Default / range | Note |
|---|---|---|---|
PX / EX | Redis SET | none | Always set one |
appendfsync | Redis | everysec | Redlock docs: always for crash safety |
lockWatchdogTimeout | Redisson | 30 s | Watchdog lease length |
WithTTL | etcd concurrency | 60 s | Session lease |
| lock-delay | Consul session | 15 s, 0-60 s | Chubby-style safeguard |
| behavior | Consul session | release | or delete |
max_locks_per_transaction | PostgreSQL | 64 | Caps advisory locks with max_connections |
lock_timeout | PostgreSQL | 0 (off) | Bounds waits for row/table locks |
betweenBlockedAttemptsSleepFor | Laravel | 250 ms | Poll interval in block() |
withoutOverlapping($minutes) | Laravel scheduler | 1440 | Event mutex expiry |
leaseDurationSeconds | Kubernetes Lease | set by client | Takeover wait |
Go
Module academy/distributed-locking (go 1.24, github.com/redis/go-redis/v9 v9.17.0, go.etcd.io/etcd/client/v3 v3.6.8, github.com/alicebob/miniredis/v2 v2.41.0 for tests). Newer etcd and go-redis releases require go 1.26; these are the newest that keep go 1.24.
Before
The lock most teams write first. Each BUG comment is a row in Solving the classic problems.
// Package main shows the lock most teams write first. It compiles and
// usually works, which is why it survives code review. Every comment marked
// BUG is a failure mode explained on the page.
package main
import (
"context"
"log"
"time"
"github.com/redis/go-redis/v9"
)
func chargeMonthlyInvoices(ctx context.Context, rdb *redis.Client) error {
// BUG 1: check-then-act. Two workers can both see "not locked".
n, err := rdb.Exists(ctx, "lock:invoices").Result()
if err != nil {
return err
}
if n > 0 {
return nil
}
// BUG 2: a fixed value; any process can later delete this lock.
// BUG 3: the TTL (10 s) is a guess shorter than the job can take.
if err := rdb.Set(ctx, "lock:invoices", "1", 10*time.Second).Err(); err != nil {
return err
}
// BUG 4: unconditional DEL removes whoever holds the lock now,
// which after a GC pause or slow call is somebody else.
defer rdb.Del(ctx, "lock:invoices")
// BUG 5: no fencing token reaches the payment ledger, so a holder
// whose lock already expired still writes.
return chargeAll(ctx)
}
func chargeAll(ctx context.Context) error {
select {
case <-time.After(30 * time.Second): // longer than the TTL
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func main() {
rdb := redis.NewClient(&redis.Options{Addr: "127.0.0.1:6379"})
if err := chargeMonthlyInvoices(context.Background(), rdb); err != nil {
log.Fatal(err)
}
}After
A Redis lock with an atomic acquire that also issues a fencing token, Lua compare-and-delete release, compare-and-pexpire renewal and a watchdog that cancels work on loss:
// Package redislock is a single-instance Redis lock done properly:
// SET NX PX with a random owner token, compare-and-delete release,
// compare-and-pexpire renewal, a watchdog that reports loss, and a
// fencing token issued atomically with the acquisition.
//
// It is an efficiency lock on its own. It becomes safe for correctness
// only when the protected resource checks the fencing token (see package
// fencing) and the token counter survives Redis failover.
package redislock
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"time"
"github.com/redis/go-redis/v9"
)
// ErrNotAcquired means another owner holds the lock right now.
var ErrNotAcquired = errors.New("redislock: not acquired")
// ErrNotOwner means the key expired or now belongs to someone else.
var ErrNotOwner = errors.New("redislock: lock not held by this owner")
// acquireScript sets the lock only if absent and, in the same atomic step,
// increments the fencing counter. KEYS[1]=lock key, KEYS[2]=fence key,
// ARGV[1]=owner token, ARGV[2]=ttl in ms. Returns the token or false.
var acquireScript = redis.NewScript(`
if redis.call("SET", KEYS[1], ARGV[1], "NX", "PX", ARGV[2]) then
return redis.call("INCR", KEYS[2])
end
return false
`)
// releaseScript deletes the key only if it still holds our owner token.
var releaseScript = redis.NewScript(`
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
end
return 0
`)
// refreshScript extends the TTL only if we still own the key.
var refreshScript = redis.NewScript(`
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("PEXPIRE", KEYS[1], ARGV[2])
end
return 0
`)
// Client creates locks against one Redis primary.
type Client struct {
rdb redis.Scripter
}
// New wraps any go-redis client (Client, Ring member, or Cluster when the
// lock and fence keys share a hash tag such as {invoices}).
func New(rdb redis.Scripter) *Client { return &Client{rdb: rdb} }
// Lock is one acquisition. Token is the fencing token to send with every
// write to the protected resource.
type Lock struct {
c *Client
key string
owner string
ttl time.Duration
Token int64
}
// Owner returns the random value stored in the key.
func (l *Lock) Owner() string { return l.owner }
func newOwner() (string, error) {
b := make([]byte, 16) // 128 bits; Redis docs suggest 20 bytes from /dev/urandom
if _, err := rand.Read(b); err != nil {
return "", err
}
return hex.EncodeToString(b), nil
}
func fenceKey(key string) string { return key + ":fence" }
// TryAcquire makes one attempt and returns ErrNotAcquired if the lock is held.
func (c *Client) TryAcquire(ctx context.Context, key string, ttl time.Duration) (*Lock, error) {
owner, err := newOwner()
if err != nil {
return nil, err
}
res, err := acquireScript.Run(ctx, c.rdb, []string{key, fenceKey(key)}, owner, ttl.Milliseconds()).Int64()
if errors.Is(err, redis.Nil) {
return nil, ErrNotAcquired
}
if err != nil {
return nil, fmt.Errorf("redislock: acquire %s: %w", key, err)
}
return &Lock{c: c, key: key, owner: owner, ttl: ttl, Token: res}, nil
}
// Acquire retries with a fixed interval until ctx ends. Callers that need
// fairness should use a consensus lock with a queue (etcd, ZooKeeper).
func (c *Client) Acquire(ctx context.Context, key string, ttl, retry time.Duration) (*Lock, error) {
t := time.NewTicker(retry)
defer t.Stop()
for {
l, err := c.TryAcquire(ctx, key, ttl)
if !errors.Is(err, ErrNotAcquired) {
return l, err
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-t.C:
}
}
}
// Release deletes the key only if this owner still holds it.
func (l *Lock) Release(ctx context.Context) error {
n, err := releaseScript.Run(ctx, l.c.rdb, []string{l.key}, l.owner).Int64()
if err != nil {
return fmt.Errorf("redislock: release %s: %w", l.key, err)
}
if n == 0 {
return ErrNotOwner
}
return nil
}
// Refresh extends the TTL to the original duration if still owned.
func (l *Lock) Refresh(ctx context.Context) error {
n, err := refreshScript.Run(ctx, l.c.rdb, []string{l.key}, l.owner, l.ttl.Milliseconds()).Int64()
if err != nil {
return fmt.Errorf("redislock: refresh %s: %w", l.key, err)
}
if n == 0 {
return ErrNotOwner
}
return nil
}
// KeepAlive starts a watchdog that refreshes every interval (use ttl/3).
// The returned context is cancelled as soon as a refresh fails or the
// remaining safe time runs out, so work started with it stops. A paused
// process cannot react to the cancel; that is what the fencing token is for.
func (l *Lock) KeepAlive(parent context.Context, interval time.Duration) (context.Context, context.CancelFunc) {
ctx, cancel := context.WithCancelCause(parent)
go func() {
t := time.NewTicker(interval)
defer t.Stop()
deadline := time.Now().Add(l.ttl)
for {
select {
case <-ctx.Done():
return
case now := <-t.C:
if now.After(deadline) {
cancel(fmt.Errorf("%w: lease ran out before renewal", ErrNotOwner))
return
}
rctx, rcancel := context.WithTimeout(ctx, interval)
err := l.Refresh(rctx)
rcancel()
if err != nil {
cancel(err)
return
}
deadline = now.Add(l.ttl)
}
}
}()
return ctx, func() { cancel(context.Canceled) }
}Tests with miniredis (in-memory Redis with Lua support; FastForward expires keys without sleeping):
package redislock
import (
"context"
"errors"
"testing"
"time"
"github.com/alicebob/miniredis/v2"
"github.com/redis/go-redis/v9"
)
func setup(t *testing.T) (*miniredis.Miniredis, *Client) {
t.Helper()
mr := miniredis.RunT(t)
rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
t.Cleanup(func() { _ = rdb.Close() })
return mr, New(rdb)
}
func TestMutualExclusionAndMonotonicTokens(t *testing.T) {
mr, c := setup(t)
ctx := context.Background()
a, err := c.TryAcquire(ctx, "lock:{invoices}", 10*time.Second)
if err != nil {
t.Fatal(err)
}
if _, err := c.TryAcquire(ctx, "lock:{invoices}", 10*time.Second); !errors.Is(err, ErrNotAcquired) {
t.Fatalf("second acquire: want ErrNotAcquired, got %v", err)
}
mr.FastForward(11 * time.Second) // a's lease expires (a GC pause, say)
b, err := c.TryAcquire(ctx, "lock:{invoices}", 10*time.Second)
if err != nil {
t.Fatal(err)
}
if b.Token <= a.Token {
t.Fatalf("tokens must increase: a=%d b=%d", a.Token, b.Token)
}
// a wakes up and tries to release: it must not delete b's lock.
if err := a.Release(ctx); !errors.Is(err, ErrNotOwner) {
t.Fatalf("stale release: want ErrNotOwner, got %v", err)
}
if got, _ := mr.Get("lock:{invoices}"); got != b.Owner() {
t.Fatalf("b's lock was removed")
}
if err := b.Release(ctx); err != nil {
t.Fatal(err)
}
}
func TestRefreshOnlyByOwner(t *testing.T) {
mr, c := setup(t)
ctx := context.Background()
l, err := c.TryAcquire(ctx, "lock:{report}", 3*time.Second)
if err != nil {
t.Fatal(err)
}
mr.FastForward(2 * time.Second)
if err := l.Refresh(ctx); err != nil {
t.Fatal(err)
}
if ttl := mr.TTL("lock:{report}"); ttl != 3*time.Second {
t.Fatalf("ttl after refresh = %v", ttl)
}
mr.FastForward(4 * time.Second)
if err := l.Refresh(ctx); !errors.Is(err, ErrNotOwner) {
t.Fatalf("refresh after expiry: want ErrNotOwner, got %v", err)
}
}
func TestWatchdogCancelsWorkWhenLockIsLost(t *testing.T) {
mr, c := setup(t)
l, err := c.TryAcquire(context.Background(), "lock:{export}", time.Second)
if err != nil {
t.Fatal(err)
}
work, stop := l.KeepAlive(context.Background(), 20*time.Millisecond)
defer stop()
time.Sleep(60 * time.Millisecond)
if work.Err() != nil {
t.Fatalf("watchdog cancelled while still owner: %v", context.Cause(work))
}
mr.Del("lock:{export}") // an operator, failover or expiry took it away
select {
case <-work.Done():
if !errors.Is(context.Cause(work), ErrNotOwner) {
t.Fatalf("cause = %v", context.Cause(work))
}
case <-time.After(time.Second):
t.Fatal("watchdog did not notice the lost lock")
}
}
func TestAcquireWaitsThenTimesOut(t *testing.T) {
_, c := setup(t)
if _, err := c.TryAcquire(context.Background(), "lock:{x}", 5*time.Second); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
if _, err := c.Acquire(ctx, "lock:{x}", 5*time.Second, 10*time.Millisecond); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("want DeadlineExceeded, got %v", err)
}
}The storage side that enforces the token, in memory and as one SQL statement:
// Package fencing is the half of distributed locking that lives in the
// storage layer: every write carries the fencing token of the lock under
// which it was made, and the store rejects any token lower than the highest
// one it has already accepted for that resource.
package fencing
import (
"context"
"database/sql"
"errors"
"fmt"
"sync"
)
// ErrStaleToken means a newer lock holder has already written.
var ErrStaleToken = errors.New("fencing: stale token rejected")
// MemStore is an in-process reference implementation used by tests and the demo.
type MemStore struct {
mu sync.Mutex
data map[string]string
high map[string]int64
}
// NewMemStore returns an empty store.
func NewMemStore() *MemStore {
return &MemStore{data: map[string]string{}, high: map[string]int64{}}
}
// Write stores value for resource if token >= the highest token seen.
// Equal tokens are allowed so one holder can write several times.
func (s *MemStore) Write(_ context.Context, resource string, token int64, value string) error {
s.mu.Lock()
defer s.mu.Unlock()
if token < s.high[resource] {
return fmt.Errorf("%w: resource=%s token=%d highest=%d", ErrStaleToken, resource, token, s.high[resource])
}
s.high[resource] = token
s.data[resource] = value
return nil
}
// Read returns the current value.
func (s *MemStore) Read(resource string) string {
s.mu.Lock()
defer s.mu.Unlock()
return s.data[resource]
}
// SQLStore enforces the same rule in PostgreSQL with one conditional UPDATE.
// Schema (see sql/schema.sql):
//
// CREATE TABLE documents (id text PRIMARY KEY, body text NOT NULL,
// fence_token bigint NOT NULL DEFAULT 0);
type SQLStore struct {
DB *sql.DB
}
// Write is atomic: the comparison and the update happen in one statement,
// so there is no check-then-act window between them.
func (s SQLStore) Write(ctx context.Context, resource string, token int64, value string) error {
res, err := s.DB.ExecContext(ctx, `
UPDATE documents
SET body = $3, fence_token = $2
WHERE id = $1 AND fence_token <= $2`, resource, token, value)
if err != nil {
return fmt.Errorf("fencing: write %s: %w", resource, err)
}
n, err := res.RowsAffected()
if err != nil {
return err
}
if n == 0 {
return fmt.Errorf("%w: resource=%s token=%d", ErrStaleToken, resource, token)
}
return nil
}package fencing
import (
"context"
"errors"
"testing"
)
// The Kleppmann sequence: client 1 gets token 33, pauses; client 2 gets 34
// and writes; client 1 wakes up and writes with 33, which must be rejected.
func TestPausedHolderIsFencedOff(t *testing.T) {
s := NewMemStore()
ctx := context.Background()
if err := s.Write(ctx, "file-42", 34, "written by client 2"); err != nil {
t.Fatal(err)
}
err := s.Write(ctx, "file-42", 33, "written by client 1 after GC pause")
if !errors.Is(err, ErrStaleToken) {
t.Fatalf("want ErrStaleToken, got %v", err)
}
if got := s.Read("file-42"); got != "written by client 2" {
t.Fatalf("stale write landed: %q", got)
}
}
func TestSameHolderMayWriteTwice(t *testing.T) {
s := NewMemStore()
ctx := context.Background()
for _, v := range []string{"step 1", "step 2"} {
if err := s.Write(ctx, "r", 7, v); err != nil {
t.Fatal(err)
}
}
if err := s.Write(ctx, "r", 8, "next holder"); err != nil {
t.Fatal(err)
}
}An etcd lock with clientv3/concurrency, the create revision as token and a guarded Txn:
// Package etcdlock uses etcd's concurrency package: a Session owns a lease
// that the client keeps alive, a Mutex is a key under a prefix whose
// create revision orders the waiters, and IsOwner() is a Txn comparison
// that makes a write conditional on still holding the lock.
package etcdlock
import (
"context"
"errors"
"fmt"
clientv3 "go.etcd.io/etcd/client/v3"
"go.etcd.io/etcd/client/v3/concurrency"
)
// ErrLostOwnership means the guarded Txn found the lock key gone.
var ErrLostOwnership = errors.New("etcdlock: no longer the owner")
// RunExclusive acquires the named lock, runs fn with a fencing token
// (the create revision of our lock key, strictly increasing across
// holders) and releases. ttlSeconds is the session lease TTL.
func RunExclusive(ctx context.Context, cli *clientv3.Client, name string, ttlSeconds int,
fn func(ctx context.Context, token int64, guard clientv3.Cmp) error) error {
sess, err := concurrency.NewSession(cli, concurrency.WithTTL(ttlSeconds))
if err != nil {
return fmt.Errorf("etcdlock: session: %w", err)
}
defer sess.Close() // revokes the lease, deleting our key if still present
m := concurrency.NewMutex(sess, "/locks/"+name)
if err := m.Lock(ctx); err != nil { // waits behind lower create revisions
return fmt.Errorf("etcdlock: lock %s: %w", name, err)
}
defer func() { _ = m.Unlock(context.WithoutCancel(ctx)) }()
// The session's Done channel closes when the keep-alive stops (lease
// expired or revoked). Work must stop then.
work, cancel := context.WithCancel(ctx)
defer cancel()
go func() {
select {
case <-sess.Done():
cancel()
case <-work.Done():
}
}()
// Fencing token: the create revision of our own lock key. etcd's store
// revision is a cluster-wide counter, so a later holder always has a
// larger value.
got, err := cli.Get(work, m.Key())
if err != nil {
return fmt.Errorf("etcdlock: read own key: %w", err)
}
if len(got.Kvs) == 0 {
return ErrLostOwnership
}
return fn(work, got.Kvs[0].CreateRevision, m.IsOwner())
}
// GuardedPut writes key=value in etcd only if the lock is still ours.
// This is fencing inside etcd itself; for an external store pass the token.
func GuardedPut(ctx context.Context, cli *clientv3.Client, guard clientv3.Cmp, key, value string) error {
resp, err := cli.Txn(ctx).If(guard).Then(clientv3.OpPut(key, value)).Commit()
if err != nil {
return fmt.Errorf("etcdlock: txn: %w", err)
}
if !resp.Succeeded {
return ErrLostOwnership
}
return nil
}
// TryOnce shows the non-blocking form: concurrency.ErrLocked when busy.
func TryOnce(ctx context.Context, sess *concurrency.Session, name string) (*concurrency.Mutex, error) {
m := concurrency.NewMutex(sess, "/locks/"+name)
if err := m.TryLock(ctx); err != nil {
if errors.Is(err, concurrency.ErrLocked) {
return nil, fmt.Errorf("etcdlock: %s busy: %w", name, err)
}
return nil, err
}
return m, nil
}PostgreSQL advisory lock on a pinned connection, a lease row with a fencing column, and a SKIP LOCKED work claim:
// Package pglock shows the two PostgreSQL tools for cross-process locking:
// a session-level advisory lock pinned to one connection, and a lease row
// with an expiry and a fencing counter that survives restarts.
package pglock
import (
"context"
"database/sql"
"errors"
"fmt"
"hash/fnv"
"time"
)
// ErrBusy means another session or worker holds the lock or lease.
var ErrBusy = errors.New("pglock: busy")
// AdvisoryKey maps a name to the bigint key space of pg_advisory_lock.
// Collisions are possible in theory; namespace names ("billing:run").
func AdvisoryKey(name string) int64 {
h := fnv.New64a()
_, _ = h.Write([]byte(name))
return int64(h.Sum64())
}
// WithAdvisoryLock runs fn while holding a session-level advisory lock.
// The lock belongs to the database session, so it must be taken, used and
// released on the same *sql.Conn; on a pooled *sql.DB the unlock could run
// on a different connection and silently do nothing.
func WithAdvisoryLock(ctx context.Context, db *sql.DB, name string, fn func(ctx context.Context, conn *sql.Conn) error) error {
conn, err := db.Conn(ctx)
if err != nil {
return err
}
defer conn.Close()
key := AdvisoryKey(name)
var ok bool
if err := conn.QueryRowContext(ctx, `SELECT pg_try_advisory_lock($1)`, key).Scan(&ok); err != nil {
return fmt.Errorf("pglock: try lock: %w", err)
}
if !ok {
return ErrBusy
}
defer func() {
// Use a fresh context so a cancelled ctx still unlocks.
uctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer cancel()
_, _ = conn.ExecContext(uctx, `SELECT pg_advisory_unlock($1)`, key)
}()
return fn(ctx, conn)
}
// Lease is a row in job_leases (see sql/schema.sql).
type Lease struct {
Name string
Holder string
Token int64
Expires time.Time
}
// ClaimLease takes the lease if it is free or expired, in one statement.
// The database clock (now()) decides expiry, so client clocks do not matter.
// fence_token increments on every successful claim and is the fencing token.
func ClaimLease(ctx context.Context, db *sql.DB, name, holder string, ttl time.Duration) (*Lease, error) {
l := &Lease{Name: name, Holder: holder}
err := db.QueryRowContext(ctx, `
INSERT INTO job_leases AS l (name, holder, fence_token, expires_at)
VALUES ($1, $2, 1, now() + make_interval(secs => $3))
ON CONFLICT (name) DO UPDATE
SET holder = EXCLUDED.holder,
fence_token = l.fence_token + 1,
expires_at = EXCLUDED.expires_at
WHERE l.expires_at < now() OR l.holder = EXCLUDED.holder
RETURNING fence_token, expires_at`, name, holder, ttl.Seconds()).Scan(&l.Token, &l.Expires)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrBusy
}
if err != nil {
return nil, fmt.Errorf("pglock: claim %s: %w", name, err)
}
return l, nil
}
// RenewLease extends the lease only for the same holder and token.
func RenewLease(ctx context.Context, db *sql.DB, l *Lease, ttl time.Duration) error {
res, err := db.ExecContext(ctx, `
UPDATE job_leases
SET expires_at = now() + make_interval(secs => $4)
WHERE name = $1 AND holder = $2 AND fence_token = $3 AND expires_at > now()`,
l.Name, l.Holder, l.Token, ttl.Seconds())
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return ErrBusy
}
return nil
}
// ClaimJobs is the SKIP LOCKED work claim: each worker gets different rows
// and nobody waits. The row lock lasts only for the transaction, so the
// claim is recorded in claimed_by/claimed_until for long jobs.
func ClaimJobs(ctx context.Context, db *sql.DB, worker string, n int, ttl time.Duration) ([]int64, error) {
rows, err := db.QueryContext(ctx, `
UPDATE jobs SET claimed_by = $1, claimed_until = now() + make_interval(secs => $3)
WHERE id IN (
SELECT id FROM jobs
WHERE done_at IS NULL AND (claimed_until IS NULL OR claimed_until < now())
ORDER BY id
LIMIT $2
FOR UPDATE SKIP LOCKED)
RETURNING id`, worker, n, ttl.Seconds())
if err != nil {
return nil, err
}
defer rows.Close()
var ids []int64
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
return nil, err
}
ids = append(ids, id)
}
return ids, rows.Err()
}A single-process replay of the paused-holder scenario (used in the lab):
// Command demo replays the GC-pause scenario in one process with an
// embedded miniredis: lease expiry, a second holder, a stale release and
// a stale write, with and without fencing.
package main
import (
"context"
"errors"
"fmt"
"time"
"github.com/alicebob/miniredis/v2"
"github.com/redis/go-redis/v9"
"academy/distributed-locking/fencing"
"academy/distributed-locking/redislock"
)
func main() {
mr, err := miniredis.Run()
if err != nil {
panic(err)
}
defer mr.Close()
rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
defer rdb.Close()
locks := redislock.New(rdb)
store := fencing.NewMemStore()
ctx := context.Background()
c1, _ := locks.TryAcquire(ctx, "lock:{file-42}", 10*time.Second)
fmt.Printf("1 client1 acquired, token=%d\n", c1.Token)
mr.FastForward(15 * time.Second) // client1 is paused for 15 s; the lease expires
fmt.Println("2 client1 paused 15s; lease (10s) expired")
c2, _ := locks.TryAcquire(ctx, "lock:{file-42}", 10*time.Second)
fmt.Printf("3 client2 acquired, token=%d\n", c2.Token)
fmt.Printf("4 client2 write: %v\n", store.Write(ctx, "file-42", c2.Token, "v2"))
err = store.Write(ctx, "file-42", c1.Token, "v1-stale")
fmt.Printf("5 client1 wakes, write with token=%d: %v\n", c1.Token, err)
fmt.Printf("6 client1 release: %v\n", c1.Release(ctx))
fmt.Printf("7 stored value=%q, stale write rejected=%t\n", store.Read("file-42"), errors.Is(err, fencing.ErrStaleToken))
fmt.Printf("8 client2 release: %v\n", c2.Release(ctx))
}The Go angle
sync.Mutexis in-process only; there is no distributed lock in the standard library.context.WithCancelCause(Go 1.20+) lets a watchdog cancel work with a reason, read back withcontext.Cause.- go-redis:
redis.NewScript(src).Run(ctx, rdb, keys, args...)triesEVALSHAand falls back toEVAL; a Luafalsereply becomesredis.Nil.rdb.SetNX(ctx, key, val, ttl)sendsSET key val PX ttl NXwhen the TTL is set, but the script form lets you add the fenceINCRatomically. - Redsync (
github.com/go-redsync/redsync/v4) is the Go Redlock implementation listed in the Redis docs; it returns no fencing token. - etcd:
concurrency.NewSession,NewMutex,Lock/TryLock/Unlock,IsOwner(),Session.Done(),NewElectionfor leader election. The client pulls in gRPC; keep it out of hot binaries that do not need it. database/sql: a session-level advisory lock needsdb.Conn(ctx);*sql.DBmay run each statement on a different pooled connection.pgxusers can hold a*pgxpool.Connthe same way.- Measure elapsed time with
time.Since(start): it uses the monotonic clock reading, immune to wall-clock steps. - Test with
miniredis(no server needed), and for etcd withgo.etcd.io/etcd/tests/v3/integrationor a fake behind an interface.
Laravel
Before
A hand-rolled cache flag: check-then-act, no owner, guessed TTL, unconditional delete.
<?php
namespace App\Console\Commands;
use App\Services\Billing;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
// The hand-rolled lock: every line here is a bug described on the page.
class ChargeMonthlyInvoices extends Command
{
protected $signature = 'billing:charge';
public function handle(Billing $billing): int
{
// check-then-act: two servers can both pass this line
if (Cache::has('billing-lock')) {
return self::SUCCESS;
}
// fixed value, guessed TTL shorter than the job, no owner
Cache::put('billing-lock', true, 60);
$billing->chargeEveryone(); // may run for minutes
// deletes whoever holds the lock now, maybe another server
Cache::forget('billing-lock');
return self::SUCCESS;
}
}After
An Artisan command with block(), refresh() after each batch and release() in finally:
<?php
namespace App\Console\Commands;
use App\Services\Billing;
use Illuminate\Console\Command;
use Illuminate\Contracts\Cache\LockTimeoutException;
use Illuminate\Support\Facades\Cache;
// Cache::lock: atomic acquire (SET NX EX on Redis), random owner token,
// owner-checked release, refresh() as a manual watchdog.
class ChargeMonthlyInvoices extends Command
{
protected $signature = 'billing:charge';
public function handle(Billing $billing): int
{
$lock = Cache::store('redis')->lock('billing:monthly-run', 120);
try {
// wait up to 5 s, retrying every 200 ms (default 250 ms)
$lock->betweenBlockedAttemptsSleepFor(200)->block(5);
} catch (LockTimeoutException) {
$this->warn('Another server is charging; skipping.');
return self::SUCCESS;
}
try {
foreach ($billing->customerBatches(500) as $batch) {
$billing->chargeBatch($batch);
// Extend to another 120 s only if we still own the lock.
if (! $lock->refresh()) {
$this->error('Lock lost; stopping before the next batch.');
return self::FAILURE;
}
}
} finally {
$lock->release(); // no-op if the owner token no longer matches
}
return self::SUCCESS;
}
}Acquire in a request, release in a job with the owner token:
<?php
namespace App\Http\Controllers;
use App\Jobs\BuildExport;
use App\Models\Export;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Cache;
// Acquire in the request, release in the queued job: pass the owner token.
class StartExport
{
public function __invoke(Export $export): JsonResponse
{
$lock = Cache::lock("export:{$export->id}", 600);
if (! $lock->get()) {
return response()->json(['status' => 'already_running'], 409);
}
BuildExport::dispatch($export, $lock->owner());
return response()->json(['status' => 'queued'], 202);
}
}<?php
namespace App\Jobs;
use App\Models\Export;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Cache;
class BuildExport implements ShouldQueue
{
use Queueable;
public function __construct(public Export $export, public string $owner) {}
public function handle(): void
{
$lock = Cache::restoreLock("export:{$this->export->id}", $this->owner);
try {
if (! $lock->isOwnedByCurrentProcess()) {
return; // the 600 s lock expired before the job started
}
$this->export->build();
} finally {
$lock->release();
}
}
}Per-key job exclusion with an expiry:
<?php
namespace App\Jobs;
use App\Models\User;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Middleware\WithoutOverlapping;
// One job per user at a time, across all workers.
class RecalculateCreditScore implements ShouldQueue
{
use Queueable;
public int $tries = 10; // overlap releases count as attempts
public function __construct(public User $user) {}
public function middleware(): array
{
return [
(new WithoutOverlapping($this->user->id))
->releaseAfter(30) // busy: try again in 30 s
->expireAfter(180), // never leave a forever-lock if the worker dies
];
}
public function handle(): void
{
$this->user->recalculateCreditScore();
}
}Scheduler deduplication in routes/console.php:
<?php
use Illuminate\Support\Facades\Schedule;
// routes/console.php: scheduler deduplication across servers.
// Requires a shared database, memcached, dynamodb or redis cache store.
Schedule::useCache('redis');
Schedule::command('billing:charge')
->dailyAt('02:00')
->onOneServer() // one server per scheduled minute
->withoutOverlapping(30); // and never two runs at once; lock expires after 30 minutes
Schedule::command('reports:refresh')
->everyFiveMinutes()
->onOneServer()
->withoutOverlapping(10)
->runInBackground();A database lease with lockForUpdate and a fenced write, plus its migration:
<?php
namespace App\Locking;
use Illuminate\Support\Facades\DB;
// A database lease with a fencing token, using lockForUpdate for the claim.
final class LeaseRepository
{
/** @return int|null fencing token, or null when busy */
public function claim(string $name, string $holder, int $ttlSeconds): ?int
{
return DB::transaction(function () use ($name, $holder, $ttlSeconds): ?int {
DB::table('job_leases')->insertOrIgnore([
'name' => $name,
'holder' => '',
'fence_token' => 0,
'expires_at' => now()->subSecond(),
]);
// SELECT ... FOR UPDATE: concurrent claimers queue on this row.
$row = DB::table('job_leases')->where('name', $name)->lockForUpdate()->first();
$free = $row->holder === $holder || now()->greaterThan($row->expires_at);
if (! $free) {
return null;
}
$token = $row->fence_token + 1;
DB::table('job_leases')->where('name', $name)->update([
'holder' => $holder,
'fence_token' => $token,
'expires_at' => now()->addSeconds($ttlSeconds),
]);
return $token;
});
}
/** The protected write: rejected when a newer holder already wrote. */
public function fencedWrite(string $documentId, int $token, string $body): bool
{
return DB::table('documents')
->where('id', $documentId)
->where('fence_token', '<=', $token)
->update(['body' => $body, 'fence_token' => $token]) === 1;
}
}<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('job_leases', function (Blueprint $table) {
$table->string('name')->primary();
$table->string('holder');
$table->unsignedBigInteger('fence_token');
$table->timestamp('expires_at');
});
Schema::table('documents', function (Blueprint $table) {
$table->unsignedBigInteger('fence_token')->default(0);
});
}
public function down(): void
{
Schema::dropIfExists('job_leases');
Schema::table('documents', fn (Blueprint $table) => $table->dropColumn('fence_token'));
}
};The Laravel angle
Cache::lockis implemented per driver:RedisLock(SET NX EX, Lua release and refresh),DatabaseLock(cache_lockstable: insert-or-ignore, then update where owner matches or expired; random pruning with lottery[2, 100]),MemcachedLock(add),DynamoDbLock(conditional put),FileLock,ArrayLock(tests only, per process).- All of them are efficiency locks: none issues a fencing token. For correctness, add a token from a lease row as in
LeaseRepository, or make the write itself conditional. Cache::lock('name')without seconds means no expiry on redis (setnx) and 86 400 s on the database driver; always pass seconds.- The scheduler's
onOneServerandwithoutOverlappinguse the cache store fromSchedule::useCache(); with thearrayorfiledriver they do not coordinate across servers. - Job middleware:
WithoutOverlappingwithexpireAfter();ShouldBeUniquejobs (uniqueness while queued) also use atomic locks: see Laravel Queue Internals. - In tests, the
arraycache driver supports locks, soCache::lockcode runs without Redis.
SQL schema and statements
The job_leases lease table, the fenced documents update, advisory locks, the SKIP LOCKED claim and the version-column CAS:
-- PostgreSQL schema and statements for database-backed locks, leases and
-- fenced writes. Tested shape: PostgreSQL 13+ (make_interval, ON CONFLICT).
-- 1. Lease table: one row per named lock; fence_token is the fencing token.
CREATE TABLE job_leases (
name text PRIMARY KEY,
holder text NOT NULL,
fence_token bigint NOT NULL,
expires_at timestamptz NOT NULL
);
-- Claim: succeeds if the row is new, expired, or already ours. now() is the
-- database clock, so client clock skew does not decide who wins.
INSERT INTO job_leases AS l (name, holder, fence_token, expires_at)
VALUES ('billing:monthly-run', 'worker-a:4711', 1, now() + interval '30 seconds')
ON CONFLICT (name) DO UPDATE
SET holder = EXCLUDED.holder,
fence_token = l.fence_token + 1,
expires_at = EXCLUDED.expires_at
WHERE l.expires_at < now() OR l.holder = EXCLUDED.holder
RETURNING fence_token, expires_at; -- zero rows = busy
-- Renew (heartbeat): only the current holder with the current token.
UPDATE job_leases
SET expires_at = now() + interval '30 seconds'
WHERE name = 'billing:monthly-run' AND holder = 'worker-a:4711'
AND fence_token = 42 AND expires_at > now();
-- Release early.
DELETE FROM job_leases
WHERE name = 'billing:monthly-run' AND holder = 'worker-a:4711' AND fence_token = 42;
-- 2. The protected resource enforces the token (the fencing check).
CREATE TABLE documents (
id text PRIMARY KEY,
body text NOT NULL,
fence_token bigint NOT NULL DEFAULT 0
);
UPDATE documents
SET body = 'new body', fence_token = 42
WHERE id = 'file-42' AND fence_token <= 42; -- 0 rows = stale holder, reject
-- 3. Advisory locks: session level (explicit unlock) and transaction level.
-- hashtextextended() is an internal PostgreSQL hash (11+); computing the bigint
-- key in the application (see pglock.AdvisoryKey) works just as well.
SELECT pg_try_advisory_lock(hashtextextended('billing:monthly-run', 0)); -- true / false
SELECT pg_advisory_unlock(hashtextextended('billing:monthly-run', 0)); -- true if held
BEGIN;
SELECT pg_advisory_xact_lock(hashtextextended('tenant:17:reindex', 0)); -- waits; released at COMMIT/ROLLBACK
-- ... work ...
COMMIT;
-- Who holds what (advisory locks show locktype = 'advisory').
SELECT l.pid, l.granted, l.classid, l.objid, a.application_name, a.state, now() - a.xact_start AS xact_age
FROM pg_locks l JOIN pg_stat_activity a USING (pid)
WHERE l.locktype = 'advisory';
-- 4. Work claim with SKIP LOCKED: competing workers take different rows.
CREATE TABLE jobs (
id bigserial PRIMARY KEY,
payload jsonb NOT NULL,
claimed_by text,
claimed_until timestamptz,
done_at timestamptz
);
CREATE INDEX jobs_pending ON jobs (id) WHERE done_at IS NULL;
UPDATE jobs SET claimed_by = 'worker-b', claimed_until = now() + interval '5 minutes'
WHERE id IN (
SELECT id FROM jobs
WHERE done_at IS NULL AND (claimed_until IS NULL OR claimed_until < now())
ORDER BY id
LIMIT 10
FOR UPDATE SKIP LOCKED)
RETURNING id;
-- 5. Optimistic alternative: no lock at all, a version column (CAS).
UPDATE accounts SET balance = balance - 100, version = version + 1
WHERE id = 7 AND version = 12; -- 0 rows = someone else won; re-read and retry-- The one statement that makes a write fenced (PostgreSQL, MySQL, SQLite alike)
UPDATE documents SET body = $3, fence_token = $2
WHERE id = $1 AND fence_token <= $2;
-- rows affected = 0 -> a newer holder already wrote; abort this holder's workSolving the classic problems
| Problem | Solution | How | Advantage | Cost / limit |
|---|---|---|---|---|
| Unlocking someone else's lock (unlock other's lock) | Owner token + compare-and-delete | Lua script or DELEX IFEQ; Laravel release() | Never frees another holder | Must treat reply 0 as "lost" |
| Long GC past TTL | Fencing token | Resource rejects lower tokens | Works for any pause length | Resource must cooperate |
| Lock held across network calls | Shrink the critical section | Prepare outside, lock only the commit; or CAS | Shorter hold, fewer expiries | Redesign |
| Lock without fencing | Add a token | Lease row counter, etcd revision, zxid | Turns an efficiency lock into a correct one | Needs a linearizable counter |
| Non-atomic check-then-act | One atomic command | SET NX PX, INSERT ... ON CONFLICT, UPDATE ... WHERE | No race window | None |
| Cron on N servers | Scheduler lock | Laravel onOneServer(), Kubernetes CronJob, leader-only scheduler | Simple | Efficiency only |
| Lock lost on Redis failover | Consensus store or accept | etcd/ZooKeeper; or idempotent work | Survives node loss | Latency, operations |
| Forever lock after a crash | Expiry everywhere | TTL on every lock; expireAfter(); leases | Self-healing | TTL must exceed work time |
| Thundering herd on release | Ordered waiters | ZooKeeper predecessor watch, etcd revision order | One wakes, not all | Consensus store |
Unlocking someone else's lock
A plain DEL after a job that took longer than the TTL deletes the next holder's key, and a third process gets in. Fix: random owner per acquisition; release with compare-and-delete; count the "not owner" result as an incident, because it proves your work ran unprotected for some time. The Go Release returns ErrNotOwner; the test TestMutualExclusionAndMonotonicTokens asserts that a stale release leaves the new holder's key intact.
Long GC (or any pause) past the TTL
No TTL is long enough for every pause, and the watchdog pauses with the process. Fix: fencing at the resource (documents.fence_token), and alerting on rejections. Reduce the frequency with GC tuning, CPU limits that do not throttle, no swap, but never rely on that for correctness.
Lock held across network calls
1 acquire lock
2 call payment provider (p99 4 s, timeout 30 s) <-- hold time now set by a third party
3 write result
4 releaseFix: do the slow call outside the lock with an idempotency key (API Idempotency), then take the lock (or better, a conditional write) only to record the result. If the call must be inside, set its timeout well below the TTL and check the lock (renewal) before writing, plus fencing.
Lock without fencing
Every efficiency lock is "a lock without fencing". It becomes a bug when the work is correctness work. Fix: issue the token from a linearizable source (lease row, etcd revision, ZooKeeper zxid, Consul LockIndex) and enforce it in the same statement as the write. With Redis only, the INCR in acquireScript is monotonic until a failover loses writes; document that limit.
Non-atomic check-then-act
EXISTS then SET, Cache::has then Cache::put, SELECT then INSERT without a unique constraint: all have a gap where two workers both see "free". Fix: one atomic operation that both checks and sets, provided by the store.
Scheduler and cron deduplication
| Option | Exactly one run per tick? | Overlap protection | Failure mode |
|---|---|---|---|
Laravel onOneServer() | Yes per minute (shared cache) | No | Cache down: depends on driver errors |
Laravel withoutOverlapping() | No (alone) | Yes | Stuck lock up to 24 h after crash |
| Both together | Yes | Yes | Same as above, efficiency only |
Kubernetes CronJob concurrencyPolicy: Forbid | Mostly (controller-driven) | Yes | Missed schedules on controller downtime |
| Leader-only scheduler (etcd/K8s lease) | Yes while leader | With fencing | Failover gap |
Idempotent job keyed by period (invoice-2026-11) | Effect once even if run twice | N/A | Needs a unique key |
Failover loses the lock
With a Redis primary and async replica, a promoted replica may not have the key. If the lock is efficiency-only, accept and document. If correctness, move it to etcd/ZooKeeper/Consul or a database lease row on a synchronously replicated primary, and fence.
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Cron/scheduled task on several servers | Laravel onOneServer() + withoutOverlapping() or single Redis lock | Idempotent job keyed by period | Efficiency; a rare double run must be harmless |
| Cache rebuild / stampede protection | Single Redis SET NX PX, short TTL | Serve stale while rebuilding | Losing the lock costs one extra query |
| Money, inventory, unique assignment | No lock: CAS / atomic UPDATE / unique constraint | Idempotency keys | The database already serialises one row |
| Correctness across systems (file in S3, external ledger) | etcd or ZooKeeper lock, or database lease | Fencing token enforced by the resource | Only fencing survives pauses |
| One worker per partition/tenant | Lease rows or etcd leases per partition | Token per lease | Ownership must move on crash |
| Job queue in PostgreSQL | FOR UPDATE SKIP LOCKED claim + claimed_until | Idempotent handlers | Workers never wait on each other |
| Migrations at deploy | pg_advisory_lock on a pinned connection | Run from one job | Simple, cleans up at session end |
| Controller in Kubernetes | Lease-based leader election (client-go) | Epoch from leaseTransitions | Built in; client-go does not fence |
| "We need it to survive one Redis node loss" | Redlock only if double execution is tolerable | Fencing elsewhere | Majority helps availability, not safety |
| Resource cannot check tokens (email, SMS, robot) | Best-effort lock + receiver-side dedup | Idempotency key to the provider | No lock can be correct here |
In architecture: from a single process to a distributed system
Monolith: one process, one database
With one process, use language mutexes for in-memory state and the database for everything persistent: an atomic UPDATE, a unique constraint, or SELECT ... FOR UPDATE inside a short transaction. Example: a Laravel app on one server charging invoices: DB::transaction + lockForUpdate() on the customer row is a real lock, enforced by the database, released on commit, no TTL, no pause problem (the database waits for the transaction). The moment you run php artisan schedule:run on a second server, the in-process assumption breaks: add onOneServer().
Modular monolith: boundaries without the network
Several modules share one database but own their tables. Locks should be owned too: the billing module owns lock:billing:* names and its job_leases rows; another module never takes billing's locks. Example: the reporting module wants to block during billing's run. Instead of taking billing's lock, billing publishes "run finished" (an in-process event) and reporting waits for it. Advisory lock keys must be namespaced (AdvisoryKey("billing:run")) so modules do not collide in the bigint space.
Microservices: every arrow is a decision
A lock cannot span service databases. Each service protects its own data with its own database; cross-service exclusion becomes a workflow problem.
Order service Payment service Inventory service
1 POST /orders (Idempotency-Key K)
2 -> outbox: OrderPlaced(order 9)
3 consume OrderPlaced; charge with provider key "order-9"
4 -> PaymentSucceeded(9)
5 consume; UPDATE stock SET n=n-1 WHERE sku=.. AND n>0
6 no distributed lock anywhere: idempotency + conditional writes + sagaWhen one service must be the only actor on an external resource (a single connection to a bank's SFTP, a partner API with one session), use a lease in that service's own store with fencing towards anything it writes, or elect a leader (Leader Election). See Saga Pattern and Transactional Outbox for the flow.
Distributed data: replicas, caches, regions
Locks are writes, so they belong on the primary or a consensus group, never on replicas or caches. Async replication loses locks on failover (Redis, PostgreSQL async standby). Multi-region locks cost a cross-region consensus round trip per acquire (tens to hundreds of ms); prefer per-region ownership of data (single writer per region per key) so locks stay local. Clocks drift more across regions; let the store's clock decide expiry. See CAP & PACELC: a correct lock is a CP choice, so during a partition the minority side cannot acquire.
Scaling path: 1x, 10x, 100x
| Load | Design | What changes |
|---|---|---|
| 1x (one app, one DB) | Database transactions and constraints; onOneServer once you add a server | Nothing distributed yet |
| 10x (many app servers, a queue) | Redis efficiency locks for cron and rebuilds; SKIP LOCKED or a broker for jobs; CAS for records | Lock names become an inventory; dashboards on hold time |
| 100x (partitions, many teams) | Partition ownership by lease (etcd or lease table) with fencing; single writer per key; locks per tenant, not global | A global lock becomes a bottleneck: one key, one Redis core, one etcd Raft log |
Lab
Experiments 1 and 2 run in one process with no server (run here, output pasted). Experiments 3-6 need Redis 7.x/8.4, PostgreSQL 16+ and etcd 3.6: commands with expected output, not run.
1. Replay the paused holder (run).
cd docs/snippets/system-design/distributed-locking/go
go run ./cmd/demo
1 client1 acquired, token=1
2 client1 paused 15s; lease (10s) expired
3 client2 acquired, token=2
4 client2 write: <nil>
5 client1 wakes, write with token=1: fencing: stale token rejected: resource=file-42 token=1 highest=2
6 client1 release: redislock: lock not held by this owner
7 stored value="v2", stale write rejected=true
8 client2 release: <nil>2. Run the tests (run).
go test -race -count=1 ./...
ok academy/distributed-locking/fencing 1.056s
ok academy/distributed-locking/redislock 1.232s3. Unsafe vs safe release in redis-cli (expected, not run).
T1> SET lock:{x} A NX PX 3000 -> OK
(wait 4 s)
T2> SET lock:{x} B NX PX 30000 -> OK
T1> DEL lock:{x} -> (integer) 1 # deleted B's lock
T2> SET lock:{x} B NX PX 30000 -> OK
T1> EVAL "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end" 1 lock:{x} A
-> (integer) 0 # B's lock survives
T1> DELEX lock:{x} IFEQ A -> (integer) 0 # Redis 8.4+4. Advisory locks survive rollback (expected, not run).
psql A> SELECT pg_try_advisory_lock(42); -> t
psql B> SELECT pg_try_advisory_lock(42); -> f
psql A> BEGIN; SELECT 1; ROLLBACK;
psql B> SELECT pg_try_advisory_lock(42); -> f (still held by A's session)
psql A> \q
psql B> SELECT pg_try_advisory_lock(42); -> t
psql B> SELECT locktype, objid, granted FROM pg_locks WHERE locktype = 'advisory';
locktype | objid | granted
advisory | 42 | t5. SKIP LOCKED claim with two workers (expected, not run).
psql A> BEGIN; SELECT id FROM jobs WHERE done_at IS NULL ORDER BY id LIMIT 2 FOR UPDATE SKIP LOCKED; -> 1, 2
psql B> BEGIN; SELECT id FROM jobs WHERE done_at IS NULL ORDER BY id LIMIT 2 FOR UPDATE SKIP LOCKED; -> 3, 4 (no wait)
psql B> SELECT id FROM jobs WHERE id = 1 FOR UPDATE NOWAIT;
ERROR: could not obtain lock on row in relation "jobs" (SQLSTATE 55P03)6. etcd lock and lease expiry (expected, not run).
T1$ etcdctl lease grant 10 -> lease 32695410dcc0ca06 granted with TTL(10s)
T1$ etcdctl lock --ttl 10 /locks/job -> /locks/job/32695410dcc0ca0a (held)
T2$ etcdctl lock /locks/job -> (blocks)
T1$ kill -STOP <pid of T1 etcdctl> # keep-alives stop; about 10 s later the session lease expires
T2$ -> /locks/job/32695410dcc0ca10 (acquired)
T2$ etcdctl get /locks/job --prefix -w json | jq '.kvs[].create_revision' -> larger than T1'sCommon misconceptions
| Belief | Reality |
|---|---|
| A Redis lock is a mutex | It is a key with a TTL; exclusion depends on timing and no failover |
Plain DEL is fine if jobs are fast | One slow run deletes another holder's lock; use compare-and-delete |
| A watchdog prevents expiry during work | It pauses with the process; it shortens, not closes, the window |
| Redlock is safe for correctness | No fencing token; safety depends on bounded pauses, delays and drift |
| Redlock is useless | It tolerates minority node loss; fine where occasional double execution is acceptable |
| etcd/ZooKeeper locks need no fencing | The store is linearizable; your paused client is not |
| The random lock value is a fencing token | It proves identity, not order; tokens must increase |
| Advisory locks are released on rollback | Session-level ones are not; only transaction-level ones are |
Laravel WithoutOverlapping expires by itself | Not unless expireAfter() is set (0 = no expiry on redis) |
onOneServer() prevents overlapping runs | It dedups one scheduled minute; add withoutOverlapping() |
| Kubernetes leader election means one leader | client-go: it "does not guarantee that only one client is acting as a leader" |
| Locks are the default tool for concurrency | CAS, idempotency, unique constraints and single writers are safer |
| Longer TTL is always safer | It also lengthens the stall after a crash |
Cheat sheet
| Topic | Remember |
|---|---|
| First question | Efficiency or correctness: what breaks if two run? |
| Acquire on Redis | SET key rand NX PX ttl (one command) |
| Release on Redis | Lua compare-and-delete or DELEX key IFEQ rand (8.4+) |
| Renew on Redis | Lua compare-and-pexpire or SET key rand IFEQ rand PX ttl (8.4+) |
| Owner value | 128-160 random bits per acquisition |
| TTL | Above measured max work; with renewal, 10-60 s renewed at TTL/3 |
| Renewal fails | Stop work immediately |
| Pauses | GC, swap, throttling, VM, network delay: unbounded |
| Fencing | Token increases per acquisition; resource rejects lower tokens in one atomic write |
| Token sources | etcd create revision, ZooKeeper zxid, Consul LockIndex, lease row counter |
| Redlock | 5 masters, majority, validity = TTL - elapsed - drift, no token |
| PostgreSQL | pg_try_advisory_lock on a pinned connection; pg_advisory_xact_lock in a tx; SKIP LOCKED for queues |
| Laravel | Cache::lock($n, $s)->block(), refresh(), owner()/restoreLock(), onOneServer(), withoutOverlapping(), WithoutOverlapping->expireAfter() |
| Kubernetes | Lease holderIdentity, leaseDurationSeconds, renewTime; client-go does not fence |
| Best lock | Often none: CAS, atomic UPDATE, unique key, idempotency, single writer |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why is SETNX followed by EXPIRE worse than SET NX PX? Must-know
Answer
Answer: They are two commands; a crash between them leaves a key with no expiry, a forever lock. SET ... NX PX creates and sets the expiry atomically.
2 — A job releases its lock with DEL. Describe how this lets three processes run at once. Must-know
Answer
Answer: A's lock expires while A works; B acquires; A finishes and DELs B's key; C acquires. Now B and C both run, and A was running unprotected after expiry. Compare-and-delete prevents the DEL of B's key.
3 — Kleppmann's test for efficiency versus correctness locks? Important
Answer
Answer: Ask what happens if the lock fails and two nodes do the work. Minor cost or inconvenience: efficiency (single Redis is enough). Corruption, loss or inconsistency: correctness (consensus plus fencing).
4 — Why can't a watchdog that renews every 10 s guarantee exclusion? Important
Answer
Answer: It runs inside the holder process. A pause stops both work and watchdog; when the process resumes, in-flight or immediate writes can happen before it notices the lease expired. Only a check at the resource stops them.
5 — What exactly does the storage do with a fencing token? Must-know
Answer
Answer: It keeps the highest token accepted per resource and, atomically with the write, rejects any write whose token is lower (for example UPDATE ... WHERE fence_token <= $token, zero rows means stale).
6 — Why is Redlock's random value not a fencing token? Important
Answer
Answer: It is unique but not ordered; the resource cannot tell whether a writer is newer than the last one it accepted. Tokens must be monotonically increasing.
7 — Give the Redlock acquisition rule and the validity formula. Good to know
Answer
Answer: Acquire on a majority (at least 3 of 5) with total elapsed time less than the TTL; validity = TTL minus elapsed time minus clock drift. Otherwise unlock all instances.
8 — Which fencing token does each of etcd, ZooKeeper and Consul offer? Good to know
Answer
Answer: etcd: the create revision of the lock key (cluster-wide revision); ZooKeeper: the zxid or znode version; Consul: the LockIndex, part of the (Key, LockIndex, Session) sequencer.
9 — Your Go service takes pg_try_advisory_lock with db.QueryRow and unlocks with db.Exec. What can go wrong? Important
Answer
Answer: *sql.DB may use different pooled connections; the unlock runs on a session that does not hold the lock (returns false with a warning) and the real lock stays until that connection closes. Pin a connection with db.Conn(ctx).
10 — A Laravel job uses new WithoutOverlapping($id) and the worker is OOM-killed. What happens on the redis cache driver, and what is the fix? Important
Answer
Answer: The lock was taken with 0 seconds, which the redis driver implements as SETNX with no TTL, so it stays forever and every later job for that id is released or dropped. Add ->expireAfter(180) (or a duration above the job's max).
11 — When is no lock correct, whatever product you use? Must-know
Answer
Answer: When the protected effect cannot check a token or be made conditional or idempotent (an email, an SMS, moving a physical object). Then use best-effort locking plus deduplication on the receiving side, and accept rare duplicates.
Glossary
| Term | Meaning |
|---|---|
| distributed lock | Advisory mutual exclusion between processes without shared memory, held in a shared store |
| mutual exclusion | Safety property: at most one holder at a time |
| efficiency lock | Lock whose failure only costs extra work (Kleppmann) |
| correctness lock | Lock whose failure corrupts state; needs consensus plus fencing |
| advisory lock | A lock the data store does not enforce; also PostgreSQL's named locks |
| SET NX PX | Redis SET options: only if not exists, expiry in ms |
| Lua compare-and-delete | Script deleting the key only if it holds the caller's value |
| DELEX / IFEQ | Redis 8.4 conditional delete and conditional SET |
| owner | Random value identifying one acquisition (Laravel owner()) |
| TTL / lock expiry | Time after which the lock disappears by itself |
| lock validity time | Redis docs' term for the TTL as the safe work window |
| auto-extension / renewal | Extending the TTL while still owner |
| watchdog | Background renewer (Redisson, KeepAlive here) |
| process pause / GC pause | Interval in which a live process runs no code |
| clock drift / clock jump | Rate difference between clocks / discontinuous step |
| monotonic clock | Clock that never goes backwards; for measuring elapsed time |
| Redlock | Client-side majority lock over N independent Redis masters |
| Kleppmann critique | 2016 argument: Redlock lacks fencing and depends on timing |
| split brain | Two parties both believe they hold the lock / leadership |
| fencing token / monotonic token | Increasing number per acquisition, checked by the resource |
| sequencer | Chubby/Consul name for a token identifying the lock generation |
| lease | Time-bounded ownership that expires unless renewed |
| etcd lease | etcd object with TTL; attached keys deleted on expiry |
| Txn | etcd atomic If/Then/Else over comparisons |
| linearizable | Every operation appears to take effect at one instant in real-time order |
| ephemeral node | ZooKeeper znode deleted when its session ends |
| sequential node | ZooKeeper znode with an increasing suffix appended by the server |
| herd effect | Waking all waiters when only one can proceed |
| Consul session | Consul liveness contract binding locks to nodes, checks and TTL |
| lock-delay | Consul/Chubby pause before a released lock can be re-acquired |
| LockIndex | Consul counter incremented on each acquire |
| pg_advisory_lock / pg_try_advisory_lock | PostgreSQL session-level advisory lock, blocking / non-blocking |
| pg_advisory_xact_lock | Transaction-level advisory lock, released at commit/rollback |
| FOR UPDATE SKIP LOCKED | Row locking that skips rows locked by others; queue claims |
| work claim | Marking rows as taken by a worker, usually with SKIP LOCKED and a claim expiry |
| lease column | expires_at/holder/fence_token columns that implement a lease in SQL |
| check-then-act | Non-atomic read then write; the classic race |
| race | Outcome depends on timing of concurrent actors |
| unlock other's lock | Deleting a lock that now belongs to another holder |
| idempotency | Repeating an operation has no additional effect |
| CAS / optimistic concurrency | Write only if a value or version is unchanged; retry on conflict |
| single writer | One owner per key or partition, so no lock is needed |
| Cache::lock / block | Laravel atomic lock; wait up to N seconds to acquire |
| restoreLock / forceRelease / refresh | Laravel: re-instantiate by owner / release regardless / extend |
| onOneServer | Laravel scheduler: run a task on one server per tick |
| withoutOverlapping / WithoutOverlapping | Laravel scheduler option / job middleware preventing overlap |
| LockTimeoutException | Laravel exception when block() times out |
| leader election | Choosing one active node; a long-lived lock with a lease |
| Kubernetes Lease | coordination.k8s.io object with holder, duration, renew time |
| Redisson / Redsync | Java Redis client with locks and watchdog / Go Redlock library |
| miniredis | In-memory Redis server for Go tests, with Lua and FastForward |
References
- Martin Kleppmann, How to do distributed locking (2016): https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html
- Salvatore Sanfilippo (antirez), Is Redlock safe? (2016): http://antirez.com/news/101
- Redis docs, Distributed Locks with Redis: https://redis.io/docs/latest/develop/clients/patterns/distributed-locks/
- Redis docs,
SET: https://redis.io/docs/latest/commands/set/ - Redis docs,
DELEX: https://redis.io/docs/latest/commands/delex/ - Redis docs,
EVAL: https://redis.io/docs/latest/commands/eval/ - Redis docs, Scripting with Lua: https://redis.io/docs/latest/develop/programmability/eval-intro/
- Redisson docs, Locks and synchronizers: https://redisson.pro/docs/data-and-services/locks-and-synchronizers/
- etcd docs, etcd API (leases, revisions, Txn): https://etcd.io/docs/v3.5/learning/api/
- etcd docs, API concurrency reference: https://etcd.io/docs/v3.5/dev-guide/api_concurrency_reference_v3/
- Go package
go.etcd.io/etcd/client/v3/concurrency: https://pkg.go.dev/go.etcd.io/etcd/client/v3/concurrency - Apache ZooKeeper, ZooKeeper Recipes and Solutions (r3.9.3): https://zookeeper.apache.org/doc/r3.9.3/recipes.html
- HashiCorp Consul, Sessions and distributed locks overview: https://developer.hashicorp.com/consul/docs/automate/session
- PostgreSQL docs, Explicit Locking (advisory locks): https://www.postgresql.org/docs/current/explicit-locking.html
- PostgreSQL docs, System Administration Functions (advisory lock functions): https://www.postgresql.org/docs/current/functions-admin.html
- PostgreSQL docs,
SELECT(locking clause,SKIP LOCKED): https://www.postgresql.org/docs/current/sql-select.html - PostgreSQL docs, Error Codes: https://www.postgresql.org/docs/current/errcodes-appendix.html
- Kubernetes docs, Leases: https://kubernetes.io/docs/concepts/architecture/leases/
- Kubernetes API reference, Lease v1: https://kubernetes.io/docs/reference/kubernetes-api/cluster-resources/lease-v1/
- Go package
k8s.io/client-go/tools/leaderelection: https://pkg.go.dev/k8s.io/client-go/tools/leaderelection - Laravel 13 docs, Cache (atomic locks): https://laravel.com/docs/13.x/cache
- Laravel 13 docs, Task Scheduling: https://laravel.com/docs/13.x/scheduling
- Laravel 13 docs, Queues (
WithoutOverlapping): https://laravel.com/docs/13.x/queues - Laravel framework source,
RedisLock.php(13.x): https://github.com/laravel/framework/blob/13.x/src/Illuminate/Cache/RedisLock.php - Laravel framework source,
DatabaseLock.php(13.x): https://github.com/laravel/framework/blob/13.x/src/Illuminate/Cache/DatabaseLock.php - Laravel framework source,
WithoutOverlapping.php(13.x): https://github.com/laravel/framework/blob/13.x/src/Illuminate/Queue/Middleware/WithoutOverlapping.php - go-redis: https://github.com/redis/go-redis and https://pkg.go.dev/github.com/redis/go-redis/v9
- miniredis: https://pkg.go.dev/github.com/alicebob/miniredis/v2
- Mike Burrows, The Chubby lock service for loosely-coupled distributed systems (OSDI 2006), paper page: https://research.google/pubs/the-chubby-lock-service-for-loosely-coupled-distributed-systems/