Skip to content

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 forGo to
The whole page in three tablesEverything in one minute
Why a lock across machines is not a mutexWhy it exists
Leases 1989, Chubby, Redlock, the 2016 debateWhere it comes from
What "advisory" meansWhat a distributed lock is
Do I need a correct lock or a cheap one?Efficiency vs correctness
SET key value NX PX 30000Single-instance Redis lock
Safe release, DELEX, the Lua scriptRelease
How long the TTL should be, watchdogsTTL and watchdog
GC, SIGSTOP, page faults, 90-second packetsPauses
NTP steps, gettimeofday, driftClocks
Five Redis masters and a majorityRedlock
Who was right in 2016The debate
The one thing that makes a lock safeFencing tokens
Time-bounded ownershipLeases
ZooKeeper, etcd, ConsulConsensus-based locks
pg_advisory_lock, SKIP LOCKED, lease rowsDatabase locks
Avoiding the lock entirelyLock-free alternatives
Cache::lock, onOneServer, WithoutOverlappingLaravel locks
coordination.k8s.io LeaseKubernetes Lease
What to graph and alert onObservability
Redis, Redisson, etcd, ZooKeeper, Consul, PostgreSQL side by sideProducts
Exact commands, replies, error textsMechanics
Working codeGo, Laravel, SQL
Classic failures and fixesSolving the classic problems
Which tool for which jobChoosing
Monolith to distributed systemIn architecture
Hands-on experimentsLab
Beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

What can go wrong, and what stops it.

FailurePlain wordsTiny exampleWhat stops it
Check-then-act raceTwo workers both see "free" and both take itEXISTS lock then SET lockOne atomic command: SET key v NX PX ttl
Unlocking someone else's lockYour lock expired, another took it, you delete theirsPlain DEL lock after a slow jobRandom owner value + compare-and-delete (Lua or DELEX IFEQ)
Lock expires mid-workThe job runs longer than the TTL10 s TTL, 30 s jobMeasured TTL, renewal by a watchdog, stop work when renewal fails
Paused holderThe process freezes, wakes up after expiry, keeps writing15 s GC pause, 10 s leaseFencing token checked by the resource
Failover loses the lockAsync replica promoted without the keyRedis primary crashConsensus store (etcd, ZooKeeper) or accept it (efficiency lock)
Clock jumpServer clock steps forward, key expires earlyNTP step on one Redlock nodeMonotonic clocks, slewing NTP, fencing
Forever lockHolder dies and the lock never expiresCache::lock('x') with 0 seconds on RedisAlways a TTL; leases instead of locks

The tools, from cheapest to strongest.

ToolGuaranteeTypical useFencing token available
Single Redis SET NX PXMutual exclusion while one primary lives and clocks behaveCron dedup, cache rebuild, rate of expensive workNot built in; INCR beside it (this page)
Redlock (5 masters)Majority-based, still timing-dependentLittle: heavier than needed for efficiency, not enough for correctnessNo
Laravel Cache::lockSame as the cache driver underneathJobs, scheduler, controllersNo
PostgreSQL advisory lockExclusive while the session livesMigrations, one-at-a-time batch jobsNo (session ends = lock gone)
Database lease rowLinearizable on the primary, expiry by now()Job ownership, partition ownershipYes, a fence_token column
etcd lease + MutexLinearizable (Raft)Correctness locks, leader electionYes, the key's create revision
ZooKeeper ephemeral sequential nodeLinearizable writes (Zab)Correctness locks, Kafka-era coordinationYes, zxid or znode version
Consul session + KV acquireRaft-backed, advisoryService-level locks, leader electionYes, LockIndex in the sequencer
Kubernetes LeaseStored in etcd through the API serverController leader election, node heartbeatsleaseTransitions counts, client-go does not fence

The four rules.

