Stage 3 · Distributed data · Hard · 20 min

Distributed locks and fencing tokens

Let only one worker do a job at a time across machines — and stay safe when the lock holder pauses — using leases and fencing tokens.

What each interview level is expected to know

Learn first: Time, clocks and ordering, Consensus and Raft

After this lesson you can:

  • Take a lock with an expiry so a crashed worker cannot hold it for ever.
  • Explain how a long pause lets two workers think they hold the same lock.
  • Use fencing tokens so storage rejects the late writer.

Start here

See it in 60 seconds

When a lock runs out too soon

A lock can run out while its holder is frozen, so storage checks a fencing token that only goes up.

Scene 1 of 6 · Take the lock

Say client A takes the lock for 10 s and gets fencing token 33, a number that only goes up.

Lock serviceLock serviceA holds it, 10 sClient AClient Atoken 33Client BClient BStorageStorage
  • Lock service — healthy — A holds it, 10 s
  • Client A — healthy — token 33
  • Client B — healthy
  • Storage — healthy
  1. Take the lock. Say client A takes the lock for 10 s and gets fencing token 33, a number that only goes up.
  2. A freezes. Then A freezes, say its program pauses for 15 s, and it does not notice the time passing.
  3. The lock runs out. After 10 s the lock runs out, so the lock service treats A as gone.
  4. B gets token 34. Client B takes the lock, gets token 34, and writes; storage notes 34 as the highest token so far.
  5. A wakes up late. A wakes up, still believes it holds the lock, and sends a write with token 33.
  6. Storage says no. Storage has already seen 34, so it refuses 33, and the late write does no harm.
  7. Now you try. Tap writes in the order they reach storage, and see which ones it accepts. For example, tapping A writes, token 33, B writes, token 34 and A writes, token 33 gives this: A accepted, B accepted and A refused; storage's highest token is now 34. Once storage has seen token 34, it refuses 33, so a client whose lock ran out cannot write.

Scene 1 of 6: Take the lock. Say client A takes the lock for 10 s and gets fencing token 33, a number that only goes up.

Key points

  1. A lock lasts a set time, so a frozen client can lose it without noticing.
  2. Each time the lock is given out, it comes with a fencing token one higher than before.
  3. Storage remembers the highest token it has seen and refuses any lower one.
  4. So a client whose lock ran out cannot overwrite the work of the next holder.

Go deeper in the Distributed locks & fencing tokens lab →

In plain words

Say two workers, client A and client B, both want to change the same record. A asks a lock service for the lock and gets it for 10 seconds. With the lock comes a number, 33. Then A's program freezes for 15 seconds. The lock runs out, so B takes it, gets the number 34 and writes. When A wakes up it knows none of this, and it sends its write with 33. The storage took a write with 34 a moment ago, so it turns 33 away. A lock with a time limit is called a lease. The rising number is called a fencing token.

In practice the lock service is a small group of servers that agree by majority, such as etcd or ZooKeeper, so it survives one crash. A lock kept on a single server can be lost when that server fails and a copy takes over. The worker should renew its lease while it works, well before the time runs out. And the storage must check the token itself, because only it sees every write in order.

The problem it solves

A lock across machines needs a time limit, or a crashed holder would keep it forever. But a holder can be slow without having crashed. Its program may pause to free memory, called a garbage collection pause, or its network may stall. The lock then runs out while the holder is still working. A second worker takes it, and both write to the same data.

Why it matters

Many systems run the same job on several machines, for speed or as a spare. Some work must still be done by one worker at a time: charging a card, booking seat 14C, sending the monthly bill. A lock shared across machines is the usual answer. It fails in ways that a lock inside one program does not.

A worked example

A worker takes a lock with a 10-second lease and fencing token 33. A 15-second pause then makes the lease expire 5 seconds before the worker finishes, since 15 − 10 = 5. A second worker takes over with token 34 and writes first. When the first worker finally to write using token 33, the storage rejects it because 33 is less than 34.

Think of it like…

Think of a meeting room booked for 30 minutes at a time. Each booking gets a slip with a rising number: 33, then 34. The door remembers the highest number it has seen, and stays shut for a lower one.

