Skip to content

Distributed Locks

Advanced 48 min read Part 9 of 18

When you need a distributed lock vs a database lock: Redis locks, the Redlock debate, ZooKeeper and etcd locks, TTL problems, fencing, alternatives.

Summary#

A distributed lock gives one process, among many running on different machines, exclusive access to a shared resource for a while: one worker processes a given order, one user holds a given seat during checkout, one job renders a given video. Before reaching for one, check whether the database can enforce the rule itself, with a conditional update, a row lock inside a short transaction, a unique constraint, or optimistic concurrency with a version column. That is often simpler and safer. When you do need a lock across services, the common tool is Redis: SET lock:seat:42 my-random-token NX PX 30000 creates the key only if it is absent, with a 30-second expiry, and a small Lua script deletes it only if it still holds your token. This is fast, around a millisecond, and fine for efficiency locks that prevent duplicate work. It is not a correctness guarantee: Redis replication is asynchronous, so a failover can lose the lock, and Redlock, which takes the lock on a majority of independent Redis nodes, was sharply criticised by Martin Kleppmann in 2016 for relying on timing assumptions. For correctness, use a lock in a consensus system, ZooKeeper, etcd or Consul, and in every case remember that a TTL can expire while the holder is paused, so the holder can act after losing the lock. The defence is a fencing token, an increasing number issued with each lock grant and checked by the resource, which rejects writes carrying an older one. Often the best lock is no lock: optimistic concurrency, or serializing all operations on a key through one partition of a queue.

Why It Exists#

Picture a concert with one seat left. Alice and Bob press "Buy" at the same instant. Each request goes to a different application server. Each server reads the seat's status from the database, sees "available", and goes on to charge the customer's card and mark the seat as sold. Both charges succeed. Both customers get a confirmation for the same seat. This is a race condition: the outcome depends on the timing of operations that each look correct in isolation.

Inside one process, you would wrap the check and the update in a mutex, and the operating system would ensure only one thread runs it at a time. With many servers, there is no shared memory and no shared operating system. Some shared component must make the decision instead. That component could be:

  • The database that holds the data, through transactions, row locks, conditional updates, or constraints. This is usually the best answer, because the check and the change happen in the same place, atomically.
  • A separate lock service, when the protected work is not a single database operation: it spans several systems, calls external APIs, takes minutes, or the resource is not in a database at all, such as a file being processed, a third-party account being reconciled, or a seat being held while a customer types their card number.

That second case is what distributed locks are for. They are deceptively simple to build and deceptively hard to make correct, because a lock holder can crash, pause or be partitioned while holding the lock, and the system has to decide when to give the lock to someone else without knowing whether the first holder has really stopped.

How It Works#

When you need one (and when a DB lock is enough)#

Two reasons to lock. Martin Kleppmann's 2016 essay "How to do distributed locking" draws a distinction that settles most design questions:

  • Efficiency locks prevent the same work being done twice, such as sending the same digest email, recomputing the same expensive report, or transcoding the same video. If the lock occasionally fails and two processes do the work, the cost is some wasted compute or a duplicate notification. A simple, fast lock, such as a single Redis instance, is enough.
  • Correctness locks prevent damage, such as two people booking the same seat, two withdrawals overdrawing an account, or two writers corrupting a file. If the lock fails, data becomes wrong. These need a lock that is safe under failover and pauses, and fencing at the resource, or better, enforcement of the invariant in the database itself.

When the database is enough. If the shared state lives in one database, and the critical section is a single short transaction, let the database do it.

  • Conditional writes (atomic compare-and-set): make the check part of the update, so it cannot race.
-- Reserve the seat only if it is still available; the database serialises this
UPDATE seats
SET    status = 'reserved', holder = :user, hold_until = now() + interval '10 minutes'
WHERE  seat_id = :seat
  AND  (status = 'available' OR (status = 'reserved' AND hold_until < now()));
-- 1 row updated: you have it. 0 rows: someone else does.
  • Pessimistic row locks inside a short transaction: SELECT ... FOR UPDATE locks the row until commit, so a second transaction waits. Use it when you must read, compute and write within one transaction.
  • Optimistic concurrency control (OCC): read the row with its version, compute, then UPDATE ... SET ..., version = version + 1 WHERE id = :id AND version = :read_version. If another writer got there first, zero rows change, and you retry. No lock is held while you think.
  • Unique constraints: a unique index on (event_id, seat_id) in a bookings table makes double booking impossible, whatever the application does.
  • Serializable isolation: the strongest isolation level makes the database detect conflicting transactions and abort one of them. See Concurrency Control and Database Locking.

When a distributed lock is the better tool.

  • The protected operation spans several systems: a database write, a call to a payment provider, and a message publish.
  • The resource is not in a database: an object in blob storage, a file on a shared volume, a single-threaded external API, or a device.
  • The lock must be held for a long time (seconds to minutes), such as while a user completes checkout, during which holding a database row lock would tie up a connection and block other queries.
  • You want to prevent duplicate work across many workers cheaply, without touching the database.
  • Many services need to coordinate on the same named resource and do not share a database.

When you need one, in depth#

The race, step by step. The seat example fails like this, with no lock:

TimeAlice's serverBob's serverSeat in database
t1Reads seat 12: availableavailable
t2Reads seat 12: availableavailable
t3Charges Alice $500available
t4Charges Bob $500available
t5Writes seat 12: sold to Alicesold, Alice
t6Writes seat 12: sold to Bobsold, Bob

The read at t2 is stale by t5, but Bob's server has no way to know. With a conditional write, the update at t6 would include WHERE status = 'available', match zero rows, and Bob's server would refund the charge, or better, would have reserved the seat with a conditional write before charging.

Pessimistic versus optimistic. Grabbing a lock before doing the work, whether a database row lock or a Redis lock, is pessimistic: it assumes conflict is likely and prevents it. Checking for conflict only at write time, with a version number, is optimistic: it assumes conflict is rare and retries when it happens. People sometimes call the Redis SET NX pattern "optimistic", but it is pessimistic, since the lock is taken first. Redis itself supports optimistic transactions too: WATCH a key, read it, then MULTI ... EXEC, which aborts if the watched key changed. Rules of thumb:

  • Low contention (conflicts in well under 10% of attempts): optimistic is faster, since there is no lock round trip and nothing blocks.
  • High contention on the same row: optimistic retries can pile up and waste work, so pessimistic locking, or a queue, is better.
  • Long think time between read and write: avoid holding database locks; use optimistic checks or a reservation with expiry.

Why long-running database locks are a bad idea. For a checkout that lasts several minutes, a tempting design is to SELECT ... FOR UPDATE the seat and keep the transaction open until the user pays. This ties up a database connection per shopper, holds row locks that block other queries, and increases the risk of deadlocks. If the application crashes, the lock persists until the database notices the dead connection. Timeouts such as PostgreSQL's lock_timeout turn waiting into errors rather than graceful queueing. Database locks are meant for transactions lasting milliseconds.

Reservations as data, not locks. The better pattern for long holds is to store the reservation in the row itself: status and hold_until, set by a conditional update like the one above. The seat is effectively available if its status is available or its hold has expired, so no background job is needed for correctness. A periodic sweep can still tidy expired holds for readability, but if it is delayed, nothing breaks. This is a lock with a TTL, implemented inside the database, and its check is atomic with the data.

