# Distributed lock

## What it is

A distributed lock coordinates access to a named resource among processes that
communicate over a network. Several workers might try to update the same shared
object. By acquiring the lock, one worker can gain permission to do the
protected work while the others defer. A coordination service records the
current ownership and provides a way to acquire, release or wait for it.

A lock can be associated with a session or a time-limited lease. Expiry lets
another worker move forward if the previous one disappears. Processes and
networks can pause, so expiry creates an important situation. The previous
holder may still have instructions ready to run when it resumes after another
worker has acquired the lock. The lock service's view of ownership and the
resource's ability to accept writes are separate parts of the design.

A fencing token can connect those parts. Each acquisition supplies an ordered
identifier. The guarded resource can enforce a rule that rejects work associated
with an older acquisition after it has accepted a newer one. The resource has to
check the token as part of the update it protects. Using an ordered number in a
log or checking it before a later unguarded write leaves a gap between the
coordination decision and the effect.

## Why it matters

Concurrent work can produce the wrong result even if each worker follows a
reasonable sequence in isolation. Imagine a background job rebuilding a search
index. One worker builds replacement A and pauses before publishing it. Its
lease expires. Another worker builds replacement B and makes it current. If the
first worker resumes and publishes A after B, a newer correct result can be lost
while the lock dashboard shows a healthy sequence of acquisitions.

Coordination also has different value depending on what failure means. For an
expensive cache refresh, duplicate work may cost extra time. For a write that
can lose accepted user data, allowing a stale holder to continue changes the
system's correctness. Identify the consequence before selecting the mechanism. A
bounded lease may be useful for avoiding wasted computation. A write with a
stronger invariant needs to enforce the ownership decision at the place where it
changes durable data.

Availability matters because every protected operation can depend on the
coordination service. Define the response when that service cannot be reached. A
worker could wait, abandon a redundant refresh, or record that a decision is
pending. It needs a deliberate policy for an uncertain acquisition or a lost
response. Limit the time it can wait, and keep the meaning of an accepted update
clear for the caller.

## What it looks like in practice

In the index example, use a resource store that can accept a new version based
on an ordered generation. Worker A acquires generation 41 and finishes building
its replacement. Pause it before it publishes. Let worker B acquire generation
42, install a replacement and record that generation with the active pointer.
Now resume A. The publication should fail its ownership condition and leave B's
result active. Exercise the same behaviour after restarting the workers and with
a retried request that uses the same operation identity.

A test also needs to check the store that actually changes state. A simulated
lock service can demonstrate the ownership sequence without proving that a stale
writer is rejected on the real path. Observe the result of a write and the
stored version, then check a reader that uses the published pointer. Preserve
enough diagnostic information to explain which operation lost its lease, which
one acquired the next generation, and which update the durable store accepted.

Engineer's
[limited-stock engineering note](/notes/selling-limited-stock-without-overselling/)
discusses a lease holder resuming after its lease has expired and the need for a
resource to check a token. It also shows how the stock decision can be expressed
as a condition the data store applies directly. Start by writing down the
invariant. If the guarded store can enforce that invariant in the same
transaction as the change, use that capability when it fits the operation.

## Where it goes wrong

A common mistake is to treat a lease duration as a bound on how long a process
can pause. A process can be suspended for longer than expected, and a request
already in flight can reach a resource after ownership changes. Set lease and
renewal times to support normal operation. Handle a stale operation at the
resource as part of correctness. A test should deliberately pause a worker
beyond the lease duration and deliver its pending request after the replacement
is active.

Acquisition and release are also affected by network retries. A client can lose
the reply to a successful acquisition and be unsure whether it holds the lock.
An unconditional release can interfere with a later owner if the original
acquisition has expired. Use the coordination system's ownership identity or
token in its release and renewal operations. Confirm the behaviour by
interrupting the connection at each stage of a representative operation.

Finally, give a distributed lock a defined resource name and scope. Two workers
that protect the same object under different names can each acquire a lock
successfully. A worker that locks an entire service while processing one
independent object can make demand from unrelated callers wait. Follow what each
resource actually shares, test the invariant under failure, and record a bounded
recovery procedure for work that may already have taken effect.

## Further reading

- [The etcd concurrency API](https://etcd.io/docs/v3.6/dev-guide/api_concurrency_reference_v3/).
  Documents locks, leases and ownership keys.
- [Google's Chubby lock-service paper](https://research.google/pubs/the-chubby-lock-service-for-loosely-coupled-distributed-systems/).
  Describes sessions and sequencing for a distributed coordination service.
- [Apache ZooKeeper lock recipes](https://zookeeper.apache.org/doc/current/recipes.html#sc_recipes_Locks).
  Explains ordering and notification in a lock implementation.

<https://engineer.company/glossary/distributed-lock/>