Where this analogy stops working

A time limit plus a rising number is the useful part. But in a building, the desk and the door are one system. In software they are apart. The lock service hands out the number, and the storage must check it on every write. A store that cannot check it gets no protection.

Try it

See it working

Guided walkthroughOpen the full lab →

Distributed locks & fencing tokens

A worker freezes while it holds a lock, and the lock runs out. See when two workers both write, and how storage that checks a fencing token turns the late write away.

Step through one lock

Two workers want to change one report, and a lock lets one in at a time. Pick how long Worker 1 freezes while it holds the lock, then press Next step. Back takes you to the step before.

Worker 1 freezes while holding the lock

Longer than the 8 s lease.

On: the storage refuses a write whose token is lower than one it has already seen.

With these settings: Lost update. Worker 1 wrote after its lease ran out, and the storage could not tell. Worker 2's change was overwritten with no error.

Lock service, lease: 8 s, NOWLock servicelease: 8 sNOWWorker 1Worker 1waiting for the lockWorker 2Worker 2Storage, the shared reportStoragethe shared report
  • Lock service — lease: 8 s — healthy — NOW
  • Worker 1 — healthy — waiting for the lock
  • Worker 2 — healthy
  • Storage — the shared report — healthy
  • Ask or release
  • Lock granted, with a token
  • Write
Step 1 of 9

Step 1 of 9 · Lock service

Done: Worker 1 asks for the lock

What happens
Worker 1 wants to change the shared report. It asks the lock service for the lock first.
Why
Two workers changing one report at the same time can lose a change. A lock lets one in at a time.
What changes
Nobody holds the lock, so the lock service can grant it.
Next
The lock service grants the lock with token 1

Event log

8 more to go. Press a line to go back to that step.

Clock
0s
Lock held by
nobody
free
Think they hold it
0workers
Highest token seen
–
the storage does not check
The report holds
no change yet

Step 1 of 9: Lock service. Worker 1 asks for the lock. Worker 1 wants to change the shared report. It asks the lock service for the lock first.

What this simplifies. This is two workers and one lock, and the pause is a setting, not chance. A real worker can also be late for other reasons: a slow network, or a clock that runs fast or slow. A fencing token only helps when the storage can compare tokens on every write, and many storage systems cannot. Here the lock service is one process that never fails. A real one is itself several servers that have to agree on who holds the lock.

Try it yourself

Press the buttons in any order. Worker 1 can freeze while it holds the lock, as a program does during a long garbage-collection pause.

Lock
Free
Any worker can take it
Token check at the store
On
Highest token seen: 0
The shared report holds
“The first version of the report”
Last written by: System

Two workers, one lock service and one shared store

Worker 1Waiting
Token it holds: none
Lock service
Lends the lock to one worker at a time, with a token number that only goes up
Held by:nobody
Lease left:0s
Next token:1
Worker 2Waiting
Token it holds: none

The store checks tokens

When this is on, the store refuses a write whose token is lower than the highest token it has seen.

Log of what happened

[5:35:57 AM]Nobody holds the lock yet, and the store checks tokens.

Also try: Raft leader election

Mechanics

How it works

The pictures follow this page's example: client A takes a lock, freezes for 15 seconds, and wakes after its lease has run out. The first shows what a fencing token stops. The second shows why a release must check whose lock it is.

  1. Take the lock with an expiry

    A worker asks the lock service for the lock on one resource, such as seat:14C. The service grants it for a fixed time, such as 10 seconds. This timed lock is called a lease. The expiry matters: if the worker crashes, the lock frees itself.

  2. Get a fencing token

    With each lease, the lock service also hands out a number that only goes up: 33, then 34. This number is a fencing token. Services built on consensus, such as ZooKeeper or etcd, can provide one. A plain Redis lock does not, so you must add a counter yourself.

  3. The storage checks the token

    Pick a case to follow below

    With this case: Storage took A's late write with token 33, and B's change was lost. The lock alone did not stop it.

    Client A, a workerClient Aa workerClient B, a workerClient Ba workerLock service, leases of 10 s, NOWLock serviceleases of 10 sheld by ANOWStorage, the recordStoragethe record
    • Client A — a worker — healthy
    • Client B — a worker — healthy
    • Lock service — leases of 10 s — healthy — NOW — held by A
    • Storage — the record — healthy
    • Granted
    • Write
    Step 1 of 5

    Step 1 of 5 · Lock service

    Done: A takes the lock for 10 seconds

    What happens
    The lock service grants A a lease of 10 seconds, with fencing token 33.
    Why
    The lease frees the lock by itself if A crashes.
    What changes
    A starts its work.
    Next
    A freezes for 15 seconds
    Lock held by
    A
    Highest token at storage
    –
    storage ignores it
    The record holds
    the first version
    as it should be

    Step 1 of 5: Lock service. A takes the lock for 10 seconds. The lock service grants A a lease of 10 seconds, with fencing token 33.

    Every write carries its token. The storage, such as a database, refuses any write whose token is lower than the highest token it has already accepted. So a worker that paused and woke up late with token 33 is rejected once token 34 has written. The storage must do this check itself, because the lock service never sees the write.

    In the picture, step through both cases. A's lease of 10 seconds runs out while A is frozen, B takes the lock with token 34 and writes. When A wakes, it writes with token 33.

    If storage ignores the tokens, A's late write replaces B's change, and nobody sees an error. If storage checks them, 33 is lower than 34, so the write is refused and B's change stays.

  4. Release only your own lock

    Pick a case to follow below

    With this case: A deleted B's lock. Another client could now take it while B is still working.

    Client A, a workerClient Aa workerClient B, a workerClient Ba workerLock service, leases of 10 s, NOWLock serviceleases of 10 sheld by ANOWStorage, the recordStoragethe record
    • Client A — a worker — healthy
    • Client B — a worker — healthy
    • Lock service — leases of 10 s — healthy — NOW — held by A
    • Storage — the record — healthy
    • Granted
    • Request
    Step 1 of 4

    Step 1 of 4 · Lock service

    Done: A takes the lock for 10 seconds

    What happens
    The lock service grants A a lease of 10 seconds, and stores A's id, a-7f, with the lock.
    Why
    The lease frees the lock by itself if A crashes.
    What changes
    A starts its work.
    Next
    A freezes for 15 seconds
    Lock held by
    A
    as it should be
    Id stored with the lock
    a-7f

    Step 1 of 4: Lock service. A takes the lock for 10 seconds. The lock service grants A a lease of 10 seconds, and stores A's id, a-7f, with the lock.

    What these pictures simplify. These pictures use two clients, one record and stated times: a 10-second lease and a 15-second freeze. A real client can also be late because of a slow network or a wrong clock. The distributed lock lab above lets you freeze a worker yourself.

    When the work is done, the worker releases the lock. It must first check that the lock is still its own, by comparing a unique id stored with the lock. Check and delete must happen as one step. Otherwise a slow worker could delete a lock that now belongs to someone else.

    In the picture, A wakes after its lease ran out and releases the lock, which now belongs to B. A plain delete removes B's lock, so a third client could take it while B is still working. Checking the stored id first, in the same step as the delete, leaves B's lock alone.

In code: checking a fencing token

// The lock service gives each new holder a bigger number: 33, then 34, and so on.function makeStore(db) {  let highestSeen = 0  return function write(token, record) {    if (token < highestSeen) return "rejected" // an older holder woke up late    highestSeen = token    db.save(record)    return "saved"  }}
  • The check runs in the storage, not in the client, so a paused client cannot skip it.
  • Holder 33 pauses and its lock runs out. Holder 34 writes. When 33 wakes up and writes, the store refuses it.
  • The check and the save must happen as one step, such as in one .

Use it when

  • One resource that many workers may change, such as seat 14C or one hotel room: the lock lets one booking go through at a time.
  • A job that must not run twice at once, such as the monthly billing run: only the worker holding the lock runs it.
  • Choosing one active copy among several copies of a service: the copy holding the lease acts, and another takes over when the lease ends.

