The Runtime Theory

Distributed Lock Acquisition: SET NX, Leases, Renewal, and Compare-and-Delete

Follow a distributed lock through atomic SET NX acquisition, lease expiry, renewal, and Lua compare-and-delete release — and why ownership tokens matter.

The Runtime Theory Team08 stages

trace / request.md

CLIENTGENERATES TOKENATOMIC ACQUIREEXACTLYONE WINNERTHE LOCKIS A LEASECRITICALSECTION RUNSLEASE RENEWALCOMPARE-AND-DELETELEASE EXPIRYFREES IT

readyThe client creates a unique lock token — a UUID or a monotonically increasing fencing number. The token identifies this specific acquisition for the lock's entire life.

A distributed lock is a key with an owner and a deadline. Acquisition is a single atomic SET NX — the check and the set happen in one operation, which is exactly what a naive get-then-set would get wrong. The token matters on the way out as much as the way in: releasing requires compare-and-delete, a Lua script that deletes only if the key still holds this client's token.

The TTL turns the lock into a lease, and leases are what keep dead owners from deadlocking the system — expiry is the machine's guarantee that progress happens even when nobody is alive to release. Renewal is the compensating contract: real work must outrun the TTL, and the renewal loop is how it does. The ordering — token, NX, lease, renew, compare-and-delete — exists because every step protects against a specific failure: lost ownership, stale release, dead holder. Skipping any of them turns a lock into a bug.