SysDesignAtlas

Distributed Locks & Leases

Why a lock in a distributed system is never as safe as it looks, why fencing tokens are mandatory, and the designs that avoid needing a lock at all.

HLDHard11 min readlocksleasescoordinationfencing
Confidence

#What you're actually asking for

A distributed lock lets one process among many claim exclusive access to a resource — process one job, write one file, run one cron task.

The naive implementation looks trivial:

   SET lock:job42 <owner_id> NX EX 30     ← acquire, 30s expiry
   ... do the work ...
   DEL lock:job42                         ← release

NX means "only set this if nobody else already has," so exactly one caller can win even if a thousand try at once. EX 30 puts a 30-second expiry on it — a lease rather than a lock — so if the holder crashes, the lock doesn't stay held forever and block everyone.

That expiry is also the source of every problem below. A lock that can time out is a lock you might not still hold while you think you do.

So this design is fine for efficiency — stopping duplicate work that would merely waste effort. It is not sufficient for correctness — stopping two writers from corrupting each other. That distinction is the entire subject.

#Why locks aren't safe

The failure is not exotic. It's a garbage collection (GC) pause — in languages like Java or Go, the runtime periodically freezes your whole program while it reclaims unused memory. Usually that takes milliseconds; occasionally, on a big heap, it takes many seconds.

   t=0    Client A acquires lock, TTL 30s
   t=1    Client A begins work
   t=2    Client A hits a 40-SECOND GC PAUSE (or VM migration,
          or network partition, or a slow disk)
   t=31   Lock EXPIRES. A is frozen and doesn't know.
   t=32   Client B acquires the lock — legitimately, it's free
   t=33   Client B starts writing
   t=42   Client A wakes up, believes it still holds the lock,
          and writes.
          ► TWO WRITERS. Data corrupted.

No lock service can prevent this, because the client cannot know whether its lease is still valid at the moment it acts. Time passes between checking and acting, and in that window anything can happen. This is a fundamental property of distributed systems, not a bug in Redis or ZooKeeper.

#Fencing tokens

The actual fix, and it requires cooperation from the resource, not just the lock service.

Every time the lock is handed out, it comes with a number one higher than last time. Whatever you're writing to remembers the highest number it has seen and refuses anything with a lower one. A stale holder can still try to write — it just can't succeed.

   A acquires lock  → token 33
   A pauses...
   Lock expires; B acquires → token 34
   B writes with token 34   → storage records max_token = 34  ✓
   A wakes, writes token 33 → storage sees 33 < 34, REJECTS  ✓

Now safety doesn't depend on timing at all. A stale holder is structurally unable to do damage, regardless of how long it was paused.

The catch, and it's why fencing is rare in practice: the storage system must support it. If you're writing to S3 or a database that doesn't check tokens, you can't fence. Workarounds:

  • A conditional write. Store the last token in a column and make the write conditional: UPDATE ... SET data = ?, token = 34 WHERE id = ? AND token < 34. A stale holder's update matches zero rows. Most databases support this.
  • A uniqueness constraint that includes the token, so a second write for the same token fails.

When neither is possible, accept that you have an efficiency lock and design so duplicates are harmless.

Note this is the same mechanism used to prevent split brain during failover — the concept generalizes to "make stale actors detectable rather than trying to prevent them."

#Implementations

#Redis single instance

SET key value NX EX ttl, released with a Lua script that checks ownership before deleting:

   if redis.call("GET", KEYS[1]) == ARGV[1] then
       return redis.call("DEL", KEYS[1])
   end

The ownership check matters: without it, a client whose lock already expired could delete the next holder's lock. This is a real bug people ship.

Fast (sub-millisecond) and simple. But Redis replication is asynchronous, so if the primary acknowledges a lock and dies before replicating, the promoted replica has no record of it and will grant the same lock to someone else. Redis-based locks are efficiency locks by construction.

#Redlock

An algorithm that acquires the lock on a majority of N independent Redis instances. It's more robust against single-node failure, and it remains controversial. Its safety assumes that clocks on different machines don't drift apart by much, and that a client is never paused for long — and distributed systems guarantee neither. So it makes failures rarer than a single Redis does, but it's still an efficiency lock: not safe for correctness without fencing.

#ZooKeeper / etcd

Locks built on consensus (Raft/ZAB), which makes the lock state itself linearizable and durable.

