Quick revision
The short answer
We acquire the lock with SET lock:nightly <random-token> NX PX 30000, which creates the key only if it does not exist and gives it a 30-second expiry; success means we hold the lock until we release it or it expires. The token is unique to this holder, so on release we run an atomic compare-and-delete Lua script that deletes the key only if it still holds our token. A plain GET followed by DEL is wrong because the lock can expire and be taken by another instance between the two calls, and we would delete their lock; for jobs longer than the TTL we extend the lock with a watchdog or choose a TTL above the job's maximum.
What to remember
In this answer, we built a Redis lock for a nightly job. We acquire it atomically with SET lock:nightly <random-token> NX PX 30000, so only one instance succeeds and the lock expires if its holder crashes. We release it with a Lua compare-and-delete script that deletes the key only if it still holds our token, because GET followed by DEL lets the lock expire and pass to another instance between the two calls, and we would delete that instance's lock. For long jobs we use a TTL above the job's maximum or a watchdog that extends the lock, and we make the job idempotent.
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 acquire the lock with SET lock:nightly <random-token> NX PX 30000, which creates the key only if it does not exist and gives it a 30-second expiry; success means we hold the lock until we release it or it expires. The token is unique to this holder, so on release we run an atomic compare-and-delete Lua script that deletes the key only if it still holds our token. A plain GET followed by DEL is wrong because the lock can expire and be taken by another instance between the two calls, and we would delete their lock; for jobs longer than the TTL we extend the lock with a watchdog or choose a TTL above the job's maximum.
Why this question is asked
Running a scheduled job on several instances of a service is common, and so is the bug where the nightly report runs three times because three instances woke up at 02:00. A Redis lock is the usual quick fix, and interviewers ask for it because the simple version has a subtle race in its release step that many people get wrong. In this answer, we will recap what we need from a lock, write the acquire command, reproduce the broken GET-then-DEL release, fix it with a Lua script, write the whole thing in Spring, and deal with jobs that outlive the lock.
1A Quick Recap of What a Lock Needs
A lock for one nightly job needs three properties. Only one instance may hold it at a time. If the holder crashes, the lock must not stay held forever, or the job would never run again. And only the holder may release it, so that one instance cannot free a lock another instance holds.
Redis gives us the first two with one command. Because Redis executes commands one at a time, a command that creates a key only if it is absent is an atomic test-and-set: exactly one of several instances racing at 02:00 will succeed. An expiry on the key handles crashes. The third property needs a little more care.
2Acquiring the Lock
The acquire is a single SET with two options. NX means set only if the key does not exist; PX 30000 sets an expiry of 30,000 milliseconds in the same atomic step. The value is a random token, such as a UUID, unique to this attempt.
Notice why it must be one command. The older pattern of SETNX followed by EXPIRE has a gap: if the process crashes between them, the key exists without an expiry and the lock is held forever. SET with NX and PX together closes that gap.
The random token is what identifies the holder. If every instance wrote the value 1, nobody could tell later whose lock it was.
3Why GET Followed by DEL Is Wrong
The natural release is: read the key, check that it holds our token, then delete it. The trouble is that these are two separate commands, and the world can change between them.
7 messages in order. Play them, or step through them one at a time.
The check and the delete must be one atomic step.
The check was true when we made it, but by the time DEL ran, the key belonged to someone else. Deleting it frees B's lock while B is still running the job, so a third instance can start. The race window is small, but at scale small windows happen, and they happen exactly when systems are slow, which is when jobs overrun their TTL.
4The Fix: Compare-and-Delete in Lua
Redis runs a Lua script atomically: no other command executes while it runs. So we move the check and the delete into one script. It deletes the key only if its value is still our token, and returns 1 if it deleted and 0 otherwise.
Notice that a 0 result is information worth logging: it means our lock expired before we released it, so the job ran longer than the TTL and another instance may have run it too. Newer Redis versions also offer a native compare-and-delete style command in some releases; check your version, but the Lua script works everywhere.
5The Whole Lock in Spring
Here is the same lock in a Spring Boot service with StringRedisTemplate. setIfAbsent with a Duration sends SET NX PX, and a DefaultRedisScript runs the release.
We chose a TTL of 30 minutes because this job normally takes 5 and has never taken more than 12. That is the simplest answer to long jobs: a TTL comfortably above the job's maximum. The cost is that if the instance crashes, the lock blocks a rerun for up to 30 minutes, which for a nightly job is acceptable.
6When the Job Can Outlive the Lock
If the job's duration is unpredictable, a fixed TTL is either too short, risking overlap, or too long, delaying recovery. The alternative is a watchdog: a short TTL, say 30 seconds, renewed every 10 seconds by a background thread while the job runs, using a script that extends the expiry only if the token is still ours. If the process dies, renewals stop and the lock expires within 30 seconds. Redisson's RLock does exactly this automatically when we lock without a lease time.
Even with a watchdog, a long pause of the whole process can stop renewals and let the lock expire while the job still thinks it holds it. For a nightly report, an occasional duplicate run is usually harmless if the job is idempotent, for example if it overwrites the same report file. For correctness-critical work, a lock alone is not enough and the protected resource must also check a fencing token.
7Follow-up questions
What happens if the process pauses for a long GC during the job?
If the pause is longer than the remaining TTL, the lock expires, another instance acquires it and starts the job, and when our process wakes up it carries on as if it still held the lock. Both run at once. A watchdog cannot help because it was paused too. The protections are making the job idempotent, so a duplicate run does no harm, and for writes that must not overlap, a fencing token checked by the resource, such as a version column the database update compares.
Why not use Spring's ShedLock or a database lock instead?
Both are good options. ShedLock is a small library built exactly for scheduled jobs, with Redis, JDBC and other providers, and it handles the details above for us. A database row lock or advisory lock is attractive when the job writes to that database anyway, because the lock then lives where the work happens. The Redis version is useful to understand because those tools are built on the same ideas.
Is this lock safe with Redis replication?
Not perfectly. If the primary acknowledges our SET and fails before replicating it, the promoted replica has no lock and another instance can acquire it. For a nightly job that rare overlap is acceptable; for stronger guarantees we need fencing or a consensus-based lock service.
8Conclusion
In this answer, we built a Redis lock for a nightly job. We acquire it atomically with SET lock:nightly <random-token> NX PX 30000, so only one instance succeeds and the lock expires if its holder crashes. We release it with a Lua compare-and-delete script that deletes the key only if it still holds our token, because GET followed by DEL lets the lock expire and pass to another instance between the two calls, and we would delete that instance's lock. For long jobs we use a TTL above the job's maximum or a watchdog that extends the lock, and we make the job idempotent.
Open with
To acquire, I run SET lock:nightly with a random token as the value, NX and PX 30000, as one command. NX means only one instance can create the key, so exactly one wins, and PX gives it an expiry in the same atomic step, so a crashed holder cannot keep the lock forever; the old SETNX then EXPIRE pattern had a gap there.
Then, if they want more
The value must be a unique token per holder, such as a UUID, so that later I can tell whether the lock is still mine. To release, I run a small Lua script: if GET of the key equals my token, DEL it, otherwise return zero. Lua runs atomically in Redis, so the check and the delete cannot be separated.
A plain GET followed by DEL is wrong because it is two commands: between them my lock can expire, for example during a GC pause, another instance can acquire it, and my DEL then deletes their lock, letting a third instance in. In Spring I would use setIfAbsent with a Duration and execute a DefaultRedisScript.
If the job can run longer than the TTL, I either choose a TTL well above its maximum duration, or use a watchdog that extends the lock periodically while my token is still there, which is what Redisson does, and I make the job idempotent in case of overlap.
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
- 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 a simple lock in Redis so that only one instance runs a nightly job. Show the...": https://scrivio-interview-library.netlify.app/databases/redis/65da03b453/