Deadlocks. With pessimistic locking, two transactions can each hold a lock the other needs: T1 locks seat A then wants seat B, while T2 locks B then wants A. Neither can proceed. Defences:

  • Lock ordering: always acquire locks in a fixed global order, such as by ascending seat ID. A cycle is then impossible.
  • Timeouts: give up after a bounded wait, and retry with back-off.
  • Detection: databases such as PostgreSQL and MySQL detect cycles in the wait-for graph and abort one transaction, which the application must retry.
  • Acquire all or nothing: take every lock needed up front, and release everything if any fails.

The same applies to distributed locks: a process that holds lock A in Redis and waits for lock B can deadlock with one doing the reverse, and TTLs only break the deadlock by expiring a lock that someone might still be using.

The ABA problem. Optimistic checks that compare values can be fooled: a process reads balance 100, another process changes it to 50 and back to 100, and the first process's check "is it still 100?" passes, although the state changed underneath it, and decisions based on the intermediate history may be wrong. Comparing a version number that increments on every write, rather than the value, avoids this, since the version would have moved from 7 to 9. Fencing tokens are monotonically increasing for the same reason.

Hot resources. When thousands of requests contend for the same lock, such as one hot product's inventory during a flash sale, every lock design becomes a queue, with most requests waiting. Better options: split the resource (for example, 100 inventory buckets of 10 units each), admit users through a waiting room, or serialise all operations on the hot key through a single consumer, as described under alternatives below. See Pattern: Dealing with Contention.

Redis SET NX PX lock#

Redis is the most common lock service in practice, because most systems already run it, it is fast, and every command executes atomically on its single-threaded event loop. The lock is just a key that every process agrees on, such as lock:order:8812.

Acquire. Try to create the key, with a value unique to this attempt and an expiry:

SET lock:order:8812 3f9c1e7a-holder-token NX PX 30000
  • NX sets the key only if it does not exist. If the reply is OK, you hold the lock. If it is nil, someone else does.
  • PX 30000 gives the key a 30-second time-to-live, so a holder that crashes cannot keep the lock forever. EX 30 does the same in seconds.
  • The value is a random token, such as a UUID, unique to this holder and this acquisition. It identifies who owns the lock.

Older code sometimes uses SETNX followed by a separate EXPIRE. That is unsafe: if the client crashes between the two commands, the key never expires. The single SET ... NX PX command, available since Redis 2.6.12, is atomic.

Release. Do not simply DEL the key. Your lock may have expired while you were working, and another client may now hold it, in which case a blind delete would remove their lock. Instead, delete only if the value is still your token, atomically, with a Lua script, which Redis runs as one indivisible command:

-- KEYS[1] = lock key, ARGV[1] = my token
if redis.call("GET", KEYS[1]) == ARGV[1] then
  return redis.call("DEL", KEYS[1])
else
  return 0   -- not mine any more: expired and possibly re-acquired
end

Extend. If the work might take longer than expected, the holder can extend the lock before it expires, again only if it still owns it:

-- KEYS[1] = lock key, ARGV[1] = my token, ARGV[2] = new TTL in ms
if redis.call("GET", KEYS[1]) == ARGV[1] then
  return redis.call("PEXPIRE", KEYS[1], ARGV[2])
else
  return 0   -- lost the lock: stop working
end

Client libraries automate this. Redisson, a Java client, runs a "watchdog" that keeps extending a lock while the holding thread is alive, with a 30-second default lease, and libraries such as redlock-py, node-redlock and go-redsync provide acquisition, release and extension.

Waiting for a lock. A client that fails to acquire can retry after a short, randomised delay, with a limit on total waiting, or subscribe to a release notification through pub/sub or keyspace notifications. Retrying in a tight loop from many clients overloads Redis exactly when the lock is contended. For user-facing flows, failing fast with "this seat is being purchased by someone else" is often better than waiting.

Locking several resources. A user who selects four seats needs four locks. Acquire them in a fixed order, such as by seat ID, and if any acquisition fails, release the ones you already hold. If all the keys are on the same Redis node, which in Redis Cluster means giving them the same hash tag, such as lock:{event:77}:seat:12, a single Lua script can acquire them all atomically.

Redis SET NX PX lock, in depth#

A worked example: holding seats during checkout. A ticketing service lets a user hold a seat for 10 minutes while they pay.

  1. The user selects seat 12 for event 77. The booking service runs SET hold:77:12 user-981 NX PX 600000. If it fails, the seat is taken and the user is told so.
  2. The service writes a booking row with status in_progress and returns a booking ID. The seats table itself now only needs two states, available and sold, since holds live in Redis.
  3. The user pays through the payment provider. When the provider's webhook confirms payment, a database transaction marks the seat sold and the booking confirmed, using a conditional update so that a seat can only be sold once, and the hold key is deleted.
  4. If the user abandons checkout, the key expires after 10 minutes, and the seat becomes available again with no clean-up job.

The value is the user ID, so the confirmation step can check that the user confirming is the one who held the seat. The webhook handler must be idempotent, since payment providers retry webhooks, with the booking ID as the idempotency key.

Showing held seats on the seat map. The seat map must show held seats as unavailable. Listing all hold:77:* keys with SCAN is too slow. A plain Redis set of held seat IDs does not work either, because set members do not expire when the hold keys do, so abandoned holds would leave seats looking taken forever. A sorted set scored by expiry time does work: ZADD held:77 1767225600000 12 when holding, where the score is the hold's expiry in milliseconds. The seat map counts only members whose score is in the future, with ZRANGEBYSCORE held:77 from the current time to +inf, and stale members are trimmed lazily with ZREMRANGEBYSCORE held:77 -inf up to the current time. Alternatively, write a reserved status to the database alongside the Redis hold, treating Redis as the authority on expiry, and sweep stale database rows periodically.

What if Redis is down? Users cannot hold seats, so checkout degrades: either they proceed without a hold and may lose the seat at payment time, or holds are refused until Redis returns. Crucially, double booking still cannot happen, because the database's conditional update on the seat is the real guard. The lock improves the experience. The database enforces correctness. That division is the right one.

What if the hold expires during payment? User A's hold expires at minute 10, and their payment completes at minute 11. In between, user B may have acquired a hold on the same seat. When both payments complete, the database's conditional update lets exactly one of them mark the seat sold, and the other booking fails and is refunded automatically. Make the TTL generous, and extend the hold when payment starts, so this is rare. But it can never be ruled out by the lock alone.

The failover problem. Redis replication is asynchronous. Consider a primary with one replica, and automatic failover through Sentinel or Redis Cluster:

  1. Client A acquires lock:x on the primary, which replies OK.
  2. The primary crashes before the write reaches the replica.
  3. The replica is promoted. It has never heard of lock:x.
  4. Client B acquires lock:x on the new primary, and succeeds.

Both clients now hold the lock. The WAIT numreplicas timeout command makes the primary wait until a write has reached a number of replicas, which narrows the window, but it does not make replication synchronous in the consensus sense: a replica that acknowledged may still not be the one promoted, and Redis does not guarantee that the promoted replica has every acknowledged write. Persistence settings matter too: a single Redis instance that restarts without an fsynced append-only file loses its locks, and a client could acquire a lock that another client still believes it holds. That is why a single-instance Redis lock, however convenient, is an efficiency lock.

