Scrivio Interview library
DesignAdvanced8 min read · updated 12 November 2026

Teams across the company implement distributed locks in five different ways (Redis SET NX, Redisson, database advisory locks, ShedLock, ZooKeeper). Define a standard for when and how to use locks.

A good standard starts by sorting lock uses into three classes by what a failure costs: deduplicating scheduled jobs, efficiency locks that only save duplicate work, and correctness locks where two holders would corrupt data. Each class gets one supported tool (ShedLock or a database lock for jobs, Redis with a token and TTL for efficiency, and database constraints, optimistic locking, fencing tokens or a consensus store for correctness), plus metrics, TTL guidance and a rule that the protected work must be idempotent.

Why this question is asked

When five teams solve the same problem in five ways, the company pays five times: five sets of bugs, five things to monitor and five ways to fail during an incident. Distributed locks are a particularly risky place for this, because a lock that silently allows two holders looks fine in testing and only breaks under a network pause or a slow garbage collection. Interviewers ask this at senior level to see whether we can turn a technical mess into a clear rule that teams will actually follow. In this answer, we will see why one lock design cannot fit every need, classify the uses, pick a tool per class, define the guardrails and metrics, and plan how to migrate what already exists.

1A Quick Recap: What a Distributed Lock Really Promises

A distributed lock is a flag stored somewhere shared, such as Redis, a database or ZooKeeper, that says one process currently owns some resource. Other processes check the flag and wait or skip their work while it is held. Inside one JVM a lock is reliable, because the JVM knows exactly which thread holds it. Across machines it is much weaker, because the lock store cannot see the holder. It only knows that someone took the lock and has not released it yet.

So every distributed lock has a lease, a time to live (TTL) after which it expires on its own. Without a lease, a crashed holder would block everyone forever. But a lease creates the central problem: a holder that pauses for longer than the TTL (a 20 second GC pause, a slow network, a stuck remote call) still believes it holds the lock after the store has handed it to someone else. For a short window, there are two holders. Whether that window is harmless or a disaster depends entirely on what the lock protects, and that is why the standard has to start from the use, not from the tool.

2Classifying the Needs by Their Failure Mode

The first rule of the standard is that every team states which of three classes its lock belongs to. The class decides the tool and the review it needs.

Scheduled job deduplication is the most common case: ten instances of a service all run the same nightly report job, and we want it to run once. If it occasionally runs twice, we waste some work and maybe send a duplicate email, which is annoying but survivable. Efficiency locks are similar: we lock to avoid recomputing an expensive cache entry or calling a paid API twice. Two holders cost money or time, not correctness.

Correctness-critical mutual exclusion is different. Here two holders corrupt data: two workers both debit the same account, or both allocate the last seat. For this class the honest position is that a lease-based lock alone is not enough, because the two-holder window always exists. The protection must live where the data lives.

Lock classes and the standard tool for each
ClassIf two holders runStandard tool
Scheduled job dedupJob runs twice; harmless if idempotentShedLock on the service database
Efficiency lockDuplicate work or costRedis SET NX PX with token, Redisson
Correctness lockCorrupted dataDB constraint, optimistic lock, fencing token
Coordination / leaderSplit brainZooKeeper or etcd via the platform
The first question in every review: what breaks if two processes hold this lock?

Notice that the class is about the consequence, not about the code. The same SET NX call can be fine for a cache rebuild and dangerous for a payment. So the standard asks one question first: what breaks if two processes run this at the same moment?

3Choosing One Supported Tool per Class

For scheduled jobs the standard tool is ShedLock backed by the service's own database, or an equivalent database-backed lock. The service already depends on that database, so there is no extra failure point. The key setting is lockAtMostFor, the lease, which must be longer than the longest normal run but short enough that a crashed node does not block tomorrow's run. lockAtLeastFor stops a very fast job from running again on a node whose clock is slightly behind.

Java
@Scheduled(cron = "0 0 2 * * *")
@SchedulerLock(name = "nightlyReport",
lockAtMostFor = "PT30M", // normal run is about 8 minutes
lockAtLeastFor = "PT1M")
public void nightlyReport() {
reportService.buildFor(LocalDate.now().minusDays(1)); // idempotent: upserts one row per day
}

For efficiency locks the standard is Redis: SET key token NX PX 30000, where the token is a random value per holder, and release with a small Lua script that deletes the key only if it still holds our token. The token matters because without it a slow holder whose lease expired would delete the lock that now belongs to someone else. Teams that want waiting and automatic lease renewal use Redisson, configured by the platform team, rather than writing their own.

For correctness the standard says: protect the data, not the code path. A unique constraint, an optimistic version column (UPDATE ... WHERE version = 7) or a conditional write rejects the second writer even when two processes think they hold the lock. Where a lock really is needed, the lock store must issue a fencing token, a number that increases with every grant, and the resource must refuse writes carrying an older number. ZooKeeper or etcd, which use consensus, can provide this; a single Redis key cannot guarantee it during failover. Database advisory locks are acceptable for correctness only when the protected data is in that same database and the work happens in the same transaction.

