{"canonical_url":"https://engineer.company/glossary/distributed-lock/","content_markdown":"# Distributed lock\n\n## What it is\n\nA distributed lock coordinates access to a named resource among processes that\ncommunicate over a network. Several workers might try to update the same shared\nobject. By acquiring the lock, one worker can gain permission to do the\nprotected work while the others defer. A coordination service records the\ncurrent ownership and provides a way to acquire, release or wait for it.\n\nA lock can be associated with a session or a time-limited lease. Expiry lets\nanother worker move forward if the previous one disappears. Processes and\nnetworks can pause, so expiry creates an important situation. The previous\nholder may still have instructions ready to run when it resumes after another\nworker has acquired the lock. The lock service's view of ownership and the\nresource's ability to accept writes are separate parts of the design.\n\nA fencing token can connect those parts. Each acquisition supplies an ordered\nidentifier. The guarded resource can enforce a rule that rejects work associated\nwith an older acquisition after it has accepted a newer one. The resource has to\ncheck the token as part of the update it protects. Using an ordered number in a\nlog or checking it before a later unguarded write leaves a gap between the\ncoordination decision and the effect.\n\n## Why it matters\n\nConcurrent work can produce the wrong result even if each worker follows a\nreasonable sequence in isolation. Imagine a background job rebuilding a search\nindex. One worker builds replacement A and pauses before publishing it. Its\nlease expires. Another worker builds replacement B and makes it current. If the\nfirst worker resumes and publishes A after B, a newer correct result can be lost\nwhile the lock dashboard shows a healthy sequence of acquisitions.\n\nCoordination also has different value depending on what failure means. For an\nexpensive cache refresh, duplicate work may cost extra time. For a write that\ncan lose accepted user data, allowing a stale holder to continue changes the\nsystem's correctness. Identify the consequence before selecting the mechanism. A\nbounded lease may be useful for avoiding wasted computation. A write with a\nstronger invariant needs to enforce the ownership decision at the place where it\nchanges durable data.\n\nAvailability matters because every protected operation can depend on the\ncoordination service. Define the response when that service cannot be reached. A\nworker could wait, abandon a redundant refresh, or record that a decision is\npending. It needs a deliberate policy for an uncertain acquisition or a lost\nresponse. Limit the time it can wait, and keep the meaning of an accepted update\nclear for the caller.\n\n## What it looks like in practice\n\nIn the index example, use a resource store that can accept a new version based\non an ordered generation. Worker A acquires generation 41 and finishes building\nits replacement. Pause it before it publishes. Let worker B acquire generation\n42, install a replacement and record that generation with the active pointer.\nNow resume A. The publication should fail its ownership condition and leave B's\nresult active. Exercise the same behaviour after restarting the workers and with\na retried request that uses the same operation identity.\n\nA test also needs to check the store that actually changes state. A simulated\nlock service can demonstrate the ownership sequence without proving that a stale\nwriter is rejected on the real path. Observe the result of a write and the\nstored version, then check a reader that uses the published pointer. Preserve\nenough diagnostic information to explain which operation lost its lease, which\none acquired the next generation, and which update the durable store accepted.\n\nEngineer's\n[limited-stock engineering note](/notes/selling-limited-stock-without-overselling/)\ndiscusses a lease holder resuming after its lease has expired and the need for a\nresource to check a token. It also shows how the stock decision can be expressed\nas a condition the data store applies directly. Start by writing down the\ninvariant. If the guarded store can enforce that invariant in the same\ntransaction as the change, use that capability when it fits the operation.\n\n## Where it goes wrong\n\nA common mistake is to treat a lease duration as a bound on how long a process\ncan pause. A process can be suspended for longer than expected, and a request\nalready in flight can reach a resource after ownership changes. Set lease and\nrenewal times to support normal operation. Handle a stale operation at the\nresource as part of correctness. A test should deliberately pause a worker\nbeyond the lease duration and deliver its pending request after the replacement\nis active.\n\nAcquisition and release are also affected by network retries. A client can lose\nthe reply to a successful acquisition and be unsure whether it holds the lock.\nAn unconditional release can interfere with a later owner if the original\nacquisition has expired. Use the coordination system's ownership identity or\ntoken in its release and renewal operations. Confirm the behaviour by\ninterrupting the connection at each stage of a representative operation.\n\nFinally, give a distributed lock a defined resource name and scope. Two workers\nthat protect the same object under different names can each acquire a lock\nsuccessfully. A worker that locks an entire service while processing one\nindependent object can make demand from unrelated callers wait. Follow what each\nresource actually shares, test the invariant under failure, and record a bounded\nrecovery procedure for work that may already have taken effect.\n\n## Further reading\n\n- [The etcd concurrency API](https://etcd.io/docs/v3.6/dev-guide/api_concurrency_reference_v3/).\n  Documents locks, leases and ownership keys.\n- [Google's Chubby lock-service paper](https://research.google/pubs/the-chubby-lock-service-for-loosely-coupled-distributed-systems/).\n  Describes sessions and sequencing for a distributed coordination service.\n- [Apache ZooKeeper lock recipes](https://zookeeper.apache.org/doc/current/recipes.html#sc_recipes_Locks).\n  Explains ordering and notification in a lock implementation.\n\n\u003chttps://engineer.company/glossary/distributed-lock/\u003e\n","date_modified":"2026-11-25T07:18:46Z","description":"Follow a lock lease through expiry and see how fencing can prevent a stale process from changing the protected data.","formats":{"gemtext":"https://engineer.company/glossary/distributed-lock/index.gmi","gopher":"https://engineer.company/glossary/distributed-lock/gophermap","html":"https://engineer.company/glossary/distributed-lock/","json":"https://engineer.company/glossary/distributed-lock/index.json","markdown":"https://engineer.company/glossary/distributed-lock/index.md","pdf":"https://engineer.company/glossary/distributed-lock/index.pdf"},"kind":"page","language":"en","title":"What is a distributed lock?","url":"https://engineer.company/glossary/distributed-lock/","version":1}