skip to content
jaeaeichsysdes

Distributed Locks & Fencing Tokens

Why TTL leases alone cannot guarantee mutual exclusion under GC pauses or network delays, and how monotonic fencing tokens enforced by storage prevent zombie writes.

On a single machine, a mutex is binary: either thread A holds it or thread B holds it. If the process crashes, the OS cleans up everything at once.

Across a network, machines crash independently and clocks drift. If Client A acquires a lock and then loses power, nobody else can ever proceed unless the lock expires automatically. So every distributed lock must be a time-bounded lease (a lock with a TTL).

That single necessity introduces a subtle trap that breaks most naive distributed locks in production.

Efficiency locks vs correctness locks

Before picking a lock implementation, separate two completely different goals:

  • Efficiency: you want to avoid repeating expensive work (sending the same digest email twice, or recomputing a cache entry simultaneously). If the lock fails occasionally, you waste a few CPU cycles or send a duplicate notification, not corrupt state.
  • Correctness: two concurrent writers will corrupt a file, double-book a seat, or double-spend a balance. Even a 1-in-10,000 overlap is unacceptable.

For efficiency, SET lock_key client_id NX PX 10000 in Redis is fast and practical (released via a Lua compare-and-delete script so a client never deletes someone else’s lock). For correctness, a TTL lease alone is never enough.

Why Redis SET NX EX fails under pauses

Suppose Client A acquires a 10-second lease on order:42, then pauses for 15 seconds. Why would a healthy process pause for 15 seconds?

  • A stop-the-world JVM / Go / Python garbage collection pause
  • A VM live migration or noisy-neighbor CPU stall
  • A packet delayed in a congested network switch

While Client A is frozen, its 10-second lease expires. The lock service grants the lock to Client B, which reads and writes safely to storage. Moments later, Client A unfreezes. From Client A’s perspective, it checked the lock before pausing and still holds it — so it fires its stale write and silently overwrites Client B.

Step through Martin Kleppmann’s zombie-writer failure below, then switch to fencing tokens to see how storage stops the stale write cold.

interactive · step through the GC pause, then toggle fencing tokens to block the zombie write

Zombie Client A resumes unaware its lease expired and sends its stale write (#33).

Client Atoken #33
woke up · sent stale write without knowing lease expired
Client Btoken #34
holds lease #34 · assumes its write is intact
Storage serviceno token check
Client A's STALE write (overwrote B!)
DATA CORRUPTION · storage blindly overwrote Client B's data

step 4/4 · CORRUPTED · lock holder: Client Btoggle fencing tokens to reject stale #33

The fix: monotonic fencing tokens

A lock service cannot reach into Client A’s CPU and stop a packet that is already in flight. The storage layer itself must reject stale writes.

Every time the lock service grants a lease, it attaches a strictly monotonic integer called a fencing token (33, 34, 35…). The client passes that token along with every write to the database or storage service:

token #33

Client A acquires lock, freezes in GC

token #34

Client B acquires lock, storage saves max = 34

33 < 34

Zombie A wakes up; storage rejects write

In SQL, the check is a single conditional update or version column:

UPDATE seats
SET owner = 'client_a', fence_token = 33
WHERE seat_id = '14A' AND fence_token < 33;

If rows_affected == 0, the zombie writer immediately knows it lost ownership and aborts without corrupting Client B’s state.

note

Notice the twist: if your database already supports conditional updates (WHERE version = expected or SELECT ... FOR UPDATE), you often do not need an external distributed lock at all — the database’s own row lock or optimistic concurrency control is the fencing mechanism.

Redis / Redlock vs consensus-backed locks

If you do need an external lock service that generates strictly monotonic fencing tokens, the lock service itself must survive node crashes without losing or resetting its counter:

Mechanism Fencing token? Fault model Best fit
Single Redis (SET NX PX) No (lost on failover) Async replication can lose lock on crash Efficiency locks, rate-limit dedup, cache stampede
Redlock (5 Redis nodes) No monotonic counter Relies on bounded wall-clock drift across nodes Best-effort efficiency without a single Redis SPOF
etcd / ZooKeeper / Chubby Yes (revision / zxid) Consensus quorum survives crashes cleanly Correctness locks, leader election, metadata leases
DB optimistic lock (version) Built-in per row Atomic inside the same database transaction Seat booking, inventory decrement, balance updates

Wait — why not just renew the lease in a background thread (“watchdog”)? A watchdog helps long-running jobs avoid expiring early, but it does not eliminate the hazard: if the whole process freezes in GC or a network partition delays packets, the watchdog freezes too. Only storage-side fencing makes correctness independent of process timing.

Where this shows up in system design

  • Ticketmaster seat bookingTemporary seat holds use a lease TTL so abandoned carts release seats, backed by a DB version/fencing check at checkout.
  • Cron job leader electionAn etcd or ZooKeeper lease elects one active scheduler; workers include the lease revision as a fencing token when writing job state.
  • Inventory reservationHigh-contention flash sales avoid Redis-only locks in favor of atomic DB conditional updates (`stock >= qty AND version = v`).
  • Distributed file systems (Chubby / GFS / HDFS)Master leases carry monotonic generation numbers so a partitioned old master cannot issue stale chunk mutations.

Check yourself: system design scenarios

interactive · pick the right locking strategy for each scenario

1. Nightly billing ledger settlement

correctness-critical · external object store · GC pauses possible

A batch worker locks an account, computes interest, and overwrites the account balance in object storage. A double write would corrupt customer balances.

2. Preventing duplicate cache warmups

efficiency-only · low ops overhead · occasional overlap ok

Every 5 minutes, 20 app servers wake up to recompute a heavy analytics dashboard cache in Redis. Running it twice occasionally wastes 2 seconds of CPU but hurts nothing.

3. Concert ticket checkout on PostgreSQL

single relational DB · zero double-booking · simple architecture

Two users click 'Pay' on seat 14A at the exact same millisecond. Both checkout requests hit your PostgreSQL database.

esc
⌘B sidebar[ ] prev/next1–5 flowsc copyt theme