The standard pattern uses ephemeral sequential nodes (a node is ZooKeeper's word for a stored key):

  • Sequential: each client wanting the lock creates a node, and ZooKeeper stamps it with an ever-increasing number — lock-0001, lock-0002, … The client with the lowest number holds the lock; the rest form a queue.
  • Watch only your predecessor: each waiting client asks to be notified when the node just ahead of it disappears. If every client watched the lock holder instead, each release would wake all waiters at once to fight over it (a thundering herd), when only one can win.
  • Ephemeral: the node is tied to the client's session, so it vanishes automatically when the client dies or loses its connection. That releases the lock without you having to guess a TTL.

Stronger and slower (consensus round trips, typically ~10 ms). The real reason to prefer etcd: every write gets a global revision number that only ever increases, so the revision at which you acquired the lock is a fencing token, ready to use.

#Database locks

Postgres advisory locks (named locks that the database holds for you, not attached to any row — pg_advisory_lock(42)), or a SELECT ... FOR UPDATE row lock. If your data is already in one database, this is often the correct answer. The lock and the data share a transaction: the lock is held until the transaction commits, and if your connection dies, the transaction rolls back and none of your writes happen. So the whole category of "my lease expired between checking and writing" disappears.

Underrated. When someone proposes ZooKeeper for coordinating work whose state lives in Postgres anyway, "we can just use a row lock in the same transaction" is usually the simpler and safer answer.

#Leases

A lock with a TTL is really a lease — time-bounded ownership that must be renewed. The framing is more honest, because it forces the question every distributed lock design must answer: what happens when renewal fails?

Good lease design:

  • Renew well before expiry (at ~1/3 of the TTL) so a transient blip doesn't lose ownership.
  • Stop work immediately when renewal fails. The holder should self-fence: if you couldn't renew, assume you no longer own it and abort, rather than finishing and writing.
  • Pick the TTL as a real tradeoff. Short TTL → fast recovery after a crash, but more renewal traffic, and a healthy holder that's merely slow under load is more likely to miss a renewal and lose the lock for no good reason. Long TTL → fewer renewals, but a crashed holder blocks the resource for the full duration.

Leases underpin leader election: the leader holds a lease and renews it; failing to renew means stepping down.

#Designing the lock away

The best answer is often that you don't need one. Volunteering an alternative is a stronger move than implementing a lock well.

1. Make the operation idempotent. If processing a job twice produces the same result, duplicates are harmless and you can drop the lock entirely. See Idempotency.

2. Use optimistic concurrency. Instead of locking, read a version, and make the write conditional on the version being unchanged:

sql
UPDATE accounts SET balance = 90, version = version + 1
WHERE id = 42 AND version = 7;      -- 0 rows updated → retry

No lock, no lease, no timing assumption — and it's naturally fenced. Excellent under low contention, degrades under high contention (retry storms).

3. Partition ownership. Assign each key to exactly one worker by consistent hashing. Job 42 always goes to worker 3, so no other worker ever sees it — there's nothing to compete over and nothing to lock. Exclusivity comes from where work is sent, not from workers asking a lock service at runtime. This is how Kafka consumer groups avoid needing locks at all — each partition is assigned to exactly one consumer in the group.

4. Use a single-threaded serialization point. Route all operations on an entity through one queue partition, or one actor (an object that processes its incoming messages strictly one at a time). Operations on that entity then happen one after another by design, so two can never overlap.

5. Push it into the database. A unique constraint prevents duplicate bookings more reliably than any lock: let the second insert fail.

#The decision

RequirementApproach
Avoid duplicate work; duplicates are wasteful onlyRedis lock — simple and fast
Duplicates would corrupt dataFencing tokens + conditional writes, or design the lock away
Data is already in one databaseDatabase transaction / advisory lock
Leader election, config, membershipetcd / ZooKeeper (consensus)
Low-contention updates to one rowOptimistic concurrency (version check)
Per-entity serialization at scalePartition ownership by hash

The sentence to carry into an interview: "A distributed lock is a performance optimization, not a safety mechanism. If correctness depends on it, I need fencing at the resource — or a design that doesn't need mutual exclusion at all."

#Check yourself

A lock for efficiency versus a lock for correctness: what's the difference?Show answer
Efficiency locks only stop wasted duplicate work, so an occasional failure is harmless. Correctness locks prevent corruption — and no lease-based lock can guarantee that on its own.
Walk through how a GC pause breaks a lease-based lock.Show answer
A holds a 30 s lease and freezes for 40 s; the lease expires and B legitimately acquires it; A wakes still believing it holds the lock and writes too. The client can't know its lease is valid at the moment it acts.
How do fencing tokens make a stale lock holder harmless?Show answer
Each grant comes with a number one higher than the last, and storage rejects writes with a lower number than it has seen. A paused holder's write is refused however long it slept — but the storage must support the check.
Why must releasing a Redis lock check ownership first?Show answer
Otherwise a client whose lock already expired can delete the next holder's lock. Release with a Lua script that deletes only if the value is still your owner ID.
Why are Redis locks efficiency locks by nature?Show answer
Replication is asynchronous: the primary can grant a lock and die before replicating it, and the promoted replica will grant the same lock again.
Why prefer etcd or ZooKeeper for coordination locks?Show answer
Lock state goes through consensus, so it's linearizable and durable; ephemeral nodes vanish with the client's session; and etcd's revision numbers serve as fencing tokens.
What does good lease handling look like?Show answer
Renew at about a third of the TTL, stop work immediately if renewal fails (assume you lost it), and choose the TTL by trading recovery speed against renewal load.
Name four ways to design the lock away.Show answer
Make the operation idempotent; use optimistic concurrency with a version check; give each key exactly one owner by hashing (like Kafka partitions); route each entity through one queue partition; or let a unique constraint reject duplicates.

#What to carry forward

  • A distributed lock is a performance optimisation, not a safety mechanism.
  • Pauses and partitions mean a client can't know its lease is still valid when it acts.
  • For correctness, fence at the resource: storage rejects stale tokens, or use conditional writes.
  • Redis locks are fast efficiency locks; etcd/ZooKeeper give consensus-backed locks with fencing; a database row lock is often simplest.
  • Better still, design the need away: idempotency, optimistic concurrency, partitioned ownership, unique constraints.
00:00
/ 11m