Distributed locks in system design

A distributed lock makes sure only one process across many machines does something at a time, such as running a scheduled job or changing one record. Because machines pause and networks drop messages, a distributed lock is really a lease that expires, and a holder can lose it without knowing. When correctness depends on the lock, pair it with fencing tokens that the protected resource checks; when it only saves duplicate work, a simple Redis lock with a timeout is usually enough.

By Published 7 min read

1. What a distributed lock is

On one machine, a mutex works because all threads share memory and the operating system arbitrates. Across machines there is no shared memory, so processes ask a separate service for permission: a database, Redis, or a coordination store like ZooKeeper or etcd. That service can be slow or partitioned, and the process holding the lock can freeze for seconds during garbage collection or a VM migration. Every design choice follows from those two facts.

A useful distinction, popularized by Martin Kleppmann: an efficiency lock prevents wasted work, and if it occasionally fails, two workers send the same report and nothing breaks. A correctness lock protects an invariant, and if it fails, money is spent twice or a file is corrupted. Name which one you need before choosing an implementation.

2. Why interviewers ask about it

Locks appear in job schedulers, booking systems, payment flows and leader election. Interviewers want to hear whether you know that a lock can expire under you, what happens then, and whether the problem needs a lock at all. "I'll use a Redis lock" with no expiry, owner check or fencing plan is a common weak answer.

3. Ways to implement one

Common lock backends and what they give you
BackendHow the lock worksStrengthWatch for
Relational databaseRow lock (SELECT ... FOR UPDATE), advisory lock, or inserting a unique rowYou often already have one; works inside a transactionLock held only while the connection or transaction lives; adds load to the primary
Redis (single node)SET key token NX PX ttl; delete only if the token still matchesFast and simpleFailover to a replica that missed the write can grant the lock twice; fine for efficiency locks
Consensus store (ZooKeeper, etcd)Ephemeral nodes or leases tied to a session; ordered keys for fair queuesLinearizable; built-in watches; session ends when the client diesAnother cluster to run; a lost session still means a paused client can act late
Conditional write (compare-and-set)Write only if a version or owner field still has the expected valueNo separate lock service; atomic in the databaseNeeds a database that supports conditional updates on the item
Common lock backends and what they give you. Scroll sideways on a small screen.

4. Leases, pauses and fencing tokens

A lock with no expiry is held forever if its holder crashes, so every distributed lock is a lease: valid until a deadline unless renewed. That creates the classic failure. Worker 1 gets the lease, then freezes for longer than the lease time. The lease expires, worker 2 gets it and writes. Worker 1 wakes, still believes it holds the lock, and writes too. Checking "do I still hold it?" right before writing does not help, because the pause can happen between the check and the write.

The fix is a fencing token: every time the lock is granted, the lock service hands out a number larger than any before. The worker sends the token with each write, and the storage rejects any write whose token is lower than one it has already seen. The resource itself enforces safety, so a late writer cannot do damage.

import itertools

class LockService:
    """Stand-in for a consensus-backed lock with leases."""
    def __init__(self):
        self.holder, self.expires = None, 0.0
        self.tokens = itertools.count(1)       # tokens only ever increase

    def acquire(self, client: str, ttl: float, now: float):
        if self.holder is None or now >= self.expires:
            self.holder, self.expires = client, now + ttl
            return next(self.tokens)
        return None

class Storage:
    """The protected resource refuses writes with an older token."""
    def __init__(self):
        self.highest_token, self.value = 0, None

    def write(self, token: int, value: str) -> bool:
        if token < self.highest_token:
            return False
        self.highest_token, self.value = token, value
        return True

locks, db = LockService(), Storage()
t1 = locks.acquire("worker-1", ttl=10, now=0)    # token 1
# worker-1 pauses past its lease ...
t2 = locks.acquire("worker-2", ttl=10, now=12)   # token 2
print(db.write(t2, "from worker-2"))             # True
print(db.write(t1, "from worker-1"))             # False: fenced off
Leases with fencing tokens (run with python3; outputs in comments)

Fencing needs the resource's cooperation. A database can store the highest token in the row and use a conditional update; an object store may support a version precondition. If the resource cannot check tokens, treat the lock as an efficiency lock and make the operation itself idempotent.

5. The Redis lock, done carefully

ACQUIRE   SET lock:report-42 <random-token> NX PX 30000
          (NX = only if absent, PX = expire after 30,000 ms)

RELEASE   run atomically as a Lua script:
          if redis.call("get", KEYS[1]) == ARGV[1] then
              return redis.call("del", KEYS[1])
          else
              return 0
          end