The Redlock debate#

To survive the failure of a single Redis node, Salvatore Sanfilippo (antirez), the creator of Redis, proposed Redlock, described in the Redis documentation. It uses N independent Redis primaries, typically 5, with no replication between them, ideally on separate machines.

The algorithm:

  1. Record the current time.
  2. Try to acquire the lock on each of the N nodes in turn, with the same key and random value, using SET key value NX PX ttl, and a small per-node timeout, for example 5 to 50 ms, so that a dead node does not stall the attempt.
  3. Compute how long acquisition took. The lock is acquired only if it was set on a majority of nodes (at least 3 of 5) and the elapsed time is less than the TTL.
  4. The lock's validity time is the TTL minus the elapsed time, minus an allowance for clock drift between nodes.
  5. If acquisition fails, release the lock on all nodes, including the ones that did not reply, and retry after a random delay.
  6. Release by running the check-and-delete script on all nodes.

The critique. In February 2016, Martin Kleppmann published "How to do distributed locking", arguing that Redlock is unsuitable for correctness:

  • No fencing. Redlock produces random values, not monotonically increasing tokens, so the resource cannot reject a stale holder. Any lock with expiry, Redlock included, needs fencing to be safe against pauses, and Redlock cannot supply it.
  • Process pauses. A client acquires the lock, then pauses, in garbage collection, page faults, or a VM being descheduled, for longer than the validity time. The lock expires, another client acquires it, and the first client resumes and acts, believing it still holds the lock. Checking the time before acting does not help, because the pause can happen between the check and the action.
  • Network delays. A request sent while the lock was valid can be delayed in the network and arrive at the resource after the lock expired.
  • Clock jumps. Redlock relies on each Redis node's expiry being measured correctly. If one node's clock jumps forward, for example after an administrator or NTP steps it, that node expires the key early. A second client can then gather a majority that includes this node, while the first client still holds a majority too, and both hold the lock.

His conclusion: for efficiency, a single Redis node is simpler and good enough; for correctness, Redlock's dependence on bounded network delay, bounded pauses and bounded clock error makes it unsafe, and a consensus system with fencing should be used instead.

The reply. Antirez responded in "Is Redlock safe?" the same month. His main arguments:

  • Fencing requires a resource that can check tokens, and if such a resource exists, its own compare-and-set could be used with Redlock's random value too, so the lack of a counter does not make Redlock uniquely weak.
  • Process pauses and network delays after acquisition affect every lock with automatic expiry, including ZooKeeper's, which also expires sessions on timeout. Redlock does check the elapsed time after acquisition, catching delays that happen during acquisition.
  • Clock jumps can be avoided operationally, by configuring time synchronisation to slew rather than step, and Redlock's assumption is about clock rate, not synchronised time.
  • On crash recovery without fsync, he recommended delayed restarts: a crashed node should stay unavailable for longer than the maximum TTL, so it cannot rejoin and grant a lock that was held on it before the crash.

Where the debate landed. Both sides agree on several points: a lock with expiry can be held by two clients when a holder pauses, so correctness requires the resource to reject stale holders; and a single Redis instance is fine for efficiency. The disagreement is whether Redlock's timing assumptions are acceptable for correctness. The view most practitioners adopted:

  • For efficiency, a single Redis instance, with token-checked release, is simpler than Redlock and nearly as good.
  • For correctness, do not rely on any lock alone. Use a consensus system, take a fencing token from it, and have the resource check it, or enforce the invariant in the database.
  • Redlock occupies an awkward middle: more complex and costly than a single node, and still not something to rely on for correctness.

The Redlock debate, in depth#

Timing assumptions, made explicit. Redlock is safe if, and only if, all of these hold: every client finishes its protected work, including any delayed network messages it sent, within the validity time; no client process pauses for a significant fraction of the TTL; and every Redis node measures the TTL at close to the same rate as the client. These are partially synchronous assumptions: they are usually true, and occasionally false. Consensus algorithms such as Raft are designed so that their safety never depends on such assumptions, only their liveness, as described in Consensus. Redlock's safety does depend on them. That is the precise technical content of the critique.

How big are pauses in practice? Garbage collection pauses in JVMs with large heaps have historically reached seconds, and occasionally tens of seconds, under memory pressure. Virtual machines can be paused for live migration. A process can be stopped by the operating system while it swaps, or by an operator's debugger. Disk I/O on a struggling network volume can block a thread for tens of seconds. None of these is common, but in a large fleet, running for years, all of them happen.

The persistence scenario. Suppose Redis nodes use append-only files with fsync every second, the default. Client A acquires the lock on nodes 1, 2 and 3. Node 3 crashes and restarts within a second, losing A's key, which had not been flushed. Client B now acquires the lock on nodes 3, 4 and 5, a majority. Both A and B hold the lock. Antirez's delayed-restart rule, keeping node 3 out of service for longer than the maximum TTL, prevents this, but it is an operational rule that must be enforced in deployment tooling, and it is easy to violate. fsync always also prevents it, at a large cost in write latency.

Why a counter is hard in Redis. A fencing token must increase with each grant. On a single Redis node, INCR gives a counter, but if that node fails over, the counter may go backwards, since the promoted replica may have missed recent increments. Across five independent Redlock nodes, there is no single counter at all. A consensus system, by contrast, has a natural, durable, increasing number: the Raft log index or etcd revision, or ZooKeeper's zxid, which are exactly what their lock recipes use.

Practical guidance for Redis users.

  • Use a single primary, with token-checked release and extension, for efficiency locks.
  • Choose TTLs well above the expected work time, and extend them while working.
  • Keep the critical section idempotent, so a rare double holder causes no harm.
  • If two holders would corrupt data, enforce the invariant where the data lives, through conditional writes, version checks or fencing tokens, not in Redis.

ZooKeeper and etcd locks#

Coordination services built on consensus give locks that survive server failures without losing the lock and that come with a natural fencing token. The cost is latency, a few milliseconds per acquisition instead of under one, and operating the service.

The ZooKeeper lock recipe. ZooKeeper's documentation describes a lock built from ephemeral sequential znodes, the same structure as its leader election recipe:

  1. To acquire lock /locks/order-8812, the client creates an ephemeral sequential child: /locks/order-8812/lock-0000000031.
  2. It lists the children. If its znode has the lowest sequence number, it holds the lock.
  3. Otherwise, it sets a watch on the child with the next lower sequence number, and waits.
  4. When that predecessor is deleted, it lists the children again. Usually it now holds the lock. If the predecessor had simply given up waiting, it watches the new predecessor instead.
  5. To release, it deletes its own znode. If it crashes, or its session expires, ZooKeeper deletes the ephemeral znode automatically.

This design has three useful properties. Fairness: clients get the lock in the order they asked, like a queue. No herd effect: each release wakes exactly one waiter. Automatic release on failure: a crashed holder's session expires after its timeout. And the sequence number, or the zxid at which the znode was created, increases with every acquisition, so it is a fencing token.

