Video in progress

How do you write a simple distributed lock on top of Redis, and what is an easy mistake to make when releasing it?

You acquire it with SET lock:key <unique-token> NX PX 30000. On release you may delete only if the token is yours, and the check plus the delete must be atomic in one Lua script. A plain DEL can remove someone else's lock.

📖 Answer

The classic mistake:

A: SET lock NX PX 30000   -> OK
A: long GC pause, 35 s
   the lock expired
B: SET lock NX PX 30000   -> OK
A: DEL lock               // deleted B's lock!
C: SET lock NX ...        -> OK, now B and C are running at the same time

The correct version:

String token = UUID.randomUUID().toString();
Boolean ok = redis.opsForValue()
    .setIfAbsent("lock:report", token, Duration.ofSeconds(30));
if (!Boolean.TRUE.equals(ok)) return;
try {
    buildReport();
} finally {
    redis.execute(RELEASE, List.of("lock:report"), token);
}
-- the RELEASE script
if redis.call('get', KEYS[1]) == ARGV[1] then
  return redis.call('del', KEYS[1])
end
return 0

If you call GET and DEL separately from Java, the lock can expire between them and someone else can take it, which is why you use Lua.

Pick a lock lifetime longer than the job, and remember that this lock only gives you an "at most one in most cases" guarantee. Where money is involved you also need DB-level protection (a unique constraint, a version column). If you want a ready-made solution, Redisson's RLock does most of this for you.