Video in progress

Strong Middle 🏗️ System design

What are the risks of a distributed lock built on Redis, and why do you need a fencing token?

The lock is taken with a TTL; if the owner freezes for longer than the TTL because of a GC pause or the network, the lock passes to someone else and two processes work at the same time, both believing "I'm the owner". A fencing token is an increasing number issued with each lock; the resource rejects writes with an older number.

📖 Answer

A simple implementation:

String token = UUID.randomUUID().toString();
Boolean ok = redis.opsForValue()
        .setIfAbsent("lock:invoice:42", token, Duration.ofSeconds(30));

On release, delete only your own lock — with a Lua script doing "is the value mine, and if so delete" in one step. Otherwise you delete someone else's lock.

The main risk is about timing:

  1. A took the lock (30 s).
  2. A hits a 40-second GC pause or a slow disk.
  3. The lock expired, B took it and started working.
  4. A woke up and kept writing, believing "I have the lock".

Now both are writing at the same time. Having A check the lock itself doesn't help — when A checked, the lock really was its own, and then the pause happened.

Fencing token: every time a lock is taken, an increasing number is issued (for example INCR in Redis or a DB sequence). A gets 33, B gets 34. The resource (the DB) checks the number on every write:

UPDATE invoices SET status = 'SENT', fence = 34
WHERE id = 42 AND fence < 34;

If A comes with 33, the write doesn't go through.

In practice:

  • if the lock is only for efficiency (not doing one job twice) and an occasional duplicate does no harm, a plain Redis lock is enough;
  • if it's needed for correctness (money, a unique resource), use protection at the DB level — a unique constraint, SELECT ... FOR UPDATE, an optimistic version — or a lease and fencing in etcd/ZooKeeper;
  • Redisson's watchdog extends the lock automatically, but it gives no guarantee against a long GC pause either.