Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

You need a distributed lock so that only one instance runs a scheduled job at a time. Discuss using Redis for this, and alternatives.

With Redis, a basic lock is SET lock:job token NX PX 60000, which creates the key only if it does not exist and gives it an expiry, and the holder releases it with a small Lua script that deletes the key only if it still holds its own token. The weak point is expiry: a holder paused by garbage collection or a network stall can lose the lock while it still thinks it holds it, so where correctness matters we add fencing tokens. Often a simpler choice is ShedLock on a database table, a database advisory lock or Kubernetes leader election, and in every case the job should be idempotent so a rare double run does no harm.

Why this question is asked

A scheduled job that sends invoices, cleans up data or syncs with a partner works fine on one instance. Scale the service to four pods and the job runs four times, every time. A distributed lock is the usual answer, and Redis is the usual first idea because it is fast and already there. Interviewers ask this scenario because the simple version is easy, and the interesting part is knowing exactly when it fails and what we do about it. In this answer, we will build the Redis lock correctly, look at how it can let two holders in, see what fencing tokens are, discuss Redisson and Redlock, compare the alternatives, and end with the property that makes all of them safe: idempotence.

1A Quick Recap: What the Lock Must Guarantee

A distributed lock is a lock shared by several processes on different machines. For a scheduled job, it must give two guarantees: at most one instance runs the job at a time, and if the holder crashes, the lock is eventually released so the job is not stuck forever. The second guarantee is why every practical lock has an expiry, a lease, and the first guarantee is exactly what an expiry can break, as we will see.

2Building the Redis Lock Correctly

Acquiring the lock is one atomic command. NX means set only if the key does not exist, and PX gives the expiry in milliseconds. The value is a random token unique to this holder, so we can later prove the lock is still ours.

Java
String token = UUID.randomUUID().toString();
Boolean ok = redis.opsForValue().setIfAbsent("lock:invoice-job", token, Duration.ofSeconds(60));
// SET lock:invoice-job 3f2a... NX PX 60000 -> true for one instance, false for the others
if (Boolean.TRUE.equals(ok)) {
try { runInvoiceJob(); }
finally {
redis.execute(RELEASE, List.of("lock:invoice-job"), token); // 1 if we deleted our own lock, 0 if not
}
}
// RELEASE script, run atomically inside Redis
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
else
return 0
end

The release must compare and delete in one step. A plain DEL would remove a lock that already expired and was taken by another instance. A GET followed by a DEL in Java would leave a gap between the two commands in which exactly that could happen. A Lua script runs atomically in Redis, so nothing can happen in between.

3How Two Holders Can Run at Once

The lock has a 60 second lease. Suppose instance A acquires it and then stops for 70 seconds: a long garbage collection pause, a frozen virtual machine, or a network partition between A and everything else. The key expires, instance B acquires the lock and starts the job. Then A wakes up, has no idea time passed, and continues writing. For a while, both are running. Choosing a longer lease only makes the window rarer, and checking the lock before each write does not help either, because the pause can happen right after the check.

Step throughLease expiry lets two holders in
Instance ARedisInstance BStorage
SET lock NX PX 60000 -> OK
GC pause, 70 s
lock expires after 60 s
SET lock NX PX 60000 -> OK
write batch, token 34
write batch, token 33 (stale)
rejected: 33 < 34

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

Without the token check in storage, both writes would be accepted.

4Fencing Tokens: Making Storage Reject the Stale Holder

The fix that actually closes the gap is a fencing token. Each time the lock is granted, the lock service hands out a number that only ever increases, for example from INCR lock:invoice-job:fence. The holder sends this number with every write, and the storage it writes to remembers the highest number it has seen and rejects anything lower. In the picture above, B got 34 and A still carries 33, so A's late write is refused.

Notice that fencing needs cooperation from the resource being protected, typically a conditional update such as UPDATE ... WHERE last_token < :token in a database. If the job writes to something that cannot check tokens, such as sending emails, fencing is not possible, and we fall back on idempotence.

5Redisson and the Redlock Debate

Redisson, a Redis client library for Java, offers RLock, a lock with a familiar Java Lock interface. Its watchdog keeps extending the lease while the holding thread is alive, 30 seconds by default, which reduces expiries during long but healthy jobs, though a full process pause still stops the watchdog too. Redlock is an algorithm proposed by the Redis author that acquires the lock on a majority of several independent Redis nodes so that one failed node does not lose the lock. Its safety has been publicly debated: critics pointed out that it depends on bounded pauses and clock behaviour and still offers no fencing token. For a scheduled job, the general view is that a single Redis lock is fine for efficiency, avoiding wasted duplicate work, and that neither is enough on its own when a double run would corrupt data.