RuleWhy
Ask "what breaks if two run at once?" before choosingEfficiency locks can be cheap; correctness locks need consensus plus fencing
Every lock has an expiry and an owner tokenWithout expiry a crash locks forever; without owner you release other people's locks
The resource checks the token, not the clientA paused client cannot check anything at the moment that matters
Prefer no lock: idempotency, compare-and-set, single writerA 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 processLock across machines
Shared memory, the lock is a word in RAMThe 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 neededExpiry is required, so ownership can end while the holder still works
The OS enforces it for code that uses itPurely advisory: nothing stops a write that ignores it
Clock irrelevantTTLs depend on clocks on the lock server, and sometimes the client
Cost: nanosecondsCost: one or more network round trips, plus a consensus write for strong stores
A paused lock holder, with and without a fencing check in storageClient 1Lock serviceClient 2Storageacquire: ok, token 33stop-the-world GC pause (or SIGSTOP, page fault, slow disk)lease for client 1 (TTL)expiresacquire: ok, token 34write(data, 34)ok; highest = 34wakes up, still believes it holds the lockwrite(data, 33)With fencing: 33 < 34, rejectedclient 2's data survivesWithout: write lands, data corruptedToken = number that only grows per acquisition.The check runs in storage, not in the client.

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 ​

  1. "Redis SET NX gives 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.
  2. "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.
  3. "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.

YearEventSource
1989Gray and Cheriton, Leases (SOSP)Reference [1] in Kleppmann's post
2006Burrows, The Chubby lock service (OSDI): sequencers, lock-delayGoogle Research paper page; Consul docs
ZooKeeper eraLock recipe: ephemeral + sequence flags, watch the next-lowest nodeZooKeeper recipes
2016 (8 Feb)Kleppmann critiques Redlock, introduces fencing tokens to most readersmartin.kleppmann.com
2016 (9 Feb)antirez replies: monotonic clocks yes, the rest disputedantirez.com
v1.26Each kube-apiserver publishes an identity Lease in kube-systemKubernetes Leases docs
Redis 8.4DELEX key IFEQ value and SET ... IFEQ make compare-and-delete and compare-and-renew nativeredis.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 hold

Real 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.

StoreAtomic conditional writeExpiryEnforced on the data?
RedisSET NX, Lua scripts, SET IFEQ (8.4)Key TTL (PX, EX)No
PostgreSQLINSERT ... ON CONFLICT, advisory lock functionsSession end, or a lease columnOnly if the protected table checks a token
etcdTxn with Compare on revision/version/valueLease TTL, kept alive by the clientOnly through a guarded Txn or a token
ZooKeepercreate fails if the node exists; sequential namesEphemeral node dies with the sessionOnly through a token (zxid)
ConsulKV ?acquire= session check-and-setSession TTL, health checksNo; 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.

QuestionEfficiency lockCorrectness lock
Cost of two holdersExtra work, a duplicate emailCorruption, double charge, inconsistency
StoreSingle Redis, Cache::lock, advisory locketcd, ZooKeeper, Consul, database lease row
Fencing tokenOptionalRequired
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 -> OK

Real 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.

DetailChoiceWhy
Value128-160 random bits, per acquisitionRelease and renew must prove ownership
Expiry optionPX (ms) or EX (s); PXAT for absoluteNX and expiry must be one command
Replica readsNever read the lock from a replicaReplication is asynchronous
Redis ClusterLock key and companion keys share a hash tag, e.g. lock:{invoices} and lock:{invoices}:fenceMulti-key scripts must hit one slot
RetryRandom delay; the Redis docs recommend it "to desynchronize multiple clients"Avoids lock-step contention
PersistenceEfficiency lock: default; correctness: not Redis aloneA 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 methodAtomicChecks ownerAvailable
DEL keyYesNoAll versions: unsafe
GET then DEL from the clientNo (race between them)Yes, but too lateNever do this
Lua compare-and-delete via EVAL/EVALSHAYesYesRedis 2.6+, all clients
DELEX key IFEQ valueYesYesRedis 8.4+
Laravel $lock->release()Yes (Lua on redis driver; WHERE owner = ? on database driver)YesLaravel 13
Laravel forceRelease()YesNo (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 it
Lease with watchdog renewal (TTL 30 s, renew every 10 s)time (s)0102030405060Node Alease to 30renewed at 10: lease to 40renew okNode A paused 12 s to 50 s: watchdog goroutine is paused too, no renewallease expires at 40Node BB acquires at 41, token 8A wakes at 50, writes token 7storage: 7 < 8, reject (fencing)Renewal shortens the window;it cannot close it. A pausedprocess cannot notice expiry.

Real 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.

SettingRule of thumbReason
TTL without renewalWell above measured max work time, plus headroomExpiry mid-work is the main failure
TTL with renewal10-60 sBounds how long a crashed holder blocks others
Renewal intervalTTL / 3Two missed renewals still leave time
Renewal call timeoutBelow the intervalA hung renewal must not look like success
On renewal failureCancel work immediately, do not retry the renewal foreverThe lock is gone; continuing is unsafe
Max total holdA 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  <-- corruption

Real 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 pauseTypical lengthDetected by the client?
Stop-the-world GC (JVM, .NET)ms to minutes ("several minutes" cited by Kleppmann)Only afterwards
Page fault, swap, network diskms to secondsNo
CPU throttling (cgroup quota), noisy neighbourms to secondsNo
VM live migration, SIGSTOP, debuggerseconds to minutesNo
Network delay of an already-sent writeseconds; ~90 s in the GitHub incidentNo

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 lock

Real 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.

SystemClock that decides expiryNote
Redis key TTLWall clock of the Redis serverPer Redis docs disclaimer
etcd leaseThe 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 TTLServers; TTL is "a lower bound for invalidation"Consul: "clients should be aware of clock skew issues"
PostgreSQL lease rownow() on the primaryOne clock decides; clients' clocks irrelevant
Kubernetes client-go leader electionLocal 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)
Redlock: majority of N=5 independent Redis mastersClient 1value = random 20 BA: OKB: OKC: OKD: timeoutE: timeoutSET lock v NX PX 10000per-node timeout 5-50 msClient 1 decides3 of 5 = majority (N/2+1)elapsed = T2 - T1 (first send to last reply)validity = TTL - elapsed - clock driftno majority or validity <= 0: unlock all fiveHow two clients both win (Kleppmann)1. C's wall clock jumps forward: key expires early or C restarts without fsync and forgets the key2. Client 2 locks C, D, E: also a majority3. Both hold the lock; no token tells storage whichMitigations from the Redis docs: delayed restart longer than max TTL, appendfsync always, fencing tokens.

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 knobValue in the docsEffect
N5Tolerates 2 failed nodes
Per-node timeout5-50 ms for a 10 s TTLA dead node does not eat the validity
Retry"after a random delay"Reduces split votes
Crash recoveryDelayed restart for "a bit more than the max TTL", or fsync=alwaysOtherwise a restarted node forgets keys
ExtensionLua extend on all nodes, majority within validitySame algorithm as acquire
FencingNoneThe 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:

PointKleppmannantirez
FencingRedlock "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 modelRedlock 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 acquireGC between request and reply breaks itSteps 1 and 3 re-read the time, so "the lock will always be considered not valid if too much time elapsed"
Delay after acquireUnsafe without fencingAgreed: common to "all the distributed locks implementations"
Clock jumpsgettimeofday jumpsAgrees: Redis "should switch to the monotonic time API"
RecommendationEfficiency: single Redis. Correctness: "a proper consensus system such as ZooKeeper" plus fencingRedlock 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 fencing

Real 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.

TakeawayApplies to
Any lock with expiry can be outlived by its holderRedis, Redlock, etcd, ZooKeeper, Consul, database leases
The only general defence is a check at the resourceFencing tokens, conditional writes, idempotency
Redlock's majority helps availability, not the paused-holder problemRedlock

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: REJECTED

Real 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 sourceMonotonic across failover?How the resource checks
etcd create revisionYes (Raft, cluster-wide revision)Store column or guarded Txn with IsOwner()
ZooKeeper zxid / znode versionYes (Zab)Store column
Consul LockIndexYes (Raft)Compare with the last seen index
Database lease fence_tokenYes on one primary; with sync replication across failoverSame database: UPDATE ... WHERE fence_token <= $1
Redis INCR on one primaryOnly while no failover loses writes (Kleppmann: "that node may fail")Store column
RedlockNo tokenNot 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 wakes

Real 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 systemGrantRenewExpiry effect
etcdLeaseGrant (TTL seconds)LeaseKeepAlive streamAttached keys deleted
ZooKeeperSession (timeout negotiated at connect)Client heartbeatsEphemeral nodes deleted
ConsulSession create (TTL, checks, behavior, lock-delay)session/renewLocks released (default) or deleted
KubernetesCreate/Update a Lease objectUpdate renewTimeOthers may take over after leaseDurationSeconds
PostgreSQL lease rowINSERT ... ON CONFLICT with expires_atUPDATE ... SET expires_at by holderOthers' 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 a create() that succeeded but whose reply was lost. Apache Curator's InterProcessMutex packages the recipe.
  • etcd: concurrency.NewSession creates 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; TryLock returns ErrLocked ("mutex: Locked by another session"); IsOwner() returns a Cmp usable in Txn(...).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 release or delete, TTL, lock-delay 0-60 s, default 15 s), then PUT /v1/kv/<key>?acquire=<session>; the acquire "acts like a Check-And-Set operation"; LockIndex increments 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.

