← all labs

Distributed Lock with Fencing Tokens

A distributed lock lets only one worker process a shared resource at a time. The usual implementation: SET key value NX PX ttl in Redis — whoever sets the key first holds the lock until the TTL expires.

The problem: a plain TTL lock isn't actually safe. If a worker pauses for longer than the TTL — a GC pause, a slow network call, a scheduler delay — its lock silently expires while it's still "holding" it in its own mind. Another worker acquires the lock and starts working. When the first worker wakes up, it has no idea its lock is gone, and may still write to the resource — corrupting it.

The fix: fencing tokens. Every time the lock is acquired, a monotonically increasing token is issued alongside it. The resource being protected only accepts a write if its token is the highest one it has seen. A stale worker's write is rejected even after its lock has expired and moved on to someone else — the token, not the lock itself, is what actually protects the resource.

lock holder

—

current fencing token

0

last committed token

—

event timeline

No events yet — click "Run the race" to start.

    Backend: Next.js API routes + Upstash Redis. Source: github.com/vaibhav-mahalle/labs