Scrivio Interview library
ConceptPrincipal7 min read · updated 12 November 2026

In distributed systems, locks become leases with timeouts and fencing tokens. Which principles from in-JVM locking carry over, which do not, and what long-term stance on distributed locking would you take for your organisation?

From in-JVM locking, three habits carry over well: always bound the wait with a timeout, acquire several locks in one consistent order, and keep the critical section short. What does not carry over is the guarantee that the holder really holds the lock: a distributed holder can be paused or cut off and keep acting after its lease expired, so the protected resource must reject stale holders with fencing tokens. My long-term stance is to design so that distributed locks are rarely needed, using database constraints, optimistic concurrency or single-writer partitions, and where one is needed, to use a proven consensus-backed system and document how it fails.

Background to this question

Senior engineers are asked this because distributed locking is where many teams quietly lose data. The code looks familiar, acquire, work, release, so people assume it behaves like synchronized. It does not, and the differences only appear during pauses, partitions and failovers, which are rare enough to escape testing. In this answer, we will recall what an in-JVM lock actually guarantees, sort the habits into those that carry over and those that break, look at fencing tokens in detail, and then set out an organisation-level stance with the reasoning behind it.

1What an In-JVM Lock Really Guarantees

Inside one JVM, a lock such as synchronized or ReentrantLock lives in memory shared by all the threads that use it. Its guarantees are strong because of a simple fact: the holder and the waiters fail together. If the process dies, every thread dies with it, so nobody is left believing it holds a lock that someone else also holds. If the holder is paused by garbage collection, the waiters are paused too, or at least they keep waiting, because the lock is not released until the holder calls unlock.

The lock also gives memory visibility: whatever the holder wrote before unlocking is visible to the next thread that locks. So mutual exclusion and visibility come together, for free, as long as everyone uses the same lock object.

2The Habits That Carry Over

Three in-JVM habits are just as valuable in a distributed system. The first is bounding the wait. We already prefer tryLock with a timeout over an unbounded lock() on hot paths, and a distributed acquire must always have a timeout too, because the lock service may be slow or unreachable. The second is consistent ordering. Two processes that need locks on account 7 and account 9 will deadlock if one takes 7 then 9 and the other 9 then 7, exactly as two threads would; sorting the keys before acquiring removes that risk in both worlds.

The third is keeping the critical section short. In the JVM a long critical section limits throughput. In a distributed lock it also raises the chance that the work outlives the lease, which is the failure we will look at next. So the reason for brevity becomes stronger, not weaker.

In-JVM lock habits in a distributed system
Habit or guaranteeIn one JVMDistributed
Timeout on acquireGood practiceEssential
Consistent lock orderingPrevents deadlockPrevents deadlock
Short critical sectionThroughputThroughput and lease safety
Holder is the only writerGuaranteedNot guaranteed: lease can expire
Release on holder deathProcess dies with itOnly when the lease expires
Visibility of writesHappens-beforeMust come from the resource itself

3What Breaks: The Holder Who Does Not Know

A distributed lock is held in another service, such as ZooKeeper, etcd or Redis, and the holder is a separate process that can fail independently. The service cannot wait forever for a crashed holder, so every distributed lock is a lease: it expires after, say, 30 seconds unless renewed. That is a necessity, and it creates the central problem.

Suppose the holder starts a write, then pauses for 40 seconds because of a long garbage collection, a stalled disk or a VM being migrated. The lease expires, the lock service grants the lock to someone else, and the second holder starts writing. Then the first process resumes. From its own point of view no time has passed and it still holds the lock, so it finishes its write. Now two writers have acted under the same lock. No amount of care in the client code can prevent this, because the client cannot notice its own pause before the next instruction runs. A network partition causes the same effect: the holder is cut off from the lock service, which expires its lease, but it can still reach the database.

4Fencing Tokens: Let the Resource Say No

The way out is to stop relying on the holder's belief and let the protected resource decide. Each time the lock service grants the lock, it hands out a number that only ever increases, called a fencing token. ZooKeeper's zxid or a node's version can serve as one, and etcd's revision numbers likewise. The holder attaches the token to every write, and the resource remembers the highest token it has accepted and rejects anything lower.

SQL
-- the resource stores the highest token seen for this key
UPDATE stock SET qty = :qty, fence = :token
WHERE sku = :sku AND fence < :token; -- holder with token 34: 1 row updated
-- late holder with token 33: 0 rows, write refused