Skip it when

  • An update to one row in one database: a version check on the row, called optimistic locking, is faster and needs no lock service.
  • A rule the database can enforce itself, such as one booking per seat: a unique constraint rejects the second insert with no lock at all.
  • Work that is safe to repeat, such as setting a status to "sent": make the operation and let two workers both do it.

Check yourself

Why does a distributed lock need a lease, a time limit?

Judgement

Trade-offs and how it fails

What you give up

Safety
A lease on its own only makes two holders unlikely. After a pause, two workers can both believe they hold the lock. The fencing token check in the storage is what stops the late write.
Latency
Taking and releasing the lock are extra network calls on every job. If many workers want the same lock, they wait in line, and the lock becomes the slowest part of the system.
Lease length
A short lease frees the lock soon after a crash, but it can run out under a holder that is only slow. A long lease runs out less often, and makes everyone wait longer after a crash.

Failure modes

  • A pause outlasts the lease: A holds a 10-second lease and its program pauses for 15 seconds. B takes the lock and writes. With no fencing token, A's late write then overwrites B's.
  • Releasing someone else's lock: A's lease runs out and B takes the lock. A then finishes and deletes the lock key without checking whose it is, so B's lock is gone.
  • The lock service loses the lock: a single Redis server fails, and its takes over before it has copied the lock key. A second worker can then take a lock that is still held.

In the real world

  • Google's Chubby paper (2006) describes a lock service built on consensus. It hands out a number that lets servers reject a stale lock holder. Source: Google: the Chubby paper (2006) (checked 14 October 2026)
  • ZooKeeper removes a client's lock node when that client's session ends, and etcd offers leases that expire. Many lock libraries build on these.
  • Martin Kleppmann's article "How to do distributed locking" (2016) shows a lock failing after a pause, and how a fencing token prevents the damage. It argues that Redlock, a Redis lock algorithm, is not safe when correctness depends on the lock. Source: Martin Kleppmann, "How to do distributed locking" (2016) (checked 14 October 2026)
  • Redis's documentation says its replication is asynchronous, so a lock key can be lost when a replica takes over. It says such a lock is still fine where a rare race is acceptable.

Trade-offs to be ready to discuss: Optimistic vs pessimistic locking

Check yourself

When can you avoid a distributed lock altogether?

Interview

What interviewers look for

  • Say what the lease cannot do: "A lease can run out while its holder is paused. So I add a fencing token, and the storage refuses any older token."
  • For a Redis lock, say how you release it: "Each holder stores a random id with the lock. A short Lua script checks the id and deletes the key in one step."
  • Ask first whether a lock is needed: "For one row I would use a version check. For one booking per seat I would use a unique constraint."
  • Say what the lock is for. If it only saves repeated work, a rare double run is fine and one Redis lock is enough. If it keeps data correct, use a consensus-based service and fencing tokens.

Say it out loud: What is a fencing token, and why does a lock with a lease need one?

Worker A holds a lock with a 10-second lease and fencing token 33. It pauses for 15 seconds. Worker B takes the lock with token 34 and writes. Then A wakes up and writes. What should happen?

Expected depth by interview level

Levels describe the depth interviewers probe, not years of experience. Choose a level on the learning path to highlight it.

JuniorBeyond this level
Not usually expected.
MidUseful
Why a lock across machines is harder than a mutex.
SeniorCore
Leases, fencing tokens, and what goes wrong when a holder pauses.
StaffExpected
Designing so a lock is not needed at all.

Practice

Apply it

Three harder questions

The first two use the idea on a new case. The last asks you to judge a design.

Apply it

Jobs usually take 2 seconds, but up to 20 when the database is slow. The lock lease is 5 seconds. What happens on a slow job?

Apply it

Worker A's lease ran out, and worker B now holds the lock. A finishes and deletes the lock key without checking whose it is. What happens?

Judge a design

To stop two users booking seat 14C, a team wraps "read the seat; if free, write the owner" in a Redis lock. What is the better design?

Next: timeouts and backoff, how a caller should wait and retry when another service is slow or down.

Go deeper

Sources and further reading

First-hand sources to check this page against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.