A read-write lock variant uses read- and write- prefixes: a reader holds the lock if no write znode has a lower number, and a writer holds it only if its znode is the lowest of all. Apache Curator implements these as InterProcessMutex, InterProcessReadWriteLock and InterProcessSemaphoreV2, handling the edge cases, such as a create request whose response was lost, which Curator handles by embedding a unique ID in the znode name so the client can find its own node after a reconnect.

etcd locks. etcd's concurrency package provides a Mutex built on leases and revisions: each client creates a key under the lock's prefix attached to its lease, the key with the lowest create revision holds the lock, and each waiter watches the key with the next lower revision. etcdctl lock mylock gives the same from a shell. The holder's key revision is a fencing token, since revisions increase across the whole store. The lock is released when the holder deletes its key, or when its lease expires after keep-alives stop.

Consul locks. Consul's sessions plus PUT ?acquire= on a key give a lock that is released when the session is invalidated, through TTL expiry, failed health checks on the node, or explicit destruction. Consul also applies a lock delay, 15 seconds by default, after a session is invalidated: the lock cannot be reacquired during that time, which gives a holder that lost its session time to notice and stop. This idea comes from Chubby.

Chubby's sequencers. Google's Chubby lock service (Mike Burrows, OSDI 2006) addressed the stale-holder problem directly. A lock holder can request a sequencer, an opaque byte string describing the lock's name, mode and generation number, and pass it to the servers it sends requests to. Those servers check with Chubby, or against a cached latest generation, that the sequencer is still valid before acting. For servers that cannot check sequencers, Chubby offers a lock-delay: when a holder fails, the lock cannot be granted to anyone else for a configurable period, up to a minute, so that delayed messages from the old holder are likely to arrive before a new holder starts. The paper presents these as the two levels of protection, with sequencers the robust one. Fencing tokens are sequencers by another name.

ZooKeeper and etcd locks, in depth#

Session expiry is not instant knowledge. A ZooKeeper lock is released when the holder's session expires on the server side. The client learns about this only when it reconnects, or when its own timer passes. Between the server expiring the session and the client noticing, the client may still believe it holds the lock. Curator's connection state listener reports SUSPENDED when the connection is lost and LOST when the session is known to have expired. Safe clients stop protected work on SUSPENDED, not just on LOST. Even so, a client that is paused cannot react at all, which brings us back to fencing: consensus-backed locks are safe against server failures, but not against client pauses, without a token checked by the resource.

Why consensus-backed locks are safer than Redis locks. The lock state is replicated by ZAB or Raft, so a lock acknowledged by the ensemble is on a majority of servers, and any new leader has it. Failover of the coordination service never forgets a granted lock, which is precisely the failure that breaks single-primary Redis locks. The fencing token comes from a counter that never goes backwards, for the same reason. And because sessions and leases are tracked by the consensus leader, with lease extension on leader change, a coordination service failover does not release every lock at once.

Performance. A ZooKeeper or etcd lock acquisition is a consensus write: a few milliseconds within a region, plus a watch notification for waiters. A ZooKeeper ensemble or an etcd cluster handles thousands to tens of thousands of such writes per second. Redis handles about a hundred thousand simple commands per second per core with sub-millisecond latency. If locks are needed per request at very high rates, a consensus store will become the bottleneck, which is usually a sign that the design should use partitioning, optimistic concurrency or a queue instead of a lock per operation.

Lock granularity. Coarse-grained locks, held for minutes or hours, such as "this process is the primary for shard 7", suit consensus stores well, since acquisition is rare. Chubby's authors explicitly designed for coarse-grained locks and advised building fine-grained locking inside applications if needed, using a coarse lock to assign ownership of groups of fine-grained locks. Fine-grained locks, held for milliseconds, per request or per row, belong in the database or in a partitioned in-process lock manager.

Semaphores and leases for counted resources. Sometimes up to N holders are allowed, such as at most 10 concurrent calls to a rate-limited partner API. ZooKeeper's semaphore recipe and Curator's InterProcessSemaphoreV2 implement this with sequential nodes: the first N children hold leases. etcd can do the same with a count of keys under a prefix checked in a transaction. Redis implementations exist using sorted sets scored by expiry time, with the same caveats about failover.

TTL expiry problems#

Every practical distributed lock has a time-to-live, because without one, a holder that crashes would hold the lock forever. But expiry creates the central problem of distributed locking: the lock can expire while the holder is still working, and a second holder can then start.

How work outlives a TTL:

  • The work is slower than expected: a database is slow, a downstream service times out and retries, a file is larger than usual.
  • The process pauses: garbage collection, swapping, VM migration, CPU starvation, or a debugger.
  • Renewals fail: the network to the lock service is congested, or the lock service is overloaded, so extensions do not arrive in time, while the holder's network path to the resource still works.
  • Messages are delayed: a write sent while the lock was valid sits in a queue, a TCP retransmission or a proxy, and arrives after expiry.
  • Clocks misbehave: the lock service's expiry clock jumps forward, or the holder measures its remaining time with a wall clock that is stepped.

Choosing a TTL. A TTL is a trade-off:

  • Too short: locks expire during normal work, causing duplicate holders often, not rarely.
  • Too long: when a holder crashes, the resource stays locked until expiry, stalling everyone else. A checkout hold of 10 minutes is fine. A worker lock of 10 minutes on a job that usually takes 2 seconds means a 10-minute stall whenever a worker crashes.

A common approach is a short TTL with renewal: a TTL of a few times the renewal interval, for example 30 seconds renewed every 10, so a crash frees the lock within 30 seconds, while long work keeps it alive. The holder must stop working as soon as a renewal fails, or as soon as its own conservative deadline passes, measured with a monotonic clock from the moment the last successful renewal was sent.

Checking before acting is not enough. A holder can check "do I still hold the lock?" before each write. That narrows the window, but cannot close it: the pause can occur between the check and the write, and the write can be delayed in the network after being sent. As long as the resource accepts the write without its own check, a stale holder can always slip through.

A worked timeline. A worker holds lock:report:2026-12 with a 30-second TTL, renewing every 10 seconds.

TimeWorker ALock serviceWorker BStorage
0 sAcquires, token 51Lock held by A until 30 s
10 sRenewsHeld by A until 40 s
12 sFull GC pause begins
40 sStill pausedLock expires
41 sLock held by B, token 52Acquires
45 sWrites report, token 52Accepts, highest token 52
52 sPause ends; writes reportRejects token 51, if it checks tokens

Without the token check at 52 s, A's stale report overwrites B's correct one. A's renewal timer is also stale: if A checked its deadline at 52 s, it would see the lock had expired, but if the pause had started just after a deadline check and just before the write, the check would have passed. Only the storage-side check is reliable.

Fencing tokens#

A fencing token is a number that increases with every grant of the lock, given to the holder with the lock, and sent with every request to the protected resource. The resource remembers the highest token it has accepted and rejects any request carrying a lower one. This makes expired holders harmless, regardless of pauses, delays and clocks, as long as the resource checks atomically.

Where the token comes from:

  • ZooKeeper: the lock znode's sequence number, or its creation zxid.
  • etcd: the lock key's create revision, or the revision returned by the acquiring transaction.
  • Consul: the lock index, LockIndex in the key's metadata, increments each time the lock is acquired.
  • A database: an epoch or version column incremented in the same conditional update that grants the lock.
  • Not Redis or Redlock, without additional machinery, since neither has a counter that is guaranteed to survive failover.

