Course contents

08. Distributed Systems Lesson 9 of 10

Distributed Locks

Acquire and release locks with leases, see a paused client write after its lock expired, stop it with fencing tokens, and weigh the Redlock debate.

14 minAdvanced7 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A distributed lock serialises a critical section across processes; it is used either for efficiency or for correctness.
  • Acquire atomically with a unique owner value and a TTL; release only if you still own the lock.
  • The TTL is required because holders crash, so every distributed lock is a lease that can expire under a slow or paused holder.
  • A paused client cannot reliably know its lease expired and may write after another client took over.
  • Fencing tokens from a consensus-backed lock service, checked by the resource, make stale holders harmless.
  • Redlock takes a majority of independent Redis nodes; its safety for correctness rests on timing assumptions that are debated.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A distributed lock gives one process at a time, anywhere in a cluster, the right to do something: modify a record, process a file, run a migration. It is stored in a shared service (Redis, etcd, ZooKeeper, Consul, a database) that every process can reach. Because the holder can crash, the lock always comes with an expiry, which makes it a lease: the right to act for a limited time.

Why it exists

Concurrent read-modify-write cycles lose updates: two processes read the same value, both change it, and the second write erases the first. Inside one process a mutex prevents that; across machines you need a lock everyone agrees on. Locks are used for two different purposes, and the distinction drives every design choice:

  • Efficiency: avoid doing the same work twice (sending the same report, recomputing the same cache entry). An occasional overlap costs a little extra work.
  • Correctness: an overlap corrupts data or double-charges a customer. The lock must hold under crashes, pauses and partitions.

How it works

Acquire. The client atomically creates the lock key only if it does not exist, with a value unique to this attempt and a TTL. In Redis: SET resource_lock <random-id> NX PX 30000. In etcd: a transaction that creates the key under a lease if its create revision is 0 (the concurrency.Mutex helper does this). In ZooKeeper: an ephemeral sequential znode; the lowest sequence number holds the lock.

Release. Delete the key only if its value is still yours, atomically. In Redis this is a short Lua script (if get == my-id then del). Without the check, a client whose lock already expired would delete the next holder's lock.

Expiry. If the holder crashes, the TTL frees the lock. Long-running work must extend the lease before it runs out (a watchdog thread, etcd keep-alives, ZooKeeper session heartbeats).

The pause problem. A lease can expire while its holder is still running but not making progress: a stop-the-world garbage collection, a VM paused for live migration, a process swapped out, or a write stuck in a network queue. When the holder resumes, it believes it still holds the lock and writes. Checking the lock right before writing does not help, because the pause can fall between the check and the write. Martin Kleppmann's 2016 essay "How to do distributed locking" uses exactly this example.

Fencing tokens. The lock service returns a number that increases with every grant. The client includes it in every operation on the protected resource, and the resource rejects any operation whose token is lower than the highest it has accepted. A holder whose lease expired carries an old token and is turned away, however late its write arrives. Consensus-backed services provide such numbers naturally (etcd revisions, ZooKeeper zxids or znode versions). The resource has to cooperate: a conditional update (UPDATE … SET …, fence = :t WHERE id = :id AND fence < :t), a version column, or an object-store precondition.

Redlock. Redis's algorithm for a lock that survives the failure of Redis nodes uses N independent masters (typically 5). The client records the start time, tries to set the key on each node in turn with a short per-node timeout, and holds the lock if it succeeded on a majority and the elapsed time is less than the TTL. The lock is then valid for the TTL minus the elapsed time minus a clock-drift allowance (the reference implementation uses 1% of the TTL plus 2 ms). On failure it releases the key on all nodes.

The Redlock debate. Kleppmann argued that Redlock's safety depends on bounded network delay, bounded pauses and bounded clock drift; that a clock jump on a Redis node can expire a key early; and that it does not produce fencing tokens, because independent nodes cannot generate one monotonic counter. Salvatore Sanfilippo (antirez), Redis's author, replied in "Is Redlock safe?" that these timing assumptions are reasonable in practice, that the algorithm checks elapsed time after acquisition, that Redis should use monotonic time for expiry, and that a pause after acquisition affects every auto-releasing lock, which a unique value combined with check-and-set on the resource can address. Both agree that pauses exist; they disagree on how much to rely on timing.

When to use it

  • Preventing duplicate work across instances (efficiency): a single Redis lock is usually enough, and Redlock adds tolerance of Redis node failures.
  • Protecting a resource from concurrent modification (correctness): use a consensus-backed lock service and fencing tokens the resource checks.
  • Short critical sections around external systems that cannot do transactions themselves, again with fencing if correctness matters.

When not to

  • When the database can enforce the rule itself: a transaction, SELECT … FOR UPDATE, a unique constraint or an optimistic version check is simpler and safer.
  • When the operation can be made idempotent: process it as many times as you like and let deduplication handle overlaps.
  • When work can be partitioned so that each item has one owner (a queue, consistent hashing) and nobody needs to lock.
  • Do not use a lock to hide a missing transaction or a race in your own data model.

