Scrivio Interview library
CodingIntermediate7 min read · updated 13 November 2026

A fencing token is a number that increases each time a lock is granted. The protected resource checks it, so a client whose lock has expired cannot overwrite newer work.

Implement lock acquisition that returns a fencing token in one Redis Lua script, and show how the database update uses the token to reject stale writers.

One Lua script does SET lock NX PX and, only if that succeeds, INCR on a counter key, returning the new number as the fencing token; both keys share a hash tag so the script runs in Redis Cluster. Every write to the database carries the token, and the UPDATE only applies WHERE fence < :token, so a client whose lock expired and was granted to someone newer updates zero rows and must stop. The check has to happen inside the resource, atomically with the write, and the counter must never go backwards.

Why this question is asked

Any lock with an expiry can be lost while its holder is still working, because of a garbage-collection pause, a slow network or a failover. Fencing tokens are the standard answer: they do not prevent the old holder from waking up, but they stop it from doing damage. Interviewers ask for the implementation because the details matter, especially where the check happens. In this answer, we will see the problem fencing solves, write the acquisition script, use the token in a conditional UPDATE, see why checking in the client is not enough, protect the counter from going backwards, and release the lock safely.

1The Problem Fencing Solves

Client A acquires lock:{report:7} with a 10-second lease and starts rebuilding report 7. It pauses for 15 seconds in a full garbage collection. The lease expires, client B acquires the lock, writes a fresh report and finishes. Then A wakes up, still believing it holds the lock, and writes its stale report over B's. The lock did its job; the problem is that A had no way of knowing it had lost it.

A fencing token is a number that increases every time the lock is granted. A gets 41, B gets 42. The database remembers the highest token it has accepted for report 7, and refuses a write with a lower one. A's late write carries 41 when 42 has already been seen, so it is rejected.

2Acquiring the Lock and the Token in One Script

The lock and the counter must change together. If we set the lock and then, in a separate command, incremented the counter, a crash between the two could leave a lock without a token, and two clients could interleave their calls. A Lua script runs atomically in Redis, so both happen as one step.

SQL
-- KEYS[1] = lock:{report:7} KEYS[2] = fence:{report:7}
-- ARGV[1] = random owner value ARGV[2] = lease in ms
if redis.call('SET', KEYS[1], ARGV[1], 'NX', 'PX', ARGV[2]) then
return redis.call('INCR', KEYS[2]) -- 42: the new fencing token
end
return nil -- lock is held by someone else

SET with NX returns OK when it creates the key, which Lua sees as true, and a nil reply when the key exists, which Lua sees as false. So INCR only runs for the client that actually got the lock. The two key names share the hash tag {report:7}: in Redis Cluster only the part inside the braces is hashed, so both keys land in the same slot, which a script requires.

3Calling It From Java

With Spring Data Redis, we load the script once as a RedisScript<Long> and execute it with the two keys and two arguments. A null result means someone else holds the lock.

Java
RedisScript<Long> acquire = RedisScript.of(new ClassPathResource("acquire_fenced.lua"), Long.class);
String owner = UUID.randomUUID().toString();
Long token = redis.execute(acquire,
List.of("lock:{report:7}", "fence:{report:7}"), owner, "10000");
if (token == null) return; // busy: someone else holds the lock
rebuildReport(7, owner, token); // token = 42, sent with every write

4Using the Token in the Database Write

The database row stores the highest token it has accepted. The write succeeds only if our token is higher, and in the same statement it records our token. That single conditional UPDATE is the whole check.

Java
int rows = jdbc.update(
"UPDATE report SET body = ?, fence = ? WHERE id = 7 AND fence < ?",
body, token, token);
// B with token 42, current fence 41 -> rows = 1, fence is now 42
// A with token 41, current fence 42 -> rows = 0: a newer holder exists
if (rows == 0) throw new LockLostException("report 7 taken over by a newer lock holder");
Step throughA stale writer is fenced off
Client ARedisClient BDatabase
acquire: token 41
GC pause 15 s, lease expires
acquire: token 42
UPDATE ... WHERE fence < 42
1 row, fence = 42
UPDATE ... WHERE fence < 41
0 rows: stop

