Fenced Distributed Lease

A lease says when ownership probably expires. A fencing token lets the protected resource reject a former owner that resumes after a pause.

Distributed systems · SQL

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

BoundaryAction
Lease acquiredIssue a token greater than every previous token
Lease renewedKeep the token; extend only before expiry
Lease expiresStop work and assume ownership is lost
Stale owner writesReject because its token is lower
Token store unavailableDo not invent ownership locally
External API cannot enforce tokensUse 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

>