Distributed lock

On this page 7

A distributed lock is a coordination mechanism that ensures only one process across several machines can hold a given lock and act on a shared resource at a time. In concurrency, it extends the idea of a mutex beyond a single address space: instead of shared memory, the processes agree on ownership through a network-accessible coordination service such as a consensus-based key-value store or a database.

Distributed locks appear wherever several service instances must not perform the same work simultaneously, for example running a scheduled job once, updating a shared file or reserving limited inventory. They are much harder to implement correctly than local locks, because networks delay messages, processes pause and clocks drift.

How a distributed lock works

A client acquires the lock by asking the coordination service to create or claim a record under an agreed name, such as lock:invoice-batch. The service grants the claim only if no other client currently holds it, using an atomic operation such as compare-and-swap or a conditional write.

Because a client can crash while holding the lock, practical implementations attach a lease with a time-to-live (TTL). If the holder does not renew the lease before it expires, the service releases the lock automatically, which prevents permanent blocking after a failure. The holder renews the lease periodically through a heartbeat and deletes the record when it finishes the critical section.

The core properties that a distributed lock must provide are listed below.

PropertyMeaningTypical mechanism
Mutual exclusionAt most one holder at any momentAtomic conditional write
LivenessA crashed holder does not block others foreverLease with TTL
Fault toleranceThe lock survives failure of service nodesReplication with consensus
Safety under delaysA stale holder cannot corrupt the resourceFencing tokens
FairnessWaiting clients are served in a predictable orderSequential queue nodes
Required properties of a distributed lock

Common implementations and their guarantees

Implementations differ mainly in how strongly they guarantee mutual exclusion when nodes fail or the network partitions. Systems built on a consensus algorithm such as Raft or ZAB provide linearizable operations, while single-node caches trade correctness for speed.

ImplementationBasisStrength of guarantee
ZooKeeper ephemeral sequential nodesZAB consensus, session-bound nodesStrong, with ordered waiting
etcd lease with revisionRaft consensus, monotonic revisionsStrong, revision usable as fencing token
Single Redis key with SET NX PXOne in-memory nodeWeak if the node fails or fails over
Redlock across Redis nodesMajority of independent nodes with timingDisputed under clock and pause faults
Relational database row lockTransactions or advisory locksStrong within one database primary
Typical distributed lock implementations

Redlock illustrates the central controversy. It acquires the lock on a majority of independent Redis instances and relies on bounded clock drift and network delay for correctness. Critics argue that a long garbage-collection pause or a clock jump can let two clients believe they hold the lock simultaneously, so the algorithm should not protect correctness-critical operations without additional fencing.

Fencing tokens and the stale holder problem

A lease alone cannot guarantee safety. A client may acquire the lock, then pause for longer than the TTL, for instance during a stop-the-world garbage collection or a virtual machine migration. The lease expires, another client acquires the lock, and the first client resumes and writes to the resource while believing it is still the holder.

The standard remedy is a fencing token: a number that increases every time the lock is granted. The client sends its token with each write, and the protected resource rejects any write carrying a lower token than the highest one it has already seen. This moves the final safety check to the resource itself, which is the only component that can enforce it reliably.

Fencing requires that the storage system supports conditional writes on the token. When it does not, the lock should be treated as an efficiency optimization that prevents duplicate work most of the time, not as a guarantee of correctness.

Distributed locks share goals with local primitives but face different failure modes. The comparison below places them next to their neighbors in concurrency.

MechanismScopeMain failure concern
MutexThreads in one processDeadlock and contention
Read-write lockThreads with many readersWriter starvation
Database transactionOperations within one databaseIsolation anomalies
Distributed lockProcesses on many machinesPartitions, pauses and clock drift
Leader electionOne long-term coordinator in a clusterSplit brain after partitions
Distributed lock compared with related mechanisms

A distributed lock held for a long time is effectively leader election, and many coordination libraries implement both with the same primitives. When the protected data lives in a single database, a transaction or row-level lock in that database is usually simpler and safer than an external lock service.

Practical guidance and common mistakes

The first design question is why the lock is needed. If duplicate execution only wastes resources, a lightweight lock with occasional failures is acceptable. If duplicate execution corrupts data or charges a customer twice, the design needs a consensus-backed store, fencing tokens and preferably idempotent operations.

  • Choosing a TTL that is too short causes leases to expire during normal work; too long a TTL delays recovery after crashes.
  • Releasing a lock without checking ownership can delete another client’s lock; compare a unique owner value before deleting.
  • Ignoring renewal failures lets the holder continue after losing the lock; stop work when renewal fails.
  • Relying on wall-clock time across machines introduces errors from clock skew; prefer monotonic clocks and server-side leases.
  • Holding locks across slow external calls increases contention and the window for stale holders.

The idea in brief

A distributed lock is like a single key to a shared room that many people in different buildings want to use. Instead of passing a physical key, they ask a trusted coordinator who has it, and the coordinator lets only one person in at a time.

The tricky part is that people can fall asleep inside or lose contact. So the key expires after a set time, and a numbered ticket system makes sure that someone who wakes up late cannot cause damage with an old key.

A practical scenario

An online ticketing service runs six instances of its billing service behind a load balancer. Every night at 02:00, a scheduled job must generate invoices exactly once. Without coordination, all six instances start the job, and customers receive duplicate invoices.

The team adds a lock in etcd named billing-nightly with a 30-second lease renewed every 10 seconds. The instance that acquires it runs the job and passes the lease revision as a fencing token to the invoice database, which stores the highest token per batch and rejects older ones. During testing, an engineer freezes the active instance for 45 seconds; another instance takes over, and the frozen one’s late writes are rejected. Duplicate invoices stop entirely, and the job completes even when an instance fails mid-run.