Quick revision
The short answer
The standard starts by asking whether a lock is needed at all, because idempotent work, unique constraints or partitioned work assignment often remove it. When the protected work lives in the same database, a database lock is the preferred tool, since the lock and the data change commit together. For long work, locks must be leases with expiry plus fencing tokens checked by the resource, because a holder can pause or lose its connection; Redis locks without fencing are not allowed for correctness-critical work, and ZooKeeper or etcd are reserved for cases that justify their cost. Everyone uses one library with documented guarantees and monitoring for stuck locks.
What to remember
In this answer, we saw that the first rule of distributed locking is to avoid it through idempotency, unique constraints or partitioning. Database locks fit work in the same database because they commit with the data, long work needs leases with expiry and fencing tokens checked by the resource, Redis locks without fencing are for efficiency only, and ZooKeeper or etcd give stronger guarantees at a higher operational cost. One shared library with documented guarantees, a lock registry and monitoring for stuck locks keep the whole company consistent.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The standard starts by asking whether a lock is needed at all, because idempotent work, unique constraints or partitioned work assignment often remove it. When the protected work lives in the same database, a database lock is the preferred tool, since the lock and the data change commit together. For long work, locks must be leases with expiry plus fencing tokens checked by the resource, because a holder can pause or lose its connection; Redis locks without fencing are not allowed for correctness-critical work, and ZooKeeper or etcd are reserved for cases that justify their cost. Everyone uses one library with documented guarantees and monitoring for stuck locks.
Why this question is asked
Distributed locks are one of those tools that every team reaches for and few teams reason about carefully, so an organisation ends up with five mechanisms that each fail in a different way under pauses and network trouble. Interviewers ask this design question to see whether we know what a lock can and cannot promise across machines, and whether we can turn that into a standard teams can follow. In this answer, we will start with whether a lock is needed, then look at when database locks are the right choice, why long work needs leases and fencing tokens, how Redis, ZooKeeper and etcd compare, and finally the shared library and monitoring.
1First Question: Do We Need a Lock at All?
Many locks exist to stop duplicate work, and duplicates are often cheaper to make harmless than to prevent. If the work is idempotent, meaning that doing it twice has the same effect as once, two pods running it occasionally costs some CPU and nothing more. A unique constraint can turn the race into a clean failure: two pods trying to create the invoice for order 42 cannot both succeed if (order_id) is unique, so the database decides the winner.
Partitioning removes contention by design. If each pod owns a hash range of tenants, or each Kafka consumer owns a set of partitions, no two workers ever touch the same key, and there is nothing to lock. The standard should make teams answer this question in writing before adding a lock, because every lock is a new failure mode.
- Can the work be idempotent or guarded by a unique constraint?Yesno lock neededNokeep going
- Is the protected work in the same database?Yesdatabase lock in the same transactionNokeep going
- Short work, and occasional duplicates acceptable?Yeslease lock via the shared libraryNolease plus fencing token checked by the resource
- Register and monitor the lockname, owner, expected hold time, alerts on stuck locks
4 steps in order. Play them, or step through them one at a time.
2Database Locks When the Work Is in the Same Database
If the job's effect is a set of writes in PostgreSQL, the strongest guarantee comes from taking the lock in that same database and transaction: SELECT ... FOR UPDATE on a row, or pg_try_advisory_xact_lock. The lock and the data change commit or roll back together, so there is no gap in which the lock has expired but the writes are still landing. If the holder's connection dies, PostgreSQL rolls back the transaction and releases the lock at the same moment, which is exactly the safety we want.
The rules for this case are the ones we already know: keep the transaction short, use transaction-scoped locks rather than session ones (especially behind PgBouncer), and do not use a dummy-row lock to cover work that happens in other systems, because the database cannot roll those back.
3Leases and Fencing Tokens for Long Work
For work that lasts minutes or touches other systems, we cannot hold a database transaction open, so the lock becomes a lease: a record that says pod A holds job X until 02:15, renewed while A is alive. Leases solve crashes, because the lock expires, but they create a new danger. Pod A can pause, for example in a 40-second garbage collection or a frozen VM, and its lease expires. Pod B takes the lock and starts working. Then A wakes up, still believing it holds the lock, and writes stale data over B's work.
The fix is a fencing token: a number that increases every time the lock is granted. Pod A got token 33, pod B got token 34. Every write to the protected resource carries the token, and the resource rejects any write with a token lower than the highest it has seen. So when A wakes up and writes with 33, the write is refused. The important point is who checks it: the resource being protected, not the lock service, because only the resource sees the late write.
6 messages in order. Play them, or step through them one at a time.
4Redis, ZooKeeper and etcd
A Redis lock, SET key value NX PX 30000, is fast and easy, and it is fine for efficiency locks, where a rare duplicate only wastes work. For correctness-critical work, the standard should not allow it on its own: it gives no fencing token, a failover to a replica can lose a lock that was just written, and the timing assumptions of multi-node schemes such as Redlock are debated. With a fencing check at the resource it can be acceptable, but then the safety comes from the fence, not from Redis.
ZooKeeper and etcd are built on consensus protocols and give stronger guarantees: sessions or leases tied to client liveness, and monotonically increasing revision or sequence numbers that work naturally as fencing tokens. The cost is another clustered system to run, secure and understand. The standard reserves them for cases that need coordination outside any single database, such as leader election for a stateful component, and where a platform team already runs one.
| Mechanism | Guarantee | Allowed for |
|---|---|---|
| Row or xact advisory lock | commits with the data | work inside the same database |
| Lease table (ShedLock style) | expiry, no fencing by default | scheduled jobs, idempotent work |
| Redis SET NX PX | best effort, lost on failover | efficiency only, or with a fence |
| ZooKeeper or etcd | consensus, tokens via revisions | leader election, critical cross-system work |
5One Library, Documented Guarantees, Monitoring
Teams should not each write lock code. The platform provides one library, for example ShedLock for scheduled jobs and Spring Integration's LockRegistry (with JDBC, Redis or ZooKeeper implementations) for code-level locks, configured with the approved backends and documented guarantees: what happens on crash, on pause, on network partition, and whether a fencing token is available.
Every lock is registered with a name, an owning team and an expected hold time. Monitoring alerts when a lock has been held much longer than expected, when a lease is close to expiry while work is still running, and when acquisition failures spike. Stuck locks are the most common incident with home-grown coordination, and they are cheap to detect when every lock goes through one library.
6Follow-up questions
What is a fencing token and who checks it?
It is a number that the lock service increases every time it grants the lock, so each holder gets a larger token than the one before. The holder sends it with every write to the protected resource, and the resource, such as a database row, a storage service or an API, remembers the highest token it has accepted and rejects any lower one. The resource must check it, because only the resource can see that a write arrived from a holder whose lease has already expired.
Why not make the lease very long so expiry never happens?
A long lease means that when a holder really crashes, nobody can do the work until the lease runs out, perhaps for an hour. It also does not remove the pause problem, only makes it rarer. A short lease with regular renewal plus a fencing check gives fast recovery and safety together.
Is SELECT FOR UPDATE on a dummy row acceptable?
It works for short work inside the same database and transaction, and is equivalent to an advisory lock there. It is not acceptable as a lock for long work in other systems, because the transaction must stay open, holding a connection and holding back vacuum, and the lock vanishes if the connection drops while the external work carries on.
7Conclusion
In this answer, we saw that the first rule of distributed locking is to avoid it through idempotency, unique constraints or partitioning. Database locks fit work in the same database because they commit with the data, long work needs leases with expiry and fencing tokens checked by the resource, Redis locks without fencing are for efficiency only, and ZooKeeper or etcd give stronger guarantees at a higher operational cost. One shared library with documented guarantees, a lock registry and monitoring for stuck locks keep the whole company consistent.
Open with
My standard would start with: prove you need a lock. Idempotent work, a unique constraint that lets the database pick the winner, or partitioning work so each pod owns its keys removes most locks, and every lock is a failure mode.
Then, if they want more
If the protected work is in the same database, the lock should be there too, a row lock or a transaction-scoped advisory lock, because the lock and the data commit together, and if the connection dies both are rolled back.
For long work, or work in other systems, locks must be leases with expiry, and for correctness-critical work also fencing tokens: an increasing number issued with each grant, sent with every write, and checked by the resource, which rejects anything lower than it's already seen.
That's what protects us from a holder that paused in GC and woke up after its lease expired. Redis SET NX locks are fine for efficiency but not alone for correctness, since there's no fencing and failover can lose locks. ZooKeeper or etcd give real guarantees and natural tokens, but they're another cluster to run, so only where justified.
Finally, one approved library, ShedLock or Spring Integration's LockRegistry, with documented behaviour, a registry of lock names, and alerts on locks held too long.
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
- PostgreSQL documentation, MySQL reference manual
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 "Several teams use the main PostgreSQL database for distributed locking (advisory locks...": https://scrivio-interview-library.netlify.app/databases/database-locking/db866a1e7a/