Quick revision
The short answer
We keep one row per lease in a PostgreSQL table with the holder, a token that increases on every acquisition and an expiry computed with the database's now(). Acquire, renew and release are conditional UPDATEs whose row count tells us whether we hold the lease, and every write to the assignments table carries the token in its WHERE clause, so a holder that lost the lease updates zero rows and must stop. In Java, a scheduled task renews every third of the lease time and stops all work as soon as a renewal fails.
What to remember
In this answer, we built a lease with a fencing token in PostgreSQL. One row per lease holds the holder, an ever-increasing token and an expiry computed with the database's now(). Acquire, renew and release are conditional UPDATEs where zero rows means the lease is not ours, and every protected write either checks fence <= token or reads the lease row FOR SHARE in the same transaction. In Java, we renew every third of the lease time, pass the token to every write and stop all work as soon as a renewal fails.
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.
We keep one row per lease in a PostgreSQL table with the holder, a token that increases on every acquisition and an expiry computed with the database's now(). Acquire, renew and release are conditional UPDATEs whose row count tells us whether we hold the lease, and every write to the assignments table carries the token in its WHERE clause, so a holder that lost the lease updates zero rows and must stop. In Java, a scheduled task renews every third of the lease time and stops all work as soon as a renewal fails.
Why this question is asked
Many teams reach for Redis or ZooKeeper the moment they need a lease, but the database they already run is strongly consistent, transactional and monitored. Interviewers like this question because it shows whether we can build a correct lease from first principles, including the fencing that makes it safe, rather than just calling a library. In this answer, we will create the lease table, write acquire, renew and release, add a guarded update that rejects a stale holder, and then put it together in Java with a renewal loop.
1A Quick Recap of Leases and Fencing Tokens
A lease is a lock that expires on its own, so a crashed holder cannot block others forever. The catch is that a holder may be paused past the expiry and then continue as if it still held the lease. A fencing token solves that: every time the lease changes hands, a number goes up, and the protected data only accepts writes carrying the newest number. The lease decides who should work; the token makes sure an old holder cannot do damage.
2The Lease Table
We create one table and insert one row per lease name. Starting the expiry in the past means the first caller can acquire it immediately.
The token column is the heart of the design. It only ever increases, and each new holder receives a value no previous holder had.
3Acquire, Renew and Release
Each operation is a single conditional UPDATE. PostgreSQL locks the row while it updates it, so two callers can never both succeed.
Notice that every time comparison uses now() on the database. All callers are judged by one clock, the database server's, so a pod whose clock runs two minutes fast cannot decide a lease has expired early. And because renew and release check both holder and token, a pod that lost the lease and later acquired it again cannot accidentally renew with an old token. Zero rows updated always means the same thing: the lease is no longer ours.
4The Guarded Update That Rejects a Stale Holder
The lease alone does not stop a paused holder, so every write to the protected table carries the token. There are two ways to check it.
7 messages in order. Play them, or step through them one at a time.
Option 1 needs no extra query, but it only protects rows that the new holder has already touched. Option 2 protects every write in the transaction: FOR SHARE locks the lease row, so a new acquirer's UPDATE must wait until our transaction commits, which means the token cannot change between our check and our write. That is also why transactions must stay short; a long transaction holding FOR SHARE delays failover.
5Putting It Together in Java
In Java we renew on a ScheduledExecutorService every third of the lease time, 10 seconds for a 30-second lease, so two renewals can fail before the lease runs out. The moment a renewal returns zero rows or throws, we stop all work.
Notice that a failed renewal is treated as a lost lease even if the database is merely slow. That is deliberate: if we cannot prove we hold the lease, we stop, and the fencing check catches the rare case where we are too slow even to notice.
6Follow-up questions
Why is now() on the database safer here than System.currentTimeMillis() on the client?
Because the lease is then judged by a single clock. If each pod computed expiry from its own clock, a pod whose clock is a minute ahead would believe a lease expired a minute early and take it while the holder is still working. Using now() means every acquire and renew compares against the database server's time, so client clock skew does not matter at all. Note that now() returns the start time of the current transaction, which is fine for these single-statement updates.
Why renew every third of the lease time?
With a 30-second lease and a 10-second renewal interval, two consecutive renewals can fail, for example during a short database failover, and the lease still has not expired. Renewing more often adds load for little gain; renewing less often leaves too little margin.
What if the database fails over to a replica?
With synchronous replication the lease row and tokens survive, and the conditional updates keep working. With asynchronous replication a recent acquisition could be lost, so the token could be reused; teams that need strict fencing across failovers use synchronous replication for this table or accept the small risk.
7Conclusion
In this answer, we built a lease with a fencing token in PostgreSQL. One row per lease holds the holder, an ever-increasing token and an expiry computed with the database's now(). Acquire, renew and release are conditional UPDATEs where zero rows means the lease is not ours, and every protected write either checks fence <= token or reads the lease row FOR SHARE in the same transaction. In Java, we renew every third of the lease time, pass the token to every write and stop all work as soon as a renewal fails.
Open with
I would keep one row per lease in a table with name as the primary key, the holder, a bigint token and expires_at as timestamptz. Acquiring is a single update that sets holder to me, increments the token and sets expires_at to now plus thirty seconds, only where expires_at is already in the past, returning the token; if I get a row back, I hold the lease with that token.
Then, if they want more
Renewing extends expires_at where name, holder and token all match mine, and releasing sets expires_at to now with the same conditions. In every case, zero rows updated means I have lost the lease. All the time comparisons use the database's now(), so client clock skew cannot make anyone think a lease expired early.
For the protected data, every write carries the token: either the assignments table has a fence column and I update where fence is less than or equal to my token, or I read the lease row FOR SHARE in the same transaction and check the token still matches, which blocks a new acquirer until I commit.
A stale holder updates zero rows and stops. In Java I would renew on a ScheduledExecutorService every ten seconds, a third of the lease, treat a zero-row renewal or an exception as lost leadership, stop all workers immediately, pass the token to every write and keep the transactions short.
About this answer
- Last updated
- 13 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 official documentation for the version you use. 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 "Write the SQL and outline the Java code for a lease with a fencing token in PostgreSQL...": https://scrivio-interview-library.netlify.app/architecture/distributed-systems/2486a50a72/