7 messages in order. Play them, or step through them one at a time.

The resource, not the lock, rejects the late write.

Zero updated rows is the signal to stop: the client must not retry or fall back to an unconditional write, because a newer holder has already done the work. Report rows start with fence = 0 so the first token is accepted.

5Why the Check Must Live in the Resource

It is tempting to read the current fence first, compare in Java, and then write. That leaves exactly the gap fencing is meant to close: A reads fence 41, decides 41 is fine, pauses, B writes 42, and then A writes anyway. The comparison and the write must be one atomic operation inside the resource. A conditional UPDATE does that in a relational database; in other stores we use a compare-and-set, a conditional put or a version check that the store evaluates itself.

6Keeping the Counter From Going Backwards

The fence counter lives in Redis, and Redis can lose recent writes on failover or restart. If the counter dropped from 42 back to 40, the next holders would receive 41 and 42 again, the database would reject them as stale, and report 7 would be stuck until the counter caught up. We would rather be stuck than corrupt the data, but it is still an outage.

Two fixes work. We can seed the counter from the resource on start-up or after a failover, setting it to at least the highest fence stored in the database, with a script that only raises it. Or we can keep the counter in the database itself, for example a sequence, and use Redis only for the lock. The second is simpler when the resource is already a database.

7Releasing the Lock Safely

Release still uses compare-and-delete: delete the lock key only if it holds our random owner value. Otherwise a late client like A, finishing after its lease expired, would delete B's lock and let a third client in. The fence counter is never deleted; it only grows.

SQL
-- KEYS[1] = lock:{report:7} ARGV[1] = owner value
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1]) -- 1: released our own lock
end
return 0 -- 0: expired or owned by another client

8Follow-up questions

What if the resource is an external API that cannot check tokens?

Then fencing cannot be enforced at the resource, and we fall back to idempotency. We send an idempotency key that identifies the operation, such as 'report-7-version-42', if the API supports one, so a repeated call has no extra effect. If it supports neither, we can put a small service of our own in front of it that checks tokens, or accept that the lock is best effort and design for detecting and repairing duplicates.

Why not use the lock's random value as the token?

Because random values are not ordered. The resource needs to know which holder is newer, and only a monotonically increasing number tells it that. The random value proves ownership for release; the token proves recency for writes.

Does the token need to be checked on reads?

Usually not, because a stale reader does no harm by itself. It matters when a client reads, computes and writes; that final write carries the token and is rejected if the client has been superseded.

9Conclusion

In this answer, we wrote a Lua script that sets the lock with NX PX and, only on success, increments a counter and returns it as the fencing token, with a shared hash tag so it runs in Cluster. Each database write carries the token in a conditional UPDATE that requires fence < :token, and zero updated rows tells a stale client to stop. The check must be atomic inside the resource, the counter must never go backwards, so we seed it from the resource or keep it in the database, and release still uses compare-and-delete.

What to say in the interviewAbout 90 seconds aloud

Open with

The acquire script does SET on the lock key with my random value, NX and PX, and only if that returns OK does it INCR a counter key and return the result as the fencing token; otherwise it returns nil.

Then, if they want more

Both keys use the same hash tag, lock:{report:7} and fence:{report:7}, so they're in one slot and the script runs in Cluster. Because it's a script, the lock and the token are granted atomically. Then every write carries the token: UPDATE report SET body = ?, fence = :token WHERE id = 7 AND fence < :token.

If it updates zero rows, a newer holder has already written, so my client stops, it doesn't retry or force the write. The important part is that the comparison happens inside the database as part of the write; checking in Java first and then writing leaves the same race the token is meant to close.

I also make sure the counter never goes backwards. If Redis failover could lose it, I seed it from the highest fence stored in the database or keep the counter in the database itself. Release is still compare-and-delete on the lock value, so a client that wakes up late can't delete someone else's lock.

If the resource can't check tokens, like an external API, I fall back to idempotency keys.

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 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 "Implement lock acquisition that returns a fencing token in one Redis Lua script, and...": https://scrivio-interview-library.netlify.app/databases/redis-patterns/d27c55de63/