Single-node Redis pattern: acquire with a random token and expiry, release only your own lock
  • Random token per holder. Without it, a slow worker can delete the lock a newer worker now holds.
  • Expiry longer than the work, or renewal. Renew the lease from a background heartbeat while work continues, and stop working if renewal fails.
  • Replication caveat. Redis replication is asynchronous, so after a failover the new primary may not know about a lock that was just granted.
  • Redlock. The Redis documentation describes Redlock, which takes the lock on a majority of independent Redis nodes. Martin Kleppmann argued it relies on timing assumptions that make it unsafe for correctness, and the Redis author published a rebuttal. In an interview, the safe position is: Redis locks for efficiency; consensus plus fencing tokens for correctness.

6. Designs that avoid the lock

Often simpler and safer than locking
TechniqueHow it replaces a lockExample
Conditional write / optimistic concurrencyRead a version, write only if it is unchanged, retry on conflictUpdating an inventory count with a version column
Unique constraintLet the database reject the second insertOne booking per seat per show
Idempotency keyRepeat requests return the first result instead of acting twiceA payment retried after a timeout
Single owner per partitionRoute all work for a key to one consumer, so no two workers share itKafka partitions keyed by account; see message queues vs pub/sub
Leader electionOne elected instance does the singleton job; others stand byA cron-like scheduler with a standby
Often simpler and safer than locking. Scroll sideways on a small screen.

7. How it shows up in common prompts

Where locking questions come up
PromptWhat needs exclusivityGood answer
Job schedulerEach job runs once per scheduleWorkers claim jobs with a lease and fencing token, or a conditional update on the job row
Ticket bookingA seat held by one buyerA short hold via conditional write with expiry; unique constraint at purchase
Payment systemNo double chargeIdempotency keys and transactional ledger writes rather than a lock service
Web crawlerOne fetcher per host for politenessPartition hosts to workers; no lock per request
Rate limiterCounters updated by many serversAtomic increments in the store, not a lock around read-then-write
Where locking questions come up. Scroll sideways on a small screen.

8. Mistakes to avoid

  • No expiry. One crashed holder blocks everyone forever.
  • Deleting without checking the owner. You release someone else's lock.
  • Trusting the lease for correctness. A pause longer than the lease breaks it; use fencing.
  • Locking where a constraint or conditional write would do. Extra moving parts, same result.
  • Holding locks across network calls to other services. Lock time balloons and failures leave work half done.

9. How to talk about it in the interview

  • Say whether the lock is for efficiency or correctness.
  • Name the backend and the lease time, and how renewal works.
  • Describe the paused-holder case and your fencing answer.
  • Offer the lock-free alternative if one exists.

Fictional example

One nightly invoice run across a fleet
Interviewer
Ten app servers each have a nightly cron that generates invoices. How do you make sure it runs once?
Candidate
Running twice would bill customers twice, so this is a correctness problem. I'd avoid relying on a lock alone: each invoice row has a unique key of customer plus billing period, so a duplicate insert fails.
Interviewer
Would you still use a lock?
Candidate
As an efficiency lock, yes, so nine servers don't waste work. A lease in etcd with a 60-second TTL, renewed while the job runs. Each write carries the fencing token, and the job table stores the highest token, so a server that wakes up late after a long pause gets rejected.
Interviewer
What if the holder crashes halfway?
Candidate
The lease expires, another server takes over and skips invoices that already exist, thanks to the unique key.

Practicing with Natively

The paused-holder question is where lock answers usually break, and it is easy to rehearse. Run a mock interview with Natively open and it transcribes the exchange and can propose talking points for each follow-up, so afterwards you can check whether you raised expiry, fencing and the lock-free alternative. It can also explain a screenshot of a sequence diagram or prompt you capture. The transcript is kept for review.

Questions people ask

What is a distributed lock?

A way to make sure only one process across many machines does something at a time, such as running a job or updating a record. It is granted by a shared service like a database, Redis or a consensus store, and in practice it is a lease that expires.

What is a fencing token?

A number that increases every time the lock is granted. The holder sends it with each write, and the protected resource rejects any write with a lower token than one it has already seen, so a holder that paused past its lease cannot overwrite newer work.

Is a Redis lock safe?

A single-node Redis lock with SET NX and an expiry, released only by its owner, is fine for avoiding duplicate work. For correctness-critical locking, asynchronous replication and timing assumptions make it risky; use a consensus store with fencing tokens.

How can you avoid using a distributed lock?

Use a unique constraint, a conditional write with a version number, idempotency keys, or route all work for a key to a single consumer by partitioning. These are often simpler and safer than a separate lock service.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP