Distributed locks and fencing tokens
A distributed lock is really a lease that expires, so a paused holder can outlive it; for correctness, take the lease from a consensus store or database and have storage reject stale fencing tokens.
Analogy: A hotel key card works until checkout. When the next guest checks in, their new card tells the door to reject every older card, even if you overslept and are still inside.
How it works
- A GC pause, VM migration or slow disk can outlast the TTL; the old holder wakes and still writes.
- Fencing tokens: each grant returns a growing number, and storage rejects writes carrying an older one.
- Efficiency lock: one Redis
SET NX PXis fine. Correctness lock: etcd, ZooKeeper or the database, plus fencing. - Often the best lock is none: a conditional write on the resource itself.
Check yourself
Answer to mark it learned; your answers aren't scored.
A nightly job takes a Redis lock (SET NX PX 30000) before rewriting a customer ledger. After an incident you find two workers wrote the same ledger; one had a 45 s GC pause. Which change actually prevents the corruption?
Go deeper
Full explanation
A distributed lock lets one process at a time act on a shared resource across machines. The holder can crash, so every real lock is a lease: it expires after a TTL unless renewed.
That creates the core problem. A holder can pause (GC, VM migration, a slow disk) longer than the TTL, lose the lease without knowing, then wake up and write while a new holder also writes. No lock service can prevent this on its own.
Fencing tokens fix it: every grant returns a number that only grows (etcd revision, ZooKeeper zxid, a database counter; Chubby calls them sequencers). Each write carries the token, and the storage rejects anything older than the highest it has seen.
First ask what the lock protects (Kleppmann's split):
- Efficiency, where a rare double run only wastes work: one Redis
SET key value NX PX 30000is fine. - Correctness, where a double run corrupts data: a lease from etcd, ZooKeeper or the database, plus fencing. Redlock depends on timing assumptions and issues no tokens.
Often the best lock is none: a conditional write on the resource itself (Idempotency).
Code A Postgres lease with a fencing token checked by storage
import psycopg
# One row per lock. The token grows on every new holder: it is the fencing token.
ACQUIRE = """
INSERT INTO leases (name, holder, token, expires_at)
VALUES (%(name)s, %(me)s, 1, now() + interval '30 seconds')
ON CONFLICT (name) DO UPDATE
SET holder = EXCLUDED.holder, token = leases.token + 1,
expires_at = EXCLUDED.expires_at
WHERE leases.expires_at < now() -- only take over an expired lease
RETURNING token
"""
# The resource enforces the fence: a writer with an older token changes nothing.
FENCED_WRITE = """
UPDATE invoices SET status = %(status)s, fence = %(token)s
WHERE id = %(id)s AND fence <= %(token)s
"""
def acquire(conn: psycopg.Connection, name: str, me: str) -> int | None:
row = conn.execute(ACQUIRE, {"name": name, "me": me}).fetchone()
return row[0] if row else None # None: someone holds a live lease
def mark_paid(conn: psycopg.Connection, invoice_id: int, token: int) -> bool:
cur = conn.execute(FENCED_WRITE, {"id": invoice_id, "status": "paid", "token": token})
return cur.rowcount == 1 # 0 rows: we were fenced off, stop working
# Expiry is judged by one clock, the database's, not by each client's.
conn = psycopg.connect(DSN, autocommit=True)Real example
A billing job runs on 3 pods and uses a Redis SET NX PX 30000 lock so only one sends invoice batches. One night a pod stalls 40 s in a GC pause mid-batch. The key expires, a second pod takes the lock and sends the same batch, then the first pod wakes and finishes: customers get two emails and two charges. Duplicate emails are an efficiency problem; double charges are a correctness one. Fix: a database lease with a fencing token checked on each invoice row, plus an idempotency key on the payment call.
Trade-offs +3 · −3
+ You gain
- Simple model for singleton work: one cron run, one leader, one migration at a time.
- With fencing, stays safe under pauses, clock jumps and network delays.
- Leases self-heal: a crashed holder's lock frees itself after the TTL.
− You pay
- The TTL is a trade-off: short leases flap under load, long ones stall work after a crash.
- Fencing needs the protected resource to check tokens, which many external APIs can't do.
- The lock service becomes a critical dependency, and each consensus write costs a quorum round trip.
Use it when
Singleton work (cron, leader, schema migration, index rebuild) or serializing access to a resource that can't do conditional writes itself. For correctness, always with fencing.
Avoid it when
When the resource supports conditional writes, unique constraints or transactions, use those directly. Never rely on Redis or Redlock alone to guard money or data integrity.
Numbers to know 4
- Redis lock:
SET key random NX PX 30000; release only if the value still matches (Lua script, orDELEXin Redis 8.4+). - Redlock: N = 5 independent Redis masters, a majority of 3 needed; ~5–50 ms per-node timeout for a 10 s lease.
- Kleppmann (2016): GC pauses have lasted minutes, and one GitHub incident delayed packets ~90 s, far past typical TTLs.
- Redis expires keys by wall clock, not a monotonic clock, so a clock jump can free a lock early.
Common pitfalls 3
- Releasing with plain
DEL: after your lease expired, you delete the next holder's lock. Compare the value first. - Skipping fencing because the lock is Redlock or etcd: the paused client still writes.
- Checking 'do I still hold the lock?' right before writing: the pause can hit right after the check.
Interview questions 2
Answer out loud first, then reveal.
Is Redlock safe for a payment workflow?Show answer
No. Its safety assumes bounded pauses, network delays and clock drift. A GC pause on a client, or a clock jump on a Redis node, can let two clients both believe they hold the lock, and Redlock issues no fencing token to catch it. For payments I'd avoid a lock entirely: a conditional write or unique constraint, plus idempotency keys. If I truly need mutual exclusion, I take a lease from etcd or ZooKeeper and fence every write.
How do you choose the lease TTL?Show answer
It's availability versus overlap. After a crash, work stalls for up to one TTL, so long leases hurt recovery. Short leases expire during ordinary GC pauses or network blips and cause flapping. I renew at a fraction of the TTL, say every 3 s for a 10 s lease, stop working as soon as a renewal fails, and still fence writes, because no TTL bounds how long a process can pause.