Notice two consequences. The resource must take part, which rules out resources that cannot compare a token, such as many external APIs or plain files. And once the resource compares a number on every write, it is doing optimistic concurrency control. That observation leads directly to the stance below: if the resource must check anyway, we can often drop the lock and keep only the check.

5A Long-Term Stance for the Organisation

My default would be: avoid distributed locks for correctness, and design so they are rarely needed. For data in one database, constraints and conditional updates are atomic, durable and already shared by every instance. A unique index prevents duplicates; a version column prevents lost updates; a single conditional UPDATE enforces 'stock never below zero'. For workflows that must process one key at a time, a single-writer design, such as routing all events for a key to one Kafka partition consumed by one consumer, gives ordering without a lock.

Where a distributed lock is still the right tool, for example to elect one instance to run a nightly job or to coordinate access to a resource with no transactions, I would require three things. First, a proven system built on consensus, such as ZooKeeper or etcd, or a well-reviewed library over the database, rather than a home-grown Redis script. Second, a classification: is this lock for efficiency, where an occasional double run is harmless, or for correctness, where it is not? Efficiency locks can use simpler tools; correctness locks need fencing or must be redesigned. Third, written failure behaviour: what happens if the holder pauses past its lease, if the lock service is unreachable, and how we would detect a double holder. That document is what reviewers and on-call engineers need, and writing it often reveals that the lock was not needed.

Step throughChoosing how to coordinate writers
  1. Is the data in one database?
    YesUse a constraint or conditional updateNoNext question
  2. Can one owner per key do the work?
    YesSingle-writer partition, for example by Kafka keyNoNext question
  3. Is the lock only for efficiency?
    YesSimple lease lock, double runs harmlessNoNext question
  4. Correctness lockconsensus-backed system, fencing tokens, documented failure behaviour

4 steps in order. Play them, or step through them one at a time.

6Follow-up questions

Is a Redis lock ever acceptable?

Yes, for efficiency: to stop ten instances from rebuilding the same cache at once, an occasional double rebuild is harmless, and a SET NX with a lease is simple and fast. For correctness I would not rely on it alone, because a single Redis node can fail over and lose the key, and it offers no fencing token by default.

Does a lease renewal thread solve the pause problem?

No. A renewal thread shortens the window in normal operation, but during a stop-the-world pause the renewal thread is paused too, and during a partition it cannot reach the lock service. The holder still cannot know that its lease lapsed before its next write.

What do you mean by documenting failure behaviour?

A short note next to each lock: what it protects, whether it is for efficiency or correctness, its lease length and how that compares to the longest expected operation, what the resource does with a stale token, and how we would notice two holders, for example a metric or an audit query.

7Conclusion

In this answer, we compared in-JVM locks with distributed ones. Timeouts on acquisition, consistent ordering and short critical sections carry over and matter even more. The guarantee that only the holder acts does not, because a distributed holder can be paused or partitioned past its lease and still believe it holds the lock, so the resource must reject stale writers using fencing tokens. Since the resource must check anyway, the stance I would set is to prefer constraints, optimistic concurrency and single-writer partitions, and to allow distributed locks only through proven systems with documented failure behaviour.

What to say in the interviewAbout 90 seconds aloud

Open with

I'd split it into what carries over and what doesn't. The habits carry over: always put a timeout on acquiring, acquire multiple locks in a consistent order so two processes can't deadlock, and keep the critical section short, which in a distributed lock also reduces the chance of outliving the lease.

Then, if they want more

What doesn't carry over is the core guarantee. In a JVM the holder and the waiters fail together, so the holder really is the only one acting.

A distributed lock has to be a lease, and a holder can pause in a long GC or get partitioned past its lease, the lock is granted to someone else, and then the first process wakes up and writes, still believing it holds the lock.

The only reliable defence is a fencing token: an increasing number issued with each grant, which the resource checks and uses to reject older holders.

But once the resource compares a number on every write, that's optimistic concurrency, so my stance for an organisation is to avoid distributed locks for correctness where we can: unique constraints, version columns and conditional updates in the database, or single-writer partitions such as one Kafka partition per key.

Where a lock is truly needed, I'd require a proven consensus-backed system like ZooKeeper or etcd, label each lock as efficiency or correctness, and document how it behaves when the holder pauses or the service is unreachable.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "In distributed systems, locks become leases with timeouts and fencing tokens. Which...": https://scrivio-interview-library.netlify.app/java/locks/a7cb30d231/