How the resource checks it. The check must be part of the same atomic operation as the write:

-- Storage remembers the highest token per resource and refuses older ones
UPDATE reports
SET    body = :body, fence = :token
WHERE  report_id = '2026-12'
  AND  fence < :token;          -- strictly increasing: same token may not write twice
-- 0 rows updated: a newer lock holder has written; abort.

Use fence <= :token instead if one holder may write several times with the same token. For object stores, conditional writes with an expected version or ETag provide the same atomic check, and many key-value stores support compare-and-set on a version.

Fencing tokens, in depth#

When the resource cannot check tokens. Fencing requires cooperation from the resource. Many resources cannot do it: an email or SMS provider, a payment gateway, a legacy system, a printer. For these, two approaches remain:

  • Idempotency keys: give each logical operation a unique key, such as a booking ID, and have the provider deduplicate on it. Stripe and many other payment APIs accept an idempotency key for exactly this reason. A stale holder that retries an operation with the same key has no extra effect. See Idempotency.
  • A proxy that checks tokens: put a small service in front of the resource, which checks the token against a stored maximum before forwarding. The proxy itself becomes the fenced resource.

Fencing with many resources. If the lock protects writes to several resources, each must check the token independently, and a stale holder might succeed at a resource that the new holder has not yet touched. Two mitigations: the new holder can write its token to each resource first, "claiming" it, before doing work, or the resources can share a single fence record, for example a row in the database that each write transaction checks.

Tokens and lock re-entry. A holder that releases and immediately reacquires the lock gets a new, higher token. In-flight requests carrying its old token will be rejected, so a holder should not release and reacquire while requests are outstanding.

Fencing is the general principle; locks are an optimisation. Once the resource checks tokens, the lock's job is only to make conflicts rare, so that the work is not wasted. Correctness comes entirely from the resource's check. Seen this way, a distributed lock is an efficiency mechanism layered over an optimistic concurrency check, which is exactly what optimistic concurrency control, conditional writes and fencing all are.

Alternatives (optimistic concurrency, serializing via a queue)#

Locks are often the first idea and rarely the best one. These alternatives avoid many of their failure modes.

Optimistic concurrency control. Every record carries a version. A writer reads the record and its version, does its work, and writes back conditionally: "update only if the version is still 7, and set it to 8". If someone else wrote first, the update affects no rows, and the writer re-reads and retries, or reports a conflict to the user. Nothing is held while the writer thinks, so a crashed or paused writer blocks nobody, and a stale writer's update simply fails. This works in any database with atomic conditional updates: SQL UPDATE ... WHERE version = :v, DynamoDB condition expressions, Cassandra lightweight transactions, MongoDB's findOneAndUpdate with a version filter, and HTTP APIs with ETag and If-Match. It is the default choice when contention is low and the state lives in one store.

Conditional writes on the invariant. Often there is no need for a version at all: write the invariant directly into the condition. "Decrement stock where stock is greater than zero." "Insert the booking; a unique index on the seat rejects a second one." "Set status to shipped where status is paid." The database guarantees that only one of two racing writers satisfies the condition.

Serializing through a queue. Instead of letting many workers race for a resource and locking it, route every operation on the same key to the same single consumer, which processes them one at a time. With Kafka, use the resource ID as the message key: all messages with the same key go to the same partition, and each partition is consumed by exactly one consumer in a group, in order. A bank account's deposits and withdrawals, keyed by account ID, are then applied strictly one after another by one process, with no locks at all. Kafka's consumer group protocol does the coordination: when a consumer dies, its partitions are reassigned, and the new owner continues from the last committed offset. Kafka also fences "zombie" consumers and producers through generation numbers and producer epochs, which is fencing again, built into the platform. See Delivery Semantics.

The single-writer principle and actors. Systems such as LMAX's trading platform, actor frameworks like Akka and Orleans, and Cloudflare Durable Objects give each entity a single owner, an actor or object, that processes its messages sequentially. Concurrency control becomes the problem of ensuring there is only one owner per entity, which the framework handles with its own leases and fencing, and the application code is single-threaded per entity.

Partitioned ownership. Assign ranges of keys to workers through a coordination service, one lease per range rather than one lock per key, as described in Leader Election and Coordination. Each worker then uses ordinary in-memory locks for the keys it owns.

Commutative operations and CRDTs. If the operations can be applied in any order, such as incrementing a counter or adding to a set, no lock is needed: replicas apply updates independently and merge. See Collaborative Editing and CRDTs.

Reservations with expiry in the database. As in the seat example, store status and hold_until in the row and claim it with a conditional update. This is a lock with a TTL, but its check is atomic with the data, so it cannot be held by two writers.

Alternatives, in depth#

Comparing the approaches on one problem. Ten thousand users try to buy the last 100 units of a product in one minute.

ApproachWhat happensThroughput limitFailure behaviour
Distributed lock per productEvery request queues for one lock, about 2 ms eachAbout 500 purchases per second, with long waitsLock holder crash stalls everyone until TTL
SELECT FOR UPDATE per product rowRequests queue on the row lockSimilar, plus database connections tied upDeadlock and connection exhaustion risk
Optimistic concurrency with a versionMost writers fail their condition and retryWasted work grows with contentionSafe; retry storms if unbounded
Conditional decrement, stock > 0Each request is one atomic update, no read firstThousands per second on one rowSafe; excess requests simply fail
Bucketed stock (10 rows of 10 units)Requests pick a random bucketRoughly ten times one rowSafe; buckets may need rebalancing near zero
Queue keyed by product, single consumerRequests enqueued; one consumer decrements in memory and persistsTens of thousands per second, with batchingSafe; consumer failover adds seconds of delay

For this problem, the conditional decrement is simplest, and the queue scales furthest. The lock is the worst option, because it serialises the work and adds a network round trip to the critical path. See Design a Flash Sale and E-commerce Checkout.

When OCC retries become a problem. With N writers contending on one record, each round lets one succeed while N minus 1 retry, so total work grows quadratically under sustained contention. Mitigations: random back-off between retries, a cap on retries with an error to the user, and switching hot records to pessimistic locking or a queue. Monitoring the conflict rate tells you when this is happening.

Queues change the user experience. Serializing through a queue makes the operation asynchronous: the user's request is accepted, and the result arrives later, by polling, a webhook, or a push notification. For a flash sale, that is acceptable and even desirable. For an interactive form that needs an immediate answer, a synchronous conditional write is better.

Isolation levels as an alternative to explicit locks. Under serializable isolation, as in PostgreSQL's serializable snapshot isolation, CockroachDB and Spanner, the database detects read-write conflicts between concurrent transactions and aborts one, so application code can read, decide and write without explicit locks, and simply retry on serialization failures. Under weaker levels, such as read committed or snapshot isolation, some anomalies, such as write skew, remain possible, and explicit locks or conditions are needed. See Concurrency Control and Database Locking.

When to Use It#

  • Preventing duplicate work across workers: scheduled jobs, cache rebuilds, expensive recomputations, or webhook processing, where an occasional duplicate is tolerable. A Redis lock is enough.
  • Long holds on resources during user flows: seat or inventory holds during checkout, a driver offered a trip for 10 seconds, a document checked out for editing, usually with a TTL.
  • Coordinating work across systems that do not share a database, such as a file in object storage processed by one of many workers, with fencing at the storage layer.
  • Serialising access to an external resource that cannot handle concurrent use, such as a partner API that allows one session per account.
  • Coarse-grained ownership: one process owns a shard, a tenant, or a queue for minutes or hours, through a consensus store.

