When traffic spikes expose hidden coupling, pair CP consensus locks (etcd/ZooKeeper `zxid` or Raft term+index) with monotonically increasing fencing tokens validated by downstream storage (`WHERE token > last_seen_token`).
TL;DR30-second simplified summary▾
Core Mechanics: Distributed workers use locks to serialize payments, sequence generation, and storage mutations (50,000 active locks, 10,000 ops/sec, < 5 ms SLA).
Visual & Structural Flow: Depicts 35s GC Pause Zombie Write Blocked by Monotonic Fencing Token (Worker 1 (GC) -> Raft Lock Mgr -> Worker 2 -> Storage (Token Check)); CP Lock Lease + Monotonic Token Validation at Storage (etcd / ZooKeeper -> Lease Watchdog -> Worker RPC -> Storage Guard).
Trade-Offs & Production: Running SETNX without a unique owner UUID lets an expired worker DEL another worker's lock. Fencing tokens are standard whenever distributed locks guard stateful storage: Leader-Elected Partition Writers (Kafka / Storage Engines): Brokers and shard leaders attach.
Failure Modes & Application: Fencing tokens are standard whenever distributed locks guard stateful storage: Leader-Elected Partition Writers (Kafka / Storage Engines): Brokers and shard leaders attach epoch/term numbers to every write so deposed zombies cannot corrupt segments.
Why distributed locks fail silently under GC pauses.
Why this matters: The mechanism: understand how Why distributed locks fail silently under GC pauses works from first principles.
Think of Why distributed locks fail silently under GC pauses as the intuition layer for Design a Distributed Lock with Fencing Tokens: The mechanism: understand how Why distributed locks fail silently under GC pauses works from first principles.
Distributed workers use locks to serialize payments, sequence generation, and storage mutations (50,000 active locks, 10,000 ops/sec, < 5 ms SLA). Unlike a single-process mutex, a distributed lock must use a lease TTL so crashed workers do not deadlock the cluster forever—and that very TTL creates a subtle split-brain window if a paused worker wakes up after its lease expires.
GC-pause zombie writes, master-failover double locks, and release hijacks.
Why this matters: The problem: see what breaks without GC-pause zombie writes, master-failover double locks, and release hijacks under real concurrency or scale.
Three failure modes corrupt shared state:
- 35 s GC Pause Split-Brain: Worker 1 acquires a 30 s lock, freezes in STW GC for 35 s, Worker 2 acquires the expired lock and writes, then Worker 1 wakes up and overwrites Worker 2's state.
- Async Master Failover: On Redis primary-replica async failover, a newly promoted replica may lack the lock key and grant a duplicate lock.
- Client Release Hijack: Worker 1 wakes up and runs
DEL lock_key, deleting Worker 2's active lock.
35s GC Pause Zombie Write Blocked by Monotonic Fencing Token
Downstream storage validates monotonic fencing tokens, rejecting Worker 1's delayed write after Worker 2 commits token 35.
- Problem
- How to implement Design a Distributed Lock with Fencing Tokens without hitting unbounded tail latency, state divergence, or operational fragility.
- Naive Solution
- Use a single unpartitioned path with unbounded retries and synchronous global coordination.
- Why It Fails
- Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
- Alternatives
- Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
- Engineering Decision
- When traffic spikes expose hidden coupling, pair CP consensus locks (etcd/ZooKeeper
zxidor Raft term+index) with monotonically increasing fencing tokens validated by downstream storage (WHERE token > last_seen_token). - Trade-Offs
- Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
When Design a Distributed Lock with Fencing Tokens experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?
Naive `SETNX` + `DEL` and unsafe Redlock clock assumptions.
Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
Think of Naive SETNX + DEL and unsafe Redlock clock assumptions as the intuition layer for Design a Distributed Lock with Fencing Tokens: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
Running SETNX without a unique owner UUID lets an expired worker DEL another worker's lock. Even with atomic Lua release, an async-replicated Redis master loses locks on crash, and Redlock's reliance on synchronized physical wall clocks fails if NTP jumps or VM clocks drift.
Naive `SETNX` + `DEL` and unsafe Redlock clock assumptions
Enterprise solution: CP Consensus Leases + Monotonic Fencing Tokens.
Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.
Use a CP consensus store (etcd Raft revision or ZooKeeper ephemeral znodes with zxid) for safety, or Redis atomic Lua + external sequencer when AP speed is paired with storage fencing:
- Monotonic Fencing Token: Every lock grant returns a strictly increasing integer (
34,35, ...). Storage enforcesUPDATE ... WHERE last_fencing_token < :token(rejecting delayed writes from paused workers). - Safe Release & Watchdog Renewal: Store a unique UUID owner token; release only via atomic compare-and-delete Lua/CAS, and renew leases via a background heartbeat that aborts work if renewal fails.
CP Lock Lease + Monotonic Token Validation at Storage
Safety is enforced at the storage engine itself via monotonic fencing tokens, neutralizing GC pauses and clock jumps.
-- Atomic Redis Lock Acquisition (30s TTL) + Safe UUID Release
-- Acquire: SET resource_name <uuid_owner> NX PX 30000
-- Release (prevents deleting another worker's lock):
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
else
return 0
end
-- Downstream PostgreSQL fencing check (mandatory for true safety)
UPDATE ledger_accounts
SET balance = :new_balance, last_fencing_token = :token
WHERE account_id = :id AND last_fencing_token < :token;
Where fenced distributed locks are used in production.
Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
Fencing tokens are standard whenever distributed locks guard stateful storage:
- Leader-Elected Partition Writers (Kafka / Storage Engines): Brokers and shard leaders attach epoch/term numbers to every write so deposed zombies cannot corrupt segments.
- Distributed Cron & Payment Orchestrators: Kubernetes
Leaseobjects and etcd locks guard singleton reconciliation jobs.
Practice: Make the trade-off yourself.
Why can a distributed lock *without* a downstream fencing token never guarantee mutual exclusion on writes?