Scrivio Interview library
CodingIntermediate7 min read · updated 13 November 2026

A job coordinator must make sure that only the current lease holder updates a table of work assignments. The team wants to use the PostgreSQL database they already run rather than add Redis or ZooKeeper.

Write the SQL and outline the Java code for a lease with a fencing token in PostgreSQL: acquire, renew, release, and a guarded update that rejects a stale holder.

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.

SQL
CREATE TABLE lease (
name text PRIMARY KEY,
holder text,
token bigint NOT NULL DEFAULT 0,
expires_at timestamptz NOT NULL
);
INSERT INTO lease (name, expires_at) VALUES ('assignments', '-infinity'); -- INSERT 0 1
CREATE TABLE assignments (
id bigint PRIMARY KEY,
worker text,
fence bigint NOT NULL DEFAULT 0 -- token of the last holder that wrote this row
);

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.

SQL
-- Acquire: only if the current lease has expired
UPDATE lease
SET holder = 'pod-a', token = token + 1, expires_at = now() + interval '30 seconds'
WHERE name = 'assignments' AND expires_at < now()
RETURNING token; -- 1 row: token = 8, we hold the lease; 0 rows: someone else does
-- Renew: only if we still hold it with our token
UPDATE lease SET expires_at = now() + interval '30 seconds'
WHERE name = 'assignments' AND holder = 'pod-a' AND token = 8; -- UPDATE 1 (renewed) or UPDATE 0 (lost)
-- Release: expire it now, with the same conditions
UPDATE lease SET expires_at = now()
WHERE name = 'assignments' AND holder = 'pod-a' AND token = 8; -- UPDATE 1

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.

SQL
-- Option 1: the row remembers the highest token that wrote it
UPDATE assignments SET worker = 'w-17', fence = 8
WHERE id = 501 AND fence <= 8; -- UPDATE 1 for the current holder
-- a stale holder with token 7, after token 8 has written: UPDATE 0
-- Option 2: check the lease in the same transaction
BEGIN;
SELECT token FROM lease WHERE name = 'assignments' FOR SHARE; -- 8: still ours, continue
UPDATE assignments SET worker = 'w-17' WHERE id = 501;
COMMIT;
Step throughA stale holder is rejected
Pod APostgreSQLPod B
acquire: token 7
pause of 45 s, lease expires
acquire: token 8
UPDATE assignments ... fence <= 8
UPDATE 1
wakes: UPDATE ... fence <= 7
UPDATE 0: stop working

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.

Java
public final class PgLease {
private final JdbcTemplate jdbc;
private final String name, me;
private final ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();
private volatile long token = -1; // -1 means "not holding"
public boolean tryAcquire() {
List<Long> t = jdbc.queryForList("""
UPDATE lease SET holder = ?, token = token + 1, expires_at = now() + interval '30 seconds'
WHERE name = ? AND expires_at < now() RETURNING token""", Long.class, me, name);
if (t.isEmpty()) return false; // someone else holds it
token = t.get(0); // e.g. 8
timer.scheduleAtFixedRate(this::renew, 10, 10, TimeUnit.SECONDS);
return true;
}
private void renew() {
try {
int n = jdbc.update("UPDATE lease SET expires_at = now() + interval '30 seconds' "
+ "WHERE name = ? AND holder = ? AND token = ?", name, me, token);
if (n == 0) lost(); // 0: lease taken over
} catch (DataAccessException e) { lost(); } // cannot prove we hold it
}
public int assign(long id, String worker) { // every write carries the token
return jdbc.update("UPDATE assignments SET worker = ?, fence = ? WHERE id = ? AND fence <= ?",
worker, token, id, token); // 0 means we are stale: stop
}
private void lost() { token = -1; timer.shutdownNow(); workers.stopAll(); }
}

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.

What to say in the interviewAbout 90 seconds aloud

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/