When NOT to Use It#

  • When the database can enforce the rule: use conditional writes, unique constraints, OCC or short transactions instead.
  • For every request on a hot path: a lock round trip per request adds latency and serialises the work. Partition, queue or use atomic operations.
  • As the only guard for correctness, without fencing or a database-level check.
  • With Redlock for correctness: it adds complexity without removing the need for fencing.
  • When operations can be made idempotent and duplicates are harmless.
  • For locks held across long human actions in the database, such as an open transaction during checkout.
  • When the resource is naturally partitioned: give each partition an owner instead of locking each item.

How to Implement It#

  1. State the invariant the lock protects, and ask whether the database can enforce it directly. If so, stop there.
  2. Classify the lock as efficiency or correctness. Use a single Redis instance for efficiency, and ZooKeeper, etcd, Consul or a strong database for correctness.
  3. Name locks by resource, such as lock:order:8812, and keep them as fine-grained as the work allows.
  4. Acquire atomically with a TTL and a unique token: SET key token NX PX ttl, an etcd lease-backed key, or a ZooKeeper ephemeral sequential znode.
  5. Pick the TTL from the work time and the acceptable stall after a crash, and renew while working. Stop work immediately if a renewal fails or the local deadline passes.
  6. Release safely: delete only if the token still matches, with a Lua script or the coordination service's recipe.
  7. Fence every write: pass the lock's increasing token, and make the resource reject older tokens atomically. Where impossible, use idempotency keys.
  8. Bound waiting: retry with jittered back-off and a deadline, or fail fast to the user.
  9. Avoid deadlocks: acquire multiple locks in a fixed order, all or nothing.
  10. Monitor lock wait time, hold time, acquisition failures, expiries during work, and fencing rejections. Each fencing rejection is a lock failure caught in time.

A small Redis lock helper for efficiency locks, with token-checked release and renewal:

import { randomUUID } from "crypto";
 
const RELEASE = `if redis.call("GET", KEYS[1]) == ARGV[1] then return redis.call("DEL", KEYS[1]) else return 0 end`;
const EXTEND  = `if redis.call("GET", KEYS[1]) == ARGV[1] then return redis.call("PEXPIRE", KEYS[1], ARGV[2]) else return 0 end`;
 
export async function withLock<T>(redis: Redis, key: string, ttlMs: number, work: (signal: AbortSignal) => Promise<T>) {
  const token = randomUUID();
  const ok = await redis.set(key, token, "PX", ttlMs, "NX");
  if (ok !== "OK") return { acquired: false as const };
 
  const lost = new AbortController();
  const renew = setInterval(async () => {
    const extended = await redis.eval(EXTEND, 1, key, token, ttlMs).catch(() => 0);
    if (extended !== 1) lost.abort();             // lost the lock or Redis unreachable: stop
  }, ttlMs / 3);
 
  try {
    return { acquired: true as const, result: await work(lost.signal) };  // work must honour signal
  } finally {
    clearInterval(renew);
    await redis.eval(RELEASE, 1, key, token).catch(() => {});
  }
}

This is still an efficiency lock: a pause longer than the TTL, or a Redis failover, can let two holders run. If that would be harmful, protect the writes made inside work with a fencing token from a consensus store, or a conditional write on the data.

TechnologyFits when
Database conditional updates, OCC, unique constraintsThe state lives in one database; the best default for correctness
PostgreSQL SELECT ... FOR UPDATE and advisory locksShort critical sections in one database; advisory locks for named application locks
Redis SET NX PX with Lua release (Redisson, node-redlock, go-redsync)Fast efficiency locks and reservations with TTL; a database check behind it for correctness
RedlockRarely; only if you accept its timing assumptions and still fence or check at the resource
ZooKeeper with Apache Curator (InterProcessMutex, read-write locks, semaphores)Correctness locks in JVM and Apache ecosystems, with sequence-number fencing
etcd concurrency.Mutex, etcdctl lockCorrectness locks in cloud-native systems, with revision-based fencing
Consul sessions and acquireLocks tied to node health checks, with lock delay and LockIndex
DynamoDB lock client, conditional writesLease-based locks on DynamoDB, with a record version as fence
Kafka partitions keyed by resourceSerialising all operations on a key through one consumer instead of locking

Trade-offs#

OptionProsConsPick when
Database conditional write or OCCAtomic with the data; no extra system; stale writers fail automaticallyOnly within one database; retries under heavy contentionThe state lives in one database; the default choice
SELECT ... FOR UPDATE in a short transactionSimple read-compute-write; database detects deadlocksBlocks other writers; ties up connections if held longCritical sections of milliseconds within one database
Reservation row with hold_untilLong holds without open transactions; expiry is implicitNeeds a sweep for tidiness; one more state to reason aboutHolds lasting minutes, such as checkout
Single Redis SET NX PXSub-millisecond; simple; already deployed in most stacksLost on failover or restart; no fencing tokenEfficiency locks; holds backed by a database check
RedlockSurvives the loss of a minority of Redis nodesFive nodes to run; depends on timing assumptions; still no fencingRarely; if used, still check at the resource
ZooKeeper or etcd lockSurvives server failures; fair queue; fencing token built inA few milliseconds per acquisition; another cluster to operateCorrectness locks and coarse-grained ownership
Queue partition per keyNo locks; strict per-key order; scales by partitionsAsynchronous results; consumer failover delay; hot keys stay hotHigh-throughput operations on many independent keys
Fencing tokens at the resourceSafe against pauses, delays and clock errorsRequires resource cooperationAny correctness lock with expiry

Common Pitfalls#

  • SETNX then EXPIRE as two commands: a crash in between leaves a lock that never expires. Use one SET ... NX PX.
  • Deleting the lock without checking the token: you may delete another client's lock after yours expired. Use the check-and-delete script.
  • No TTL, or a TTL shorter than normal work: the first means a crash stalls the resource forever; the second means two holders regularly.
  • Continuing after losing the lock: renewal failed, but the work carried on. Wire renewal failure to cancellation, as in the snippet above.
  • Trusting the lock alone for correctness: without fencing or a database condition, a paused holder will eventually corrupt data.
  • Using wall-clock time for deadlines: an NTP step can extend or shrink the holder's view of its lease. Use a monotonic clock.
  • Retrying acquisition in a tight loop: many clients hammering Redis or etcd when the lock is contended. Use jittered back-off and a deadline.
  • Locks per request on a hot path: adds a network round trip and serialises traffic. Use atomic operations, partitioning or a queue.
  • Acquiring several locks in inconsistent orders: deadlocks that TTLs only break by violating mutual exclusion.
  • Assuming Redis Cluster replication makes locks safe: replication is asynchronous, and failover can lose acknowledged locks.
  • Session-level PostgreSQL advisory locks behind a transaction-pooling connection pooler: the lock belongs to a server connection that other clients will share. Use transaction-level advisory locks or session pooling.
  • Holding a lock while calling a slow external service with no timeout: the lock lasts as long as the slowest call. Set timeouts shorter than the lock's remaining validity.

