Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Design a Distributed Lock
with Fencing Tokens.

A TTL-based distributed lock alone cannot prevent split-brain writes when a lock holder freezes in a 35-second GC pause after its 30-second lease expires.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

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.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Distributed Locking & Redlock Algorithm
Distributed locking coordinates mutually exclusive access to a shared resource across independent processes that share no memory, using a network-accessible lease store such as Redis, etcd, or ZooKeeper.
Split-Brain Prevention
Split-brain happens when a network partition splits a distributed cluster into isolated groups that both elect a primary and accept conflicting writes; preventing it requires strict majority quorums (N/2 + 1), time-bounded leases, and monotonic fencing tokens.
Consistency & Consensus Replication (Raft / Paxos)
Fault-tolerant replication protocols (Raft, Multi-Paxos, Quorum) that keep distributed state consistent across node crashes and network partitions using majority quorums (2f+1) and monotonic term numbers.
Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

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.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

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:

  1. 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.
  2. Async Master Failover: On Redis primary-replica async failover, a newly promoted replica may lack the lock key and grant a duplicate lock.
  3. Client Release Hijack: Worker 1 wakes up and runs DEL lock_key, deleting Worker 2's active lock.
Fencing Token Protection

35s GC Pause Zombie Write Blocked by Monotonic Fencing Token

Worker 1 (GC)Raft Lock MgrWorker 2Storage (TokenCheck)1. Acquire -> lease 30s, token=342. 35s JVM STW GC pause (lease expires!)3. Acquire -> token=35 -> writesto DB4. Delayed write (token=34 < 35)-> REJECTED!

Downstream storage validates monotonic fencing tokens, rejecting Worker 1's delayed write after Worker 2 commits token 35.

Engineering Decision Framework
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 zxid or 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.
Decision Exercise · Make the Call

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?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

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.

Request & State Flow

Naive `SETNX` + `DEL` and unsafe Redlock clock assumptions

Client TxPlanner / Lock MgrWAL / MemTableHeap / SSTable1. Acquire snapshot / index plan2. Append redo record + fsync WAL3. Flush dirty pages / compactSSTables4. Commit & release row locks
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

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 enforces UPDATE ... 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.
Storage-Enforced Fencing

CP Lock Lease + Monotonic Token Validation at Storage

etcd / ZooKeeperCP quorum, monotonic zxid/revLease WatchdogUUID owner + heartbeat renewWorker RPCAttaches…Storage GuardRejects token <= 34…

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;
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

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 Lease objects and etcd locks guard singleton reconciliation jobs.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why can a distributed lock *without* a downstream fencing token never guarantee mutual exclusion on writes?

Recommended Learning Flow