6The Alternatives Worth Considering

Very often we do not need Redis at all. ShedLock is a small library made for exactly this case: it stores locks in a table of the database the service already uses, and we annotate the scheduled method.

Java
@EnableScheduling
@EnableSchedulerLock(defaultLockAtMostFor = "10m")
class SchedulingConfig {
@Bean LockProvider lockProvider(DataSource ds) {
return new JdbcTemplateLockProvider(JdbcTemplateLockProvider.Configuration.builder()
.withJdbcTemplate(new JdbcTemplate(ds)).usingDbTime().build());
}
}
@Scheduled(cron = "0 0 2 * * *")
@SchedulerLock(name = "invoiceJob", lockAtMostFor = "30m", lockAtLeastFor = "1m")
public void invoiceJob() { ... } // one instance runs it; the others skip this run
Options for a single-runner job
OptionNeedsWatch out for
Redis SET NX PX + Lua releaseRedislease expiry during pauses
Redisson RLockRedis, Redissonwatchdog stops on full pauses too
ShedLock (JDBC)existing database tablelockAtMostFor must exceed job time
PostgreSQL advisory lockPostgreSQL sessionpooled connections hold the session
Kubernetes leader electionLease object, RBACleader change mid-job

lockAtMostFor is the lease that protects against a crashed holder, and lockAtLeastFor prevents a second run when clocks or schedules differ slightly between instances. A PostgreSQL advisory lock, taken with pg_try_advisory_lock(42), is another option: it is released automatically when the session ends, so a crashed holder frees it, though connection pools make session-level locks tricky to manage. On Kubernetes, leader election through a Lease object, for example with Spring Cloud Kubernetes, picks one pod to run all scheduled work. The best choice is usually the store we already operate: if the database is there and Redis is not, ShedLock on the database adds no new dependency.

7The Safety Net: An Idempotent Job

Every option above can, rarely, let two runs overlap. So the last layer of protection is in the job itself. An idempotent job produces the same result whether it runs once or twice: the invoice job marks each invoice as sent in the same transaction that records it, and skips invoices already marked; a sync job uses upserts with natural keys rather than blind inserts. Then the lock becomes an efficiency measure that prevents wasted work, and a double run, if it ever happens, is harmless.

8Follow-up questions

How long should the lease be?

Longer than the job normally takes with a comfortable margin, for example twice the 99th percentile run time, but short enough that a crashed holder does not block the next run for too long. If run time varies a lot, a renewing lock such as Redisson's watchdog or a job that renews its lease between batches fits better.

What happens if Redis fails over while the lock is held?

With asynchronous replication, the lock key may not have reached the replica before it became primary, so a second instance can acquire the same lock. That is another reason to treat a Redis lock as an efficiency lock and keep the job idempotent.

9Conclusion

In this answer, we built a Redis lock with SET NX PX and a random token, released it with an atomic Lua compare-and-delete, and saw how lease expiry during a pause lets two holders run. Fencing tokens close that gap when the protected storage can check them. Redisson adds lease renewal, and Redlock's safety remains debated. ShedLock on the existing database, advisory locks and Kubernetes leader election are often simpler, and an idempotent job is what makes a rare double run harmless whichever lock we choose.

What to say in the interviewAbout 90 seconds aloud

Open with

With Redis, I would acquire the lock with SET key token NX PX, so it only succeeds if the key does not exist and it has an expiry in case the holder crashes.

Then, if they want more

The token is a random value per holder, and I release with a Lua script that deletes the key only if it still holds my token, so I never delete a lock someone else took after mine expired. The catch is the expiry.

If my instance pauses longer than the lease, say a long GC pause or a network partition, the lock expires, another instance takes it, and when mine wakes up both are running. Where that would corrupt data, the real fix is fencing tokens: each acquisition gets an increasing number, and the storage rejects writes with an older number.

Redisson gives a nicer lock with a watchdog that renews the lease, and Redlock spreads it across several Redis nodes, but Redlock's safety has been debated and neither gives fencing.

Honestly, for a scheduled job I would usually reach for ShedLock with the database we already have, a @SchedulerLock with lockAtMostFor and lockAtLeastFor, or a Postgres advisory lock, or Kubernetes leader election if we are on Kubernetes. And whichever I pick, I make the job idempotent, so that a rare double run does nothing harmful.

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
Spring Data reference
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 "You need a distributed lock so that only one instance runs a scheduled job at a time....": https://scrivio-interview-library.netlify.app/databases/spring-data-nosql/567fafbb17/