FeatureZooKeeperetcd v3Consul
ConsensusZabRaftRaft
Liveness objectSessionLease (TTL, keep-alive)Session (TTL and/or health checks)
Lock recordEphemeral sequential znodeKey with lease under a prefixKV key with Session field
WaitingWatch the predecessor (no herd)Wait for lower create revisions to be deletedBlocking query on the key
Fencing tokenzxid, znode versionCreate revision / mod_revisionLockIndex (sequencer)
Guarded writemulti with version checkTxn().If(m.IsOwner())Check LockIndex + session
Post-expiry safeguardNone built inNone built inlock-delay (default 15 s)
Go clientgithub.com/go-zookeeper/zkgo.etcd.io/etcd/client/v3/concurrencygithub.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 locks

Real 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.

ToolScopeReleased byFencingPitfall
pg_advisory_lock / pg_try_advisory_lockSessionpg_advisory_unlock, session endNoPooled connections; reentrant count; survives rollback
pg_advisory_xact_lockTransactionCOMMIT / ROLLBACKNoLong transaction holds it and blocks VACUUM cleanup
SELECT ... FOR UPDATERow, transactionTransaction endNoHolding a transaction open during a network call
FOR UPDATE SKIP LOCKEDRow, transactionTransaction endNo"inconsistent view": queues only
FOR UPDATE NOWAITRowTransaction endNoError 55P03 lock_not_available instead of waiting
Lease row (expires_at, fence_token)Named resourceExpiry by now() or deleteYesNeeds a renewal loop; table on the primary
MySQL GET_LOCK(name, timeout)SessionRELEASE_LOCK, session endNoSame 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 update

Real 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.

