Video in progress

Only one of several instances should do the work (a scheduler, a leader). How do you build a distributed lock, and why do you need a fencing token?

The lock is taken through a DB, Redis or ZooKeeper/etcd, but because of a GC pause or a network partition, an "old owner" whose lock has expired may still be running. A fencing token is a number that increases every time a lock is acquired: the resource rejects a write that arrives with an old token.

📖 Answer

The simple case: a @Scheduled job runs on 3 instances and sends invoices every night. Without a lock, a customer gets three emails. A library like ShedLock solves this through a single row in the DB:

@Scheduled(cron = "0 0 2 * * *")
@SchedulerLock(name = "invoices", lockAtMostFor = "PT30M", lockAtLeastFor = "PT1M")
public void sendInvoices() { ... }

For many cases that is enough. But there is a dangerous scenario:

  1. Instance A takes the lock (for 30 minutes).
  2. A hits a long GC pause or gets cut off from the network, and "freezes" for 31 minutes.
  3. The lock expires, B takes the lock and starts the work.
  4. A wakes up, thinks it still holds the lock, and keeps writing.

Now two "leaders" are working at once. The lock service did its job correctly; the problem is that A doesn't know its lock has expired.

A fencing token. The lock service hands out a monotonically increasing number with every lock (A gets 33, B gets 34). Every write carries the token, and the resource (DB, storage) says "I've seen 34, so I reject anything that comes with 33":

UPDATE job_state SET data = ?, fence = 34
WHERE job = 'invoices' AND fence <= 34;

That is why the lock alone doesn't give you safety: the resource has to take part too. Redis's plain SET NX PX lock gives no token, and there is a lot of debate about Redlock too (Martin Kleppmann's analysis). When correctness matters, etcd or ZooKeeper (the revision/zxid as the token) or the DB itself (a version column, SELECT ... FOR UPDATE) are more reliable.

You should ask another question too: do you need a lock at all? Often making the work idempotent (a "sent exactly once" flag with a unique invoice_id for each invoice) is more reliable than a lock. A lock is for efficiency, idempotency is for correctness.