Real-World Examples#

  • Google Chubby (Mike Burrows, "The Chubby lock service for loosely-coupled distributed systems", OSDI 2006) provides coarse-grained locks and small files to systems such as GFS and Bigtable, which use it to elect masters and store metadata. It introduced the sequencer and lock-delay ideas described above, and its paper notes that most clients use it for leader election and naming rather than fine-grained locking.
  • Apache ZooKeeper and Curator: Curator's InterProcessMutex and related recipes are widely used for locks in JVM systems, and HBase, Hadoop and Solr rely on ZooKeeper for ownership and coordination.
  • etcd in Kubernetes: controllers and schedulers use lease-based leader election so that only one instance acts at a time, built on etcd's leases and revisions through the Kubernetes API.
  • HDFS NameNode high availability fences the old active NameNode through epoch numbers on the Quorum Journal Manager: journal nodes reject writes from a writer with a lower epoch, which is fencing by token, as described in Leader Election and Coordination.
  • Kafka transactional producers carry a producer epoch tied to their transactional.id. When a new instance with the same ID initialises, the epoch increments, and brokers reject writes from the old "zombie" instance.
  • Stripe's idempotency keys let clients retry payment requests safely: the same key returns the original result rather than charging twice, which makes a stale or duplicated lock holder harmless for payment calls.
  • AWS's DynamoDB lock client, an open-source library from AWS Labs, implements lease-based locks on DynamoDB with heartbeats and a record version number that changes on every update, using conditional writes.
  • The HBase GC pause problem: Kleppmann's essay cites HBase as a system where long garbage collection pauses led to a node acting on an expired lease, the scenario that motivates fencing tokens.

In the Interview#

Deep Dive: An end-to-end seat reservation designShow

Requirements. A ticketing platform sells 50,000-seat stadium events. A popular on-sale sees 1 million users in a waiting room, admits them at a controlled rate, and must never sell a seat twice. Users hold up to 8 seats for 10 minutes while paying. Peak admitted traffic is about 5,000 hold attempts per second, concentrated on the best sections.

Layer 1: admission. A virtual waiting room admits users in batches, such as 2,000 per minute, so the hold service sees a bounded load. Without it, every lock design would face millions of retries on the same few hundred seats. See Design a Ticket Booking System.

Layer 2: the hold. For each selected seat, the hold service runs a single Lua script on the Redis shard for the event, keyed with a hash tag so all of an event's seats live on one shard:

-- KEYS: seat hold keys for one event; ARGV[1] = user ID, ARGV[2] = TTL ms
for i, key in ipairs(KEYS) do
  if redis.call("EXISTS", key) == 1 then return 0 end   -- any seat taken: fail all
end
for i, key in ipairs(KEYS) do
  redis.call("SET", key, ARGV[1], "PX", ARGV[2])
end
return 1

All-or-nothing acquisition avoids partial holds and deadlocks, since the script is atomic. One Redis shard handles well over 5,000 such scripts per second, and a 50,000-seat event's holds use a few megabytes. The script also updates the event's sorted set of held seats, scored by expiry, for the seat map.

Layer 3: the database guard. When payment succeeds, the webhook handler runs:

UPDATE seats SET status = 'sold', booking_id = :booking
WHERE  event_id = :event AND seat_id = ANY(:seats) AND status = 'available';
-- Must update exactly as many rows as seats; otherwise roll back and refund.

inside a transaction with the booking's status change, keyed by the booking ID so webhook retries are idempotent. This guard is what makes double selling impossible, even if Redis failed over and two users held the same seat.

Failure analysis.

FailureEffectWhy it is safe
Redis primary fails over, losing recent holdsA second user may hold a seat already heldThe database update lets only one sale through; the other is refunded
Hold expires during a slow paymentAnother user may hold the seatSame: the database decides, the loser is refunded
Webhook delivered twiceSecond delivery finds the booking confirmedIdempotency on the booking ID
Hold service crashes after acquiringHolds expire after 10 minutesTTL; the seats return automatically
Redis unavailableNew holds fail; checkout pauses or proceeds without holdsThe database still prevents double sales

Numbers to quote. Refunds from lost holds should be rare: Redis failovers happen a few times a year at most, and expiry races affect only payments that exceed the hold time. If the refund rate rises above, say, 0.1% of orders, extend holds when payment starts, or move holds into the database rows with hold_until, which removes the race entirely at the cost of more database writes.

Deep Dive: Inside a lock service, Chubby's designShow

Why Google built a lock service rather than a library. The Chubby paper argues that a service is easier for application developers than a consensus library: existing programs can adopt locking with a few calls instead of being restructured as replicated state machines; the results of an election, such as who is the master, need to be advertised to others, which a service with small files does naturally; developers find locks familiar; and a client needs only one server to make progress, whereas a consensus library needs a quorum of the application's own replicas.

Architecture. A Chubby cell typically has five replicas, one of which is elected master through Paxos and holds a master lease for a few seconds, renewed while it keeps winning a majority. All reads and writes go to the master. Writes are replicated through the consensus protocol, and reads are served by the master alone, which is safe because, while its lease is valid, no other master can exist.

Sessions and KeepAlives. Each client maintains a session with the cell through periodic KeepAlive RPCs. The master extends the session lease, by around 12 seconds by default according to the paper, and blocks the KeepAlive reply until the lease is close to expiry, so the reply doubles as a channel for events and cache invalidations. If the client's local lease expires without a reply, it enters jeopardy: it disables its cache and waits for a grace period, 45 seconds by default, to see if the cell recovers, for example after a master failover. If the session is restored, the application continues. If not, the client library reports that the session has expired, and the application must assume its locks are gone.

Master failover without losing sessions. When a new master is elected, it reconstructs session and lock state from the replicated database, extends every session's lease conservatively, and rejects requests from old master epochs by checking an epoch number carried in each request. Clients' grace periods are what let sessions survive a failover that takes longer than a normal lease.

Locks are advisory and coarse-grained. A Chubby lock prevents only other Chubby lock acquisitions: holding the lock on a file does not stop anyone from writing the protected resource directly. Chubby's authors chose advisory locks and expected locks to be held for hours or days, which keeps load on the cell low. Fine-grained locking, they suggested, should be built by applications themselves, using Chubby only to allocate groups of fine-grained locks to application-level lock servers.

Protection against delayed and stale requests. Exactly the two mechanisms described earlier: sequencers, checked by resource servers, and lock-delay, applied when a holder fails without releasing. The paper is candid that sequencers are the robust mechanism and lock-delay a pragmatic one for servers that cannot check sequencers.

Lessons the paper reports. Developers often used Chubby as a name service, which became its most common use, more than locking. Caching with invalidation, not timeouts, kept read load manageable. Clients that misused the service, for example by polling or by storing large data, needed review and quotas. These lessons carried into ZooKeeper and etcd, which emphasise watches and small data. The design pattern underneath, a small, replicated, consensus-backed state machine with sessions and increasing identifiers, is the one every modern lock service follows. See Consensus.

Deep Dive: Locks inside databases you already runShow