Trade-offs

Choice You gain You pay
Single Redis node Very fast, simple Lock lost if the node fails over (async replication); no fencing token
Redlock (5 Redis masters) Survives minority node failures More round trips; safety depends on timing assumptions; no fencing token
etcd / ZooKeeper / Consul lock Consensus-backed; monotonic tokens for fencing Slower (a consensus write per acquire); another critical cluster
Database row or advisory lock Uses infrastructure you already run; transactional Couples locking load to your primary database; session-scoped locks vanish on connection loss
Short TTL Fast recovery after holder crashes More renewals; leases expire under slow-but-alive holders
Long TTL Fewer spurious expiries Long waits after a holder crashes

Alternatives

  • Optimistic concurrency: read a version, write with WHERE version = :v, retry on conflict. No lock service at all.
  • Database transactions and row locks when all the data lives in one database.
  • Single-owner partitioning: route all work for a key to one consumer (Kafka partitions, consistent hashing) so no two workers touch the same key.
  • Idempotency keys: let duplicates happen and make them harmless.
  • Leader election when one process should own a whole job rather than lock individual resources.

Failure modes

  • Expired lease, live holder: GC pauses, VM freezes, slow I/O or clock jumps let a former holder act after someone else acquired the lock. Only fencing at the resource prevents damage.
  • Releasing someone else's lock with an unconditional delete after your own lease expired.
  • Lock lost on failover: a Redis primary acknowledges a lock, crashes before replicating it, and the promoted replica grants it again.
  • Lock service outage: nobody can acquire; design for a fallback or for the work to wait safely.
  • Forgotten renewals: a long task outlives its TTL because the watchdog thread was blocked by the task itself.

In production

