Video in progress
The lock has expired, but the process that took it is still working. How do you handle this?
There are two directions: keep extending the lock while the work runs (the Redisson watchdog does this), and check a fencing token on the protected resource's side. The watchdog covers many cases, but with a long GC pause or a network cut only a fencing token gives real protection.
📖 Answer
Watchdog. In Redisson, if you call lock() without a leaseTime, it takes the lock for 30 seconds, and a background timer extends it by another 30 every 10 seconds. If the process dies, the extending stops and the lock releases itself.
RLock lock = redisson.getLock("lock:invoice:" + id);
lock.lock(); // the watchdog is on
try { generate(id); }
finally { lock.unlock(); }
If you give an explicit time with lock(10, SECONDS), the watchdog is turned off, which many people don't know.
But the watchdog runs inside the JVM too. With a 40-second stop-the-world pause, it stops as well, the lock expires, another process gets in, and the first process, waking up from the pause, keeps writing with no idea anything happened.
Fencing token. When the lock is acquired, you get an increasing number (for example, INCR lock:invoice:seq). You send this number along when writing to the resource, and the resource rejects an older one:
UPDATE invoice SET status = 'DONE', fence = :token
WHERE id = :id AND fence < :token;
If 0 rows are updated, there's a newer owner than you, and you stop the work.
In practice I treat a Redis lock as an optimization for "don't run twice", and correctness comes from a DB constraint, a version column, or an idempotent operation.
Sign up to mark studied questions and save your progress.