4Guardrails: Idempotency, Timeouts and Metrics

Two rules apply to every class. First, the protected operation must be idempotent, meaning that running it twice gives the same result as running it once. A report job that upserts one row per day is idempotent; one that appends rows is not. Idempotency turns the unavoidable two-holder window from an incident into a non-event, so it is a stronger guarantee than any lock setting.

Second, no lock may be held across a remote call that has no timeout. If a service takes a lock and then calls a partner API with an infinite timeout, the lease will eventually expire in the middle of the call and a second holder appears. Every remote call inside a locked section needs a timeout shorter than the remaining lease, and the TTL guidance in the standard says to set the lease to about two to three times the 99th percentile hold time.

The supported libraries come wrapped by the platform team so that every lock emits the same metrics: time spent waiting to acquire, time held, how often acquisition fails, and, most important, how often a lease expired before the holder released it. That last number is the direct measure of the two-holder window. If it is above zero for a correctness lock, someone is relying on luck.

5Reviewing and Migrating the Existing Locks

A standard that only applies to new code changes little. So we inventory the existing uses, which is usually a few days of searching code for SETNX, Redisson, pg_advisory_lock, @SchedulerLock and ZooKeeper recipes, and record for each one its class, store, TTL and owner.

Then we migrate in order of risk, correctness-critical uses first. A payment path that relies on a hand-written Redis lock without a token is a real defect today; a cache rebuild using ZooKeeper is merely unusual. For each correctness case the fix is usually to add a constraint or version check, after which the lock becomes an efficiency measure and can stay as it is. Efficiency and job locks move to the standard tools as teams touch that code, with a deadline for removing the last custom implementations.

Step throughHow a team picks its lock
  1. Could two holders corrupt data?
    YesProtect the data: constraint, version or fencingNoContinue
  2. Is it a scheduled job?
    YesShedLock with lockAtMostForNoRedis lock with token and TTL
  3. Make the work idempotentA duplicate run must be harmless
  4. Add timeouts to remote callsShorter than the remaining lease
  5. Use the platform wrapperWait, hold and expiry metrics come for free

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

The decision every lock review follows.

6Follow-up questions

How would you detect two holders of a lock in production?

The cheapest signal is the metric for leases that expired before release, because every such event opens a window where a second process can acquire the lock. To catch actual overlaps, the wrapper logs the holder id, token and acquire and release times, and a query looks for intervals on the same lock name that overlap. For correctness locks, fencing tokens give the strongest evidence: the resource counts writes it rejected because they carried an older token. Finally, business checks such as duplicate rows or reconciliation mismatches show the effect even when the lock layer saw nothing.

Why not simply standardise on Redlock for everything?

Redlock spreads the lock over several independent Redis nodes, which helps when one node fails, but it still relies on leases and timing, so a paused holder can still overlap with a new one. It adds operational cost without giving fencing tokens. For efficiency locks a single Redis with a token is enough, and for correctness we want the data store itself to reject stale writers.

Are database advisory locks a good default?

They are attractive because they need no extra system and they are released automatically when the session ends. But they tie up a connection for the whole hold time, they do not work across databases, and connection poolers in transaction mode can break session-level locks. They fit when the work and the data are in the same database, often inside one transaction.

7Conclusion

In this answer, we saw that the five implementations are really answers to three different needs. We classified locks by what two holders would break, gave each class one supported tool, made idempotency and timeouts mandatory, added metrics that measure the two-holder window directly, and migrated correctness-critical uses first, often by moving the protection into the database itself.

What to say in the interviewAbout 80 seconds aloud

Open with

I would start by classifying every lock by what happens if two processes hold it at once, because a lease-based lock can always have a short window with two holders.

Then, if they want more

Scheduled job deduplication goes to ShedLock on the service's own database with a sensible lockAtMostFor. Efficiency locks, where a duplicate only wastes work, use Redis SET NX with a random token and a TTL, released by a Lua script that checks the token, or Redisson through a platform wrapper.

For correctness-critical cases I would not rely on the lock at all: I would use a unique constraint, an optimistic version column, or fencing tokens checked by the resource, and a consensus store like ZooKeeper or etcd only where real coordination is needed.

Every class gets one supported library that emits wait time, hold time, failures and leases that expired before release, plus TTL guidance of two to three times the p99 hold time. Two rules apply everywhere: the protected work must be idempotent, and no lock is held across a remote call without a timeout.

Then I would inventory existing uses and migrate the correctness-critical ones first, since those are live risks, and let the others converge as teams touch the code.

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.
Official documentation
Redis documentation
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 "Teams across the company implement distributed locks in five different ways (Redis SET...": https://scrivio-interview-library.netlify.app/databases/redis/3466449fc9/