Decide first whether the lock is for efficiency or correctness and say so in the code. For efficiency, a Redis lock with a unique value, a TTL several times the expected work time and a compare-and-delete release is common. For correctness, use etcd, ZooKeeper (Apache Curator's InterProcessMutex) or Consul, pass the fencing token to every write, and make the resource check it; combine with idempotency so retries are safe. Measure how long work takes compared with the TTL, alert on lock wait times, and test by pausing a holder (kill -STOP) past its TTL.

Common misconceptions

  • "If I check that I still hold the lock just before writing, I am safe." A pause or network delay after the check breaks it.
  • "Redlock is unsafe" or "Redlock is safe": its safety depends on timing assumptions; whether they are acceptable depends on what a violation costs you.
  • "A lock without a TTL is safer." It deadlocks the system the first time a holder crashes.
  • "The lock service protects the data." It only tells clients who should act; the data is protected only if the resource checks a token.

Interview angle

When a design needs mutual exclusion, first ask whether a transaction, a unique constraint, optimistic versioning or single-owner partitioning removes the need. If a distributed lock is still needed, explain acquire with a unique value and TTL, owner-checked release, and why the TTL makes it a lease. Then bring up the pause problem and fencing tokens unprompted, and position Redlock neutrally: fine for efficiency, debated for correctness. That sequence shows depth.

Model assumptions

This lesson is a scripted illustration, not a simulation: the simulator has no lock, lease, pause or fencing model, so every acquire, release, read and write is a packet placed by hand, and lock state, tokens and pauses are annotations. Time is compressed: a 600 ms lock TTL, a 700 ms pause, 30 ms one-way between a client and the lock service or storage, 5 ms between a client and a Redis node, a 20 ms per-node timeout and about 1 ms of processing. Real TTLs are typically seconds to minutes. Token values (33, 34) are illustrative.

The lesson as textEvery step of the simulation, written out.
  1. 1. Two clients, one counter, a lost update

    Two clients update the same record by read, modify, write. Both read v = 5 almost at the same time, both compute 6 and both write it back. Two increments happened; the stored value went up by one. Client 1’s update is silently lost.

    A distributed lock lets only one client at a time run that critical section, across processes and machines. Locks are used for two different reasons: efficiency (avoid doing the same work twice; an occasional overlap is tolerable) and correctness (an overlap corrupts data). This lesson is about the second, harder case.

    Scripted illustration: packets and annotations show the sequence, nothing is simulated.

    Scene: Client 1 and Client 2 both read v = 5 from storage, then both write 6. The second write overwrites the first, so one of the two increments is lost.

    Key idea: Concurrent read-modify-write loses updates. A lock serialises the critical section; for correctness it must hold under failures, not just usually.

  2. 2. Acquire, work, release

    Now each client first asks a lock service for the lock. Client 1 asks first and gets it: the service stores the key with a unique value identifying Client 1 and a time-to-live, in Redis terms SET lock <random-id> NX PX 600. Client 2 is refused and retries later.

    Client 1 reads, writes and releases. Releasing must delete the key only if it still holds Client 1’s value (a compare-and-delete, usually a small Lua script in Redis); otherwise a slow client could delete a lock someone else now holds. Client 2’s retry then succeeds.

    Scripted illustration.

    Scene: Client 1 acquires the lock; Client 2 is refused. Client 1 reads and writes storage, then releases the lock. Client 2 retries and acquires it at about 321 ms.

    Key idea: Acquire atomically with a unique owner value and a TTL; release only if you are still the owner.

  3. 3. Why the lock needs a TTL

    Client 1 took the lock and then crashed before releasing it. Without an expiry the lock would be held forever and everyone else would wait forever.

    With a TTL the lock service frees it on its own: Client 2 is refused at 231 ms, but after the 600 ms TTL its retry succeeds and it carries on. A lock with a TTL is really a lease: you hold it only for a bounded time, and long-running work has to extend it before it runs out.

    Scripted illustration.

    Scene: Client 1 crashed while holding the lock. Client 2 is refused at first; once the 600 ms TTL has passed, the lock service frees the lock and Client 2 acquires it and writes to storage.

    Key idea: A distributed lock must expire, because its holder may crash. That makes it a lease, and leases can run out under a holder that is still working.

  4. 4. A paused client writes after its lease expired

    Client 1 is back. It takes the lock and reads the record. Then its runtime stops the world for a 700 ms garbage-collection pause (a frozen VM or a swapped-out process does the same).

    While it is paused, its lease expires at 631 ms. Client 2 takes the lock, reads, and writes its update. At 824 ms Client 1 wakes up, still convinced it holds the lock, and writes a value computed from its old read. Storage accepts it and Client 2’s update is lost: the exact problem the lock was meant to prevent.

    Checking “do I still hold the lock?” right before writing does not fix it: the pause can come right after the check, and a write can also sit in a network queue. Scripted illustration.

    Scene: Client 1 acquires the lock and reads, then pauses for 700 ms. Its lease expires; Client 2 acquires the lock, reads and writes. Client 1 resumes and writes stale data, which storage accepts, overwriting Client 2’s update.

    Key idea: A lease can expire while its holder is paused. The holder cannot reliably know, so it may act after someone else took over.

  5. 5. Fencing tokens: storage has the last word

    The lock service now returns a fencing token with every grant, a number that increases each time: 33 for Client 1, 34 for Client 2. Clients send the token with every write. Storage remembers the highest token it has accepted and rejects any write with a lower one.

    Same pause, same timing. Client 2 writes with token 34; storage records 34. When Client 1 wakes up and writes with token 33, storage refuses it. The paused client can no longer do damage, however long it slept.

    Two requirements: the lock service must issue monotonically increasing tokens (a consensus-backed store does: etcd revisions, ZooKeeper zxids), and the resource must check them (a conditional write, a version column, an object-store precondition). Scripted illustration.

    Scene: The same pause, but with fencing tokens. Client 2 writes with token 34 and storage accepts it. Client 1 resumes and writes with token 33; storage rejects it because it has already seen 34.

    Key idea: Make the protected resource check a monotonically increasing token; then a stale lock holder is harmless.

  6. 6. Redlock and the debate around it

    Redlock is Redis’s algorithm for a lock that survives Redis node failures. The client tries to set the same key with the same random value and TTL on five independent Redis masters, one after another with a short per-node timeout. Here it succeeds on Redis 1, 2 and 4, finds Redis 3 held by someone else and gives up on Redis 5 (down) after 20 ms. It has 3 of 5, a majority, after 68 ms, so it holds the lock for the TTL minus the time spent and an allowance for clock drift. If it fails, it releases the key on every node.

    The safety of Redlock is debated. Martin Kleppmann (2016) argued that it depends on bounded network delays, process pauses and clock drift, that a clock jump on a Redis node can expire a key early, and that it provides no fencing token. Salvatore Sanfilippo (antirez) replied that these assumptions are reasonable in practice, that the client checks elapsed time after acquiring, and that pauses after acquisition affect any lock with automatic release.

    A common reading: for efficiency locks, Redlock or a single Redis lock is a reasonable choice; when correctness depends on the lock, use a consensus-backed lock service and fencing tokens checked by the resource. Scripted illustration.

    Scene: Client 1 tries the five Redis nodes in turn. Redis 1, 2 and 4 grant the key, Redis 3 refuses because another client holds it, and Redis 5 is down. With three of five after 68 ms, Client 1 holds the lock for the remaining TTL minus a clock-drift allowance.

    Key idea: Redlock takes a majority of independent Redis nodes within the TTL. Whether that is safe enough depends on timing assumptions; fencing at the resource does not.

  7. 7. What to remember about distributed locks

    Acquire atomically with a unique owner value and a TTL, and release only if you still own the lock. The TTL is necessary because holders crash, which makes every distributed lock a lease that can expire under a paused or slow holder.

    When correctness depends on the lock, the resource must reject stale holders with fencing tokens from a consensus-backed lock service. Redlock and single-node Redis locks are widely used for efficiency; their safety for correctness rests on timing assumptions.

    Scene: Two clients, a lock service, the storage they protect and five Redis nodes (one down) used by Redlock.

    Key idea: A lock is a lease; only fencing at the resource makes it safe for correctness.