AlternativeReplaces a lock whenCost
Idempotency keyDuplicated work, not concurrent writes, is the riskA dedup store and TTL
CAS / version columnRead-modify-write of one recordRetries under contention
Atomic single statementThe change can be expressed in one UPDATENone; best option
Unique constraint"Create once" (one invoice per month per customer)Handle the duplicate-key error
Single writer per partitionMany keys, ordered work per keyPartitioning 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) with get(), get(Closure), block($seconds) (throws Illuminate\Contracts\Cache\LockTimeoutException), release(), owner(), Cache::restoreLock($name, $owner), forceRelease(), refresh($seconds = null), isOwnedByCurrentProcess(), betweenBlockedAttemptsSleepFor($ms) (default 250 ms), plus Cache::withoutOverlapping() and Cache::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-cache clears stuck locks. Schedule::useCache('redis') picks the store.
  • Job middleware WithoutOverlapping($key) with releaseAfter($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 going

Real 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 featureUnderlying lockDefault expiryWatch out
Cache::lock('x', 10)Driver lock (SET NX EX on redis)10 sCache::lock('x') = 0 s = no expiry on redis
block(5)Polls acquire()Waits up to 5 sLockTimeoutException; release in finally
refresh()Lua compare-and-expireOriginal durationReturns false when lost: stop work
restoreLock($name, $owner)Same lock, given ownerUnchangedPass owner() to the job
onOneServer()Scheduling mutex per minute3600 sNot overlap protection across days
withoutOverlapping()Event mutex24 h (1440 min)Stuck after a crash: schedule:clear-cache
WithoutOverlapping middlewareCache::lock($key, expiresAfter)0 = forever on redisAlways add expireAfter()
database cache driver lockcache_locks table row with owner, expirationGiven seconds; 0 becomes 86400 sPruned 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 window

Real 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.

FieldMeaningUse as
holderIdentityCurrent holderWho to page
leaseDurationSecondsHow long others wait after last observed renewalFailover time bound
renewTimeLast renewalLiveness signal
leaseTransitionsNumber of holder changesMonotonic, 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 twice

Real 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.

SignalSourceAlert when
Hold time vs TTLClient histogramp99 above 50% of TTL
Acquire wait / busy rateClient counterSudden rise: a stuck holder
Renewal failuresWatchdogAny
Release not_ownerCompare-and-delete reply 0Any
Fenced write rejectedResourceAny (good catch, but investigate pauses)
Stale lockspg_locks, TTL key, etcdctl lease listHolder 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 holders

Real 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.

ProductLock primitiveOn holder crashOn store node failureToken
Redis (single primary)SET NX PX + Lua releaseTTL expiryFailover can lose the lockINCR beside it, not failover-safe
Redis + Redlock (Redsync, Redisson RedissonRedLock)Majority of N mastersTTL expiryTolerates minority lossNone
Redisson RLock / RFencedLockLua scripts, pub/sub wait, watchdog 30 sWatchdog stops, TTL expiryAs RedisRFencedLock yes
etcdLease + Mutex (concurrency)Lease expiry (default 60 s session TTL)Raft majority keeps stateCreate revision
ZooKeeper / CuratorEphemeral sequential znodeSession timeoutZab quorum keeps statezxid / version
ConsulSession + KV acquireSession TTL/health check, lock-delayRaft quorumLockIndex
PostgreSQLAdvisory lock, lease row, SKIP LOCKEDSession end / expires_atPrimary failover: sync replication or lossLease fence_token
MySQLGET_LOCK, SELECT ... FOR UPDATE SKIP LOCKED (8.0+)Session endAs replicationColumn you add
KubernetesLease objectleaseDurationSecondsetcd behind the API serverleaseTransitions
DynamoDB (Laravel dynamodb lock)Conditional put with expiry attributeExpiryRegional, managedColumn you add

Fix / how to use it: match the table to the decision table.

Mechanics ​

Exact commands and replies ​

OperationCommand / callSuccessFailure
Redis acquireSET lock:{x} <rand> NX PX 30000OK(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 30000OK(nil) (key missing or value differs)
Redis renew (Lua)if get == ARGV[1] then return pexpire(KEYS[1], ARGV[2])10
etcd leaseetcdctl lease grant 15lease 694d... granted with TTL(15s)
etcd lock CLIetcdctl lock /locks/jobprints the lock key, holds until exitblocks
PostgreSQL try lockSELECT pg_try_advisory_lock(42);tf
PostgreSQL unlock not heldSELECT pg_advisory_unlock(42);tf plus a WARNING
Consul acquirePUT /v1/kv/locks/job?acquire=<session-id>truefalse
Kuberneteskubectl get lease -n kube-systemholder, age

Timing arithmetic ​

QuantityFormulaExample
Redlock validityTTL - (T2 - T1) - drift10 000 - 52 - 100 = 9 848 ms
Safe work budgetvalidity - max expected pause - write latency9 848 - 2 000 - 200 = 7 648 ms
Renewal intervalTTL / 330 s TTL: every 10 s
Worst blocked time after crashTTL (+ lock-delay on Consul)30 s; Consul 30 + 15 s
Kubernetes failoverabout leaseDurationSeconds + retry periodclient-go example 60 s / 30 s for 2x skew rate tolerance
Lock throughput, single Redis1 RTT acquire + 1 RTT release0.5 ms RTT: about 1 ms overhead per critical section (back-of-envelope)
etcd lockRaft write (fsync on a majority) per acquire/releaseMilliseconds; much lower ceiling than Redis (no figure measured here)

Errors and messages ​

MessageWhereMeaningAction
mutex: Locked by another session (concurrency.ErrLocked)etcd TryLockBusySkip or retry later
mutex: session is expired (ErrSessionExpired)etcdLease goneNew session; treat lock as lost
Illuminate\Contracts\Cache\LockTimeoutExceptionLaravel block()Not acquired in timeSkip, release in finally
Illuminate\Cache\Limiters\LimiterTimeoutExceptionLaravel funnel()No slotBack off
SQLSTATE 55P03 lock_not_availablePostgreSQL NOWAIT, lock_timeoutRow/table lock not availableRetry or skip
SQLSTATE 40P01 deadlock_detectedPostgreSQLTwo lockers wait on each otherRetry; order lock acquisition (Deadlocks)
CROSSSLOT Keys in request don't hash to the same slotRedis ClusterLock and fence key in different slotsUse a hash tag {x}
redis: nil (redis.Nil)go-redisSET NX not applied / script returned falseErrNotAcquired

Knobs ​

KnobProductDefault / rangeNote
PX / EXRedis SETnoneAlways set one
appendfsyncRediseverysecRedlock docs: always for crash safety
lockWatchdogTimeoutRedisson30 sWatchdog lease length
WithTTLetcd concurrency60 sSession lease
lock-delayConsul session15 s, 0-60 sChubby-style safeguard
behaviorConsul sessionreleaseor delete
max_locks_per_transactionPostgreSQL64Caps advisory locks with max_connections
lock_timeoutPostgreSQL0 (off)Bounds waits for row/table locks
betweenBlockedAttemptsSleepForLaravel250 msPoll interval in block()
withoutOverlapping($minutes)Laravel scheduler1440Event mutex expiry
leaseDurationSecondsKubernetes Leaseset by clientTakeover 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.

go
// 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:

go
// 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):

go
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:

go
// 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
}
go
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:

go
// 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:

go
// 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):

go
// 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.Mutex is 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 with context.Cause.
  • go-redis: redis.NewScript(src).Run(ctx, rdb, keys, args...) tries EVALSHA and falls back to EVAL; a Lua false reply becomes redis.Nil. rdb.SetNX(ctx, key, val, ttl) sends SET key val PX ttl NX when the TTL is set, but the script form lets you add the fence INCR atomically.
  • 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(), NewElection for 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 needs db.Conn(ctx); *sql.DB may run each statement on a different pooled connection. pgx users can hold a *pgxpool.Conn the 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 with go.etcd.io/etcd/tests/v3/integration or a fake behind an interface.

Laravel ​

Before ​

A hand-rolled cache flag: check-then-act, no owner, guessed TTL, unconditional delete.

php
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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::lock is implemented per driver: RedisLock (SET NX EX, Lua release and refresh), DatabaseLock (cache_locks table: 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 onOneServer and withoutOverlapping use the cache store from Schedule::useCache(); with the array or file driver they do not coordinate across servers.
  • Job middleware: WithoutOverlapping with expireAfter(); ShouldBeUnique jobs (uniqueness while queued) also use atomic locks: see Laravel Queue Internals.
  • In tests, the array cache driver supports locks, so Cache::lock code 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:

sql
-- 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
sql
-- 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 work

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limit
Unlocking someone else's lock (unlock other's lock)Owner token + compare-and-deleteLua script or DELEX IFEQ; Laravel release()Never frees another holderMust treat reply 0 as "lost"
Long GC past TTLFencing tokenResource rejects lower tokensWorks for any pause lengthResource must cooperate
Lock held across network callsShrink the critical sectionPrepare outside, lock only the commit; or CASShorter hold, fewer expiriesRedesign
Lock without fencingAdd a tokenLease row counter, etcd revision, zxidTurns an efficiency lock into a correct oneNeeds a linearizable counter
Non-atomic check-then-actOne atomic commandSET NX PX, INSERT ... ON CONFLICT, UPDATE ... WHERENo race windowNone
Cron on N serversScheduler lockLaravel onOneServer(), Kubernetes CronJob, leader-only schedulerSimpleEfficiency only
Lock lost on Redis failoverConsensus store or acceptetcd/ZooKeeper; or idempotent workSurvives node lossLatency, operations
Forever lock after a crashExpiry everywhereTTL on every lock; expireAfter(); leasesSelf-healingTTL must exceed work time
Thundering herd on releaseOrdered waitersZooKeeper predecessor watch, etcd revision orderOne wakes, not allConsensus 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    release

Fix: 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 ​

OptionExactly one run per tick?Overlap protectionFailure mode
Laravel onOneServer()Yes per minute (shared cache)NoCache down: depends on driver errors
Laravel withoutOverlapping()No (alone)YesStuck lock up to 24 h after crash
Both togetherYesYesSame as above, efficiency only
Kubernetes CronJob concurrencyPolicy: ForbidMostly (controller-driven)YesMissed schedules on controller downtime
Leader-only scheduler (etcd/K8s lease)Yes while leaderWith fencingFailover gap
Idempotent job keyed by period (invoice-2026-11)Effect once even if run twiceN/ANeeds 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 ​

Which lock, if anyCan the work be made safe to repeator conditional on version?yesNo lock: idempotency key, CAS /version column, single writer perpartition, queue with one consumernoIf two holders run atonce, what breaks?only cost or a duplicate emailEfficiency locksingle Redis: SET NX PX + Lua compare-and-deleteLaravel Cache::lock, onOneServer, WithoutOverlappingpg_try_advisory_lock when PostgreSQL is already theremoney, data, external stateCorrectness locketcd lease + Mutex, ZooKeeper ephemeral sequential,Consul session, or a database lease rownot Redlock (no fencing token, timing assumptions)plus a fencing token checked by the resourcerevision, zxid, LockIndex, fence_token columnCannot fence the resource (an email, a robot arm)?Then no lock is correct alone: add idempotency onthe receiving side or accept a rare duplicate.
SituationRecommendationExtra techniqueReason
Cron/scheduled task on several serversLaravel onOneServer() + withoutOverlapping() or single Redis lockIdempotent job keyed by periodEfficiency; a rare double run must be harmless
Cache rebuild / stampede protectionSingle Redis SET NX PX, short TTLServe stale while rebuildingLosing the lock costs one extra query
Money, inventory, unique assignmentNo lock: CAS / atomic UPDATE / unique constraintIdempotency keysThe database already serialises one row
Correctness across systems (file in S3, external ledger)etcd or ZooKeeper lock, or database leaseFencing token enforced by the resourceOnly fencing survives pauses
One worker per partition/tenantLease rows or etcd leases per partitionToken per leaseOwnership must move on crash
Job queue in PostgreSQLFOR UPDATE SKIP LOCKED claim + claimed_untilIdempotent handlersWorkers never wait on each other
Migrations at deploypg_advisory_lock on a pinned connectionRun from one jobSimple, cleans up at session end
Controller in KubernetesLease-based leader election (client-go)Epoch from leaseTransitionsBuilt in; client-go does not fence
"We need it to survive one Redis node loss"Redlock only if double execution is tolerableFencing elsewhereMajority helps availability, not safety
Resource cannot check tokens (email, SMS, robot)Best-effort lock + receiver-side dedupIdempotency key to the providerNo 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 + saga

When 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 ​

LoadDesignWhat changes
1x (one app, one DB)Database transactions and constraints; onOneServer once you add a serverNothing distributed yet
10x (many app servers, a queue)Redis efficiency locks for cron and rebuilds; SKIP LOCKED or a broker for jobs; CAS for recordsLock 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 globalA 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.232s

3. 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 | t

5. 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's

Common misconceptions ​

BeliefReality
A Redis lock is a mutexIt is a key with a TTL; exclusion depends on timing and no failover
Plain DEL is fine if jobs are fastOne slow run deletes another holder's lock; use compare-and-delete
A watchdog prevents expiry during workIt pauses with the process; it shortens, not closes, the window
Redlock is safe for correctnessNo fencing token; safety depends on bounded pauses, delays and drift
Redlock is uselessIt tolerates minority node loss; fine where occasional double execution is acceptable
etcd/ZooKeeper locks need no fencingThe store is linearizable; your paused client is not
The random lock value is a fencing tokenIt proves identity, not order; tokens must increase
Advisory locks are released on rollbackSession-level ones are not; only transaction-level ones are
Laravel WithoutOverlapping expires by itselfNot unless expireAfter() is set (0 = no expiry on redis)
onOneServer() prevents overlapping runsIt dedups one scheduled minute; add withoutOverlapping()
Kubernetes leader election means one leaderclient-go: it "does not guarantee that only one client is acting as a leader"
Locks are the default tool for concurrencyCAS, idempotency, unique constraints and single writers are safer
Longer TTL is always saferIt also lengthens the stall after a crash

Cheat sheet ​

TopicRemember
First questionEfficiency or correctness: what breaks if two run?
Acquire on RedisSET key rand NX PX ttl (one command)
Release on RedisLua compare-and-delete or DELEX key IFEQ rand (8.4+)
Renew on RedisLua compare-and-pexpire or SET key rand IFEQ rand PX ttl (8.4+)
Owner value128-160 random bits per acquisition
TTLAbove measured max work; with renewal, 10-60 s renewed at TTL/3
Renewal failsStop work immediately
PausesGC, swap, throttling, VM, network delay: unbounded
FencingToken increases per acquisition; resource rejects lower tokens in one atomic write
Token sourcesetcd create revision, ZooKeeper zxid, Consul LockIndex, lease row counter
Redlock5 masters, majority, validity = TTL - elapsed - drift, no token
PostgreSQLpg_try_advisory_lock on a pinned connection; pg_advisory_xact_lock in a tx; SKIP LOCKED for queues
LaravelCache::lock($n, $s)->block(), refresh(), owner()/restoreLock(), onOneServer(), withoutOverlapping(), WithoutOverlapping->expireAfter()
KubernetesLease holderIdentity, leaseDurationSeconds, renewTime; client-go does not fence
Best lockOften none: CAS, atomic UPDATE, unique key, idempotency, single writer

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
distributed lockAdvisory mutual exclusion between processes without shared memory, held in a shared store
mutual exclusionSafety property: at most one holder at a time
efficiency lockLock whose failure only costs extra work (Kleppmann)
correctness lockLock whose failure corrupts state; needs consensus plus fencing
advisory lockA lock the data store does not enforce; also PostgreSQL's named locks
SET NX PXRedis SET options: only if not exists, expiry in ms
Lua compare-and-deleteScript deleting the key only if it holds the caller's value
DELEX / IFEQRedis 8.4 conditional delete and conditional SET
ownerRandom value identifying one acquisition (Laravel owner())
TTL / lock expiryTime after which the lock disappears by itself
lock validity timeRedis docs' term for the TTL as the safe work window
auto-extension / renewalExtending the TTL while still owner
watchdogBackground renewer (Redisson, KeepAlive here)
process pause / GC pauseInterval in which a live process runs no code
clock drift / clock jumpRate difference between clocks / discontinuous step
monotonic clockClock that never goes backwards; for measuring elapsed time
RedlockClient-side majority lock over N independent Redis masters
Kleppmann critique2016 argument: Redlock lacks fencing and depends on timing
split brainTwo parties both believe they hold the lock / leadership
fencing token / monotonic tokenIncreasing number per acquisition, checked by the resource
sequencerChubby/Consul name for a token identifying the lock generation
leaseTime-bounded ownership that expires unless renewed
etcd leaseetcd object with TTL; attached keys deleted on expiry
Txnetcd atomic If/Then/Else over comparisons
linearizableEvery operation appears to take effect at one instant in real-time order
ephemeral nodeZooKeeper znode deleted when its session ends
sequential nodeZooKeeper znode with an increasing suffix appended by the server
herd effectWaking all waiters when only one can proceed
Consul sessionConsul liveness contract binding locks to nodes, checks and TTL
lock-delayConsul/Chubby pause before a released lock can be re-acquired
LockIndexConsul counter incremented on each acquire
pg_advisory_lock / pg_try_advisory_lockPostgreSQL session-level advisory lock, blocking / non-blocking
pg_advisory_xact_lockTransaction-level advisory lock, released at commit/rollback
FOR UPDATE SKIP LOCKEDRow locking that skips rows locked by others; queue claims
work claimMarking rows as taken by a worker, usually with SKIP LOCKED and a claim expiry
lease columnexpires_at/holder/fence_token columns that implement a lease in SQL
check-then-actNon-atomic read then write; the classic race
raceOutcome depends on timing of concurrent actors
unlock other's lockDeleting a lock that now belongs to another holder
idempotencyRepeating an operation has no additional effect
CAS / optimistic concurrencyWrite only if a value or version is unchanged; retry on conflict
single writerOne owner per key or partition, so no lock is needed
Cache::lock / blockLaravel atomic lock; wait up to N seconds to acquire
restoreLock / forceRelease / refreshLaravel: re-instantiate by owner / release regardless / extend
onOneServerLaravel scheduler: run a task on one server per tick
withoutOverlapping / WithoutOverlappingLaravel scheduler option / job middleware preventing overlap
LockTimeoutExceptionLaravel exception when block() times out
leader electionChoosing one active node; a long-lived lock with a lease
Kubernetes Leasecoordination.k8s.io object with holder, duration, renew time
Redisson / RedsyncJava Redis client with locks and watchdog / Go Redlock library
miniredisIn-memory Redis server for Go tests, with Lua and FastForward

References ​

Built by Morteza Negahi