A lease says when ownership probably expires. A fencing token lets the protected resource reject a former owner that resumes after a pause.
Distributed Lease with Fencing
Lease expiry revokes ownership only when downstream writes reject stale owners.
-- Acquisition increments a monotonic token atomically.
UPDATE job_leases
SET owner_id = $2,
fencing_token = fencing_token + 1,
expires_at = now() + interval '30 seconds'
WHERE resource_id = $1 AND expires_at < now()
RETURNING fencing_token;
-- Every protected write rejects stale owners.
UPDATE protected_resources
SET value = $2, last_fencing_token = $3
WHERE id = $1 AND last_fencing_token < $3;
-- Zero rows: ownership is stale; stop immediately.Invariant: Only the holder of the greatest issued fencing token may commit protected work.
Use when: A paused worker must not commit after another worker acquires its expired lease.
Why this boundary matters
A paused owner can resume after its lease expires. Without a monotonic token at the write boundary, two owners can both mutate state.
Failure policy
| Boundary | Action |
|---|---|
| Lease acquired | Issue a token greater than every previous token |
| Lease renewed | Keep the token; extend only before expiry |
| Lease expires | Stop work and assume ownership is lost |
| Stale owner writes | Reject because its token is lower |
| Token store unavailable | Do not invent ownership locally |
| External API cannot enforce tokens | Use idempotent operations and reconciliation or another ownership mechanism |
Trade-offs
Fencing prevents stale owners from committing, but every protected write must compare tokens. A lease alone is only a timing belief. Systems that cannot enforce the token need a different correctness boundary.
Decision rule: Use a fenced lease for work that can outlive process pauses and whose destination can atomically reject stale tokens.
Further reference
Browse all engineering snippets · Study distributed systems papers