PostgreSQL advisory locks. PostgreSQL offers named locks with no table attached, identified by a 64-bit integer or a pair of 32-bit integers, often derived from a hash of the resource name:

  • pg_advisory_lock(key) waits for the lock, pg_try_advisory_lock(key) returns immediately with true or false, and pg_advisory_unlock(key) releases it. These are session-level: held until released or until the connection closes.
  • pg_advisory_xact_lock(key) and pg_try_advisory_xact_lock(key) are transaction-level: released automatically at commit or rollback.

They are excellent for "only one instance runs this migration or this scheduled job", since they need no extra system and are released when the holder's connection dies. Their limits: they live on one database primary, so a failover drops them; session locks break behind transaction-pooling poolers; and the holder must stay connected, so a long hold occupies a connection. They are also a useful fencing source: the job can write its results in the same database, inside a transaction that also checks a version or epoch.

MySQL named locks. GET_LOCK('name', timeout) and RELEASE_LOCK('name') provide session-level named locks in MySQL, released when the session ends. The same caveats apply: one server, lost on failover, tied to a connection.

A lock table with leases. Any database with conditional updates can host lease-based locks in a table:

-- Acquire or take over an expired lock, and bump the fencing token
UPDATE locks
SET    owner = :me, expires_at = now() + interval '30 seconds', token = token + 1
WHERE  name = 'nightly-billing'
  AND  (owner = :me OR expires_at < now())
RETURNING token;
-- No row: someone else holds it. Renew with the same statement before expiry.

The token increases with each takeover and is stored in the same database as the data, so writes can check it in the same transaction. Expiry uses the database's clock, so holders' clocks do not matter, though the holder should still stop early by its own monotonic measure. On a strongly consistent, replicated database, such as PostgreSQL with synchronous replication, Spanner, CockroachDB or DynamoDB with conditional writes, this is a correctness lock without a separate coordination service. AWS's DynamoDB lock client follows this model, with a record version number in place of the counter.

When to prefer these. If the protected data is in the same database, a database lock or lease is almost always better than Redis or ZooKeeper, because the fencing check and the write share a transaction. Reach for a separate coordination service when the protected resources live outside the database, or when many services without a shared database must coordinate.

Deep Dive: Deadlocks across machinesShow

The distributed version of the problem. When locks are spread across many servers, a deadlock cycle can span machines: transaction T1 holds a lock on server 1 and waits for one on server 2, while T2 holds the lock on server 2 and waits for one on server 1. No single server sees the cycle in its local wait-for graph.

Detection. One approach gathers wait-for edges at a central detector, which finds cycles and aborts a victim. It is simple, but the detector sees a slightly stale picture, and may report phantom deadlocks that already resolved. Edge-chasing algorithms avoid a central detector: in the Chandy-Misra-Haas algorithm (K. Mani Chandy, Jayadev Misra and Laura Haas, "Distributed Deadlock Detection", ACM Transactions on Computer Systems, 1983), a blocked process sends a probe along its wait-for edges, each blocked process forwards it, and if the probe returns to its originator, a cycle exists.

Prevention with timestamps. Rosenkrantz, Stearns and Lewis ("System Level Concurrency Control for Distributed Database Systems", ACM TODS, 1978) proposed two schemes that use transaction start timestamps to break cycles before they form:

  • Wait-die: an older transaction may wait for a younger one; a younger transaction that requests a lock held by an older one is aborted ("dies") and restarts later with its original timestamp.
  • Wound-wait: an older transaction that requests a lock held by a younger one aborts ("wounds") it; a younger transaction may wait for an older one.

Since waiting only ever happens in one direction of age, no cycle can form, and because restarted transactions keep their timestamps, each eventually becomes the oldest and completes, so no transaction starves. Google's Spanner paper (Corbett and colleagues, OSDI 2012) reports using wound-wait for read-write transactions.

Timeouts as the pragmatic answer. Most systems built on distributed locks rely on lock acquisition timeouts: a process that cannot acquire within a deadline releases what it holds and retries after a randomised delay. This breaks deadlocks at the cost of occasional unnecessary aborts. Combined with a global lock order and all-or-nothing acquisition, such as the single Lua script above, deadlocks become impossible rather than merely detectable.

Livelock. Timeouts and retries can also cause livelock: two processes repeatedly acquire part of what they need, time out, release and retry in lockstep. Randomised, exponentially growing back-off breaks the symmetry, the same technique used in Ethernet collision handling and in Raft's randomised election timeouts.

Deep Dive: Testing lock codeShow

Why ordinary tests miss lock bugs. The failures that matter, pauses longer than a TTL, failover between a write and its replication, clock steps and delayed packets, never happen in unit tests and rarely in staging. They need to be provoked.

Fault injection.

  • Pause a holder: send SIGSTOP to a process holding a lock, wait past the TTL, then SIGCONT, and check that its subsequent writes are rejected by fencing.
  • Partition the lock service: block traffic between the holder and Redis or etcd with firewall rules, while leaving its path to the resource open.
  • Fail over the lock store in the middle of acquisitions, and count how often two clients believe they hold the lock.
  • Step the clock on a lock server or client, forwards and backwards, and verify that deadlines use monotonic time.

Invariant checking. Record every protected write with the holder and token, and check afterwards that no two holders wrote within overlapping lock periods, or that the resource never accepted a lower token after a higher one. The Jepsen project by Kyle Kingsbury applies exactly this approach to databases and coordination services, recording histories of operations under injected faults and checking them against a consistency model, and has found safety bugs in many systems' locking and leadership logic.

Model checking the protocol. For a custom lock protocol, a small TLA+ specification, with processes, a lock store, expiry and resources, lets the TLC model checker explore every interleaving of a few processes and find the paused-holder scenario automatically. Amazon engineers reported using TLA+ on DynamoDB, S3 and other systems, finding subtle bugs that testing had missed (Chris Newcombe and colleagues, "How Amazon Web Services Uses Formal Methods", Communications of the ACM, 2015).

Metrics in production. Track lock acquisition latency, wait time, hold time, contention rate, expiries while held, renewals failed and fencing rejections. A non-zero rate of fencing rejections is not an error to suppress: it is proof that the lock failed and fencing saved the data.

Key Takeaways#

  • First ask whether the database can enforce the rule with a conditional update, a unique constraint, OCC or a short transaction. If so, no distributed lock is needed.
  • Classify every lock: efficiency locks prevent duplicate work and can be a single Redis key; correctness locks prevent damage and need a consensus store plus a check at the resource.
  • A Redis lock is SET key token NX PX ttl, released and extended by Lua scripts that check the token. It is fast, but asynchronous replication and restarts can lose it.
  • Redlock adds a majority of independent Redis nodes, but its safety depends on bounded pauses, delays and clock error, and it offers no fencing token, so it is not a correctness lock on its own.
  • ZooKeeper, etcd and Consul locks survive server failures, queue waiters fairly and provide increasing numbers usable as fencing tokens, at a cost of a few milliseconds per acquisition.
  • Any lock with a TTL can expire while its holder is paused. Fencing tokens, checked atomically by the resource, are the only reliable defence; where the resource cannot check, use idempotency keys.
  • Often the best lock is none: OCC, conditional writes, reservations with hold_until, a single consumer per key through a queue partition, or commutative updates.
  • Make waiting bounded, acquire multiple locks in a fixed order or all at once, and monitor expiries and fencing rejections.