Distributed patterns and operations

Distributed locks

Understand why a lock across machines is really a lease, how a paused holder breaks it, and when to use fencing tokens or avoid the lock entirely.

Lesson13 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

A subscription company runs a nightly job that charges customers whose renewal is due. To finish sooner and to survive a machine failure, the team runs the job on three workers. On the first night two workers pick up the same customer a few milliseconds apart, and the customer is charged twice.

Inside one process this is a solved problem. You wrap the critical section in a mutex, and the runtime guarantees that one thread is inside at a time. That guarantee rests on things a single machine gives you for free: shared memory, one clock, and the fact that when the process dies, the lock dies with it.

Across machines none of that holds. So the team builds a lock from what it has, a database row with locked_by = 'worker-2'. It works until worker 2 crashes while holding the lock. Nobody else can take it, and renewals stop until a person deletes the row the next morning.

So they add an expiry: the lock is valid for 30 seconds unless renewed. A crashed holder can no longer block the system for ever. But the expiry creates the central difficulty of every distributed lock: a holder that is slow, and not dead, can lose the lock without knowing it.

Leases

A lock with an expiry is called a lease. The holder may act until the lease runs out, and must renew it to carry on. Every practical distributed lock is a lease, because the alternative is a lock that a dead machine holds for ever.

The length is a trade-off. A lease of a few seconds recovers quickly when a holder dies, and expires wrongly more often when a holder is merely slow. A lease of minutes rarely expires by mistake, and leaves work stuck for minutes after a crash.

The process-pause problem

A holder checks that its lease has 20 seconds left and then starts its write. Between those two lines of code, any of these can happen:

  • a stop-the-world garbage collection pause
  • the hypervisor suspends the virtual machine, or migrates it to another host
  • the process is starved of CPU, or blocks on a slow disk
  • the write sits in a network queue

Most such stalls last milliseconds. Occasionally one lasts many seconds. When the holder resumes, it carries on exactly where it stopped, with no signal that time has passed. Its lease has expired, another worker holds the lock, and two workers are now in the critical section.

No check inside the holder can fix this, because the pause can always fall after the check. The lock service cannot fix it either, since it has no way to reach into a paused process and stop it. The protection has to come from the resource being written to.

Fencing tokens

Have the lock service return a number with every grant, and make that number strictly increasing. This is a fencing token. The holder sends it with every write, and the resource remembers the highest token it has accepted and rejects anything lower.

A lease expires during a pause, and a fencing token saves the write4 components: Lock service, Worker A, Worker B, File storage. Connections: Worker A to Lock service (acquire); Worker B to Lock service (acquire); Worker A to File storage (write + token); Worker B to File storage (write + token).Lock service10 s lease, numberedWorker AWorker BFile storageremembers highest tokenacquireacquirewrite + tokenwrite + token

Step 1 of 8

Two workers must never update the same file at the same time. They coordinate through a lock service that grants a lease lasting 10 seconds, and it stamps every grant with a number that only goes up.

Read the steps as text
  1. Two workers must never update the same file at the same time. They coordinate through a lock service that grants a lease lasting 10 seconds, and it stamps every grant with a number that only goes up.
  2. Worker A asks for the lock and gets it, with token 33. It has 10 seconds to finish, or to renew the lease if it needs longer.
  3. Worker A reads the file and then freezes in a garbage collection pause that lasts 15 seconds. It has not crashed. It simply executes nothing, so it cannot renew the lease and cannot notice time passing.
  4. After 10 seconds the lease expires. The lock service cannot tell a paused worker from a dead one, so it frees the lock. Worker B asks for it and receives token 34.
  5. Worker B writes its update and includes token 34. Storage accepts the write and records 34 as the highest token it has seen.
  6. Worker A wakes up. From its point of view no time has passed and it still holds the lock, so it sends the write it prepared before the pause, with token 33.
  7. Storage compares 33 with 34 and rejects the stale write. Without the token it would have accepted it, and B's update would have been silently overwritten with data computed from an old copy of the file.
  8. A lease alone cannot stop a paused holder, because the holder is the last to find out that its lease has expired. The lock reduces contention. The token, checked by the resource itself, is what makes the write safe.
A lease expires during a pause, and a fencing token saves the write

The token turns “I believe I hold the lock” into a claim that the storage layer can check. ZooKeeper and etcd both provide a suitable number (a znode’s sequence number, or a key’s revision), and Google’s Chubby lock service calls the same idea a sequencer.

Two limits are worth stating. The resource has to cooperate: a database can check a token in a conditional update, but an email provider or a card network will not. And once the resource can reject stale writes, it is doing the real work. The lock has become an optimisation that avoids wasted effort, which points towards the alternatives at the end of this lesson.

Redis locks and the Redlock debate

The most common lock in practice is one Redis command:

SET lock:invoice:42 8f3a1c NX PX 30000

NX sets the key only if it does not exist, and PX 30000 expires it after 30 seconds. The value is a random string unique to this holder. Release is a small Lua script that deletes the key only if the value still matches. Without that check, a holder whose lease had expired would delete the next holder’s lock.

On one Redis node this is a sound lease, with the pause problem described above and one more gap. Redis replication is asynchronous, so if the primary fails just after granting the lock, the promoted replica may never have received the key and will grant the lock again.

Redlock, proposed by Redis’s creator Salvatore Sanfilippo, addresses the failover gap. The client tries to set the lock on five independent Redis nodes, and holds it only if a majority accept and the time spent acquiring is less than the lock’s validity time.

ZooKeeper and etcd

Both are consensus-backed stores. A grant is agreed by a majority of nodes before it is acknowledged, so the failure of one node cannot lose it.

  • ZooKeeper. Each contender creates an ephemeral sequential znode under the lock’s path. The lowest sequence number holds the lock, and every other contender watches the node just ahead of its own. An ephemeral node disappears when its creator’s session expires, and that session timeout is the lease.
  • etcd. A client creates a lease with a time to live, keeps it alive with heartbeats, and writes a key attached to the lease in a transaction that succeeds only if the key does not exist. The key vanishes when the lease expires.

These survive node failures that a Redis lock does not. They are not immune to the pause problem: a client can be paused beyond its session timeout and wake up believing it holds the lock. You still need the fencing token.

If all the data lives in one relational database, you may not need a lock service at all. A row lock (SELECT ... FOR UPDATE) or a PostgreSQL advisory lock is released when the transaction or connection ends, and sits in the same system as the data it protects.

Efficiency or correctness

Before choosing a lock, ask what happens if it fails and two holders overlap. Kleppmann’s distinction is a useful one:

  • Efficiency. The work is done twice: a report is generated twice, a cache entry is rebuilt twice. That is wasteful and harmless. A single-node Redis lock with a sensible expiry is enough, and anything heavier is over-engineering.
  • Correctness. Data is corrupted, or money moves twice. A lease alone is not enough, whatever it is built on. You need fencing at the resource, or a design that does not depend on the lock.

Alternatives that avoid the lock

  • Idempotency. Give each operation a unique key and have the receiver deduplicate, so that doing it twice has the effect of doing it once. This is what fixes the double charge in the opening story, because payment providers accept an idempotency key. See idempotency.
  • Optimistic concurrency. Read a version number with the data and write with UPDATE ... WHERE version = 7. If someone else got there first, no rows change and you retry. There is no lock and no expiry, and it is the same check a fencing token performs.
  • Partitioned ownership. Route all work for a key to one worker, for example by consuming from a Kafka partition, so that nothing contends in normal operation.
  • Database constraints. A unique index on customer and billing period makes the second charge record fail.

So when should you choose a distributed lock? Choose one to stop many workers doing the same expensive thing, or to coordinate access to a resource that cannot check a token or deduplicate, accepting the remaining risk. Do not choose one as the only thing standing between you and corrupt data.

In the interview

Locks come up when a design has competing workers: a job scheduler, inventory during a flash sale, a booking system. Reaching for “a Redis lock” and stopping there is the common weak answer.

A strong answer takes about a minute. Say that a distributed lock is a lease, that a paused holder can outlive it, and that safety therefore needs a fencing token checked by the resource. State whether your use is for efficiency or correctness and choose accordingly: a single Redis node for the first, and etcd or ZooKeeper with fencing for the second. Then offer the alternative that removes the lock, usually a conditional write or an idempotency key, and say why it is simpler.

Key takeaways

  • A distributed lock needs an expiry, because a crashed holder cannot release it. A lock with an expiry is a lease.
  • A holder that is paused or slow can outlive its lease without knowing, so two holders can be inside the critical section at once.
  • A fencing token is an increasing number issued with each grant. The resource rejects writes that carry an older token than one it has seen.
  • A Redis SET with NX and PX is a good lease on one node. It can be granted twice after a failover, because replication is asynchronous.
  • ZooKeeper and etcd survive node failures through consensus, and still need fencing against paused clients.
  • Use a simple lock when a failure only wastes work. When a failure corrupts data, rely on fencing, idempotency or conditional writes.

Check yourself

1. Why does every practical distributed lock carry an expiry time?
2. A worker confirms that its lease has 10 seconds left, then stalls for 40 seconds in a garbage collection pause, and then issues its write. What reliably prevents this write from corrupting data?
3. A Redis lock is taken with SET key value NX PX 30000, where the value is a random string, and released by a script that deletes the key only if the value matches. What does the random value prevent?
4. A lock is held in a Redis primary with one asynchronous replica. The primary dies just after granting the lock, and the replica is promoted. What can happen?
5. Which of these jobs is a reasonable use of a single-node Redis lock with no fencing?

0 of 5 answered

Flashcards

These 6 cards are in your review deck. Tap a card to see the answer.

What is a lease?

A lock that expires after a set time unless the holder renews it. It lets the system recover when a holder crashes without releasing.

What is the process-pause problem?

A holder can be frozen (garbage collection, VM suspension, slow I/O) for longer than its lease. When it resumes it still believes it holds the lock, and acts alongside the new holder.

How does a fencing token work?

The lock service issues a strictly increasing number with each grant. Writers send it with every write, and the resource rejects any write whose token is lower than the highest it has seen.

How do you take and release a lock on a single Redis node?

SET key random-value NX PX ttl to acquire. To release, run a script that deletes the key only if its value still equals your random value.

What is the disagreement about Redlock?

Kleppmann argued that it depends on timing assumptions and gives no fencing token, so it is unsafe for correctness. Sanfilippo replied that the assumptions are modest and that pauses affect every lease-based lock.

Name three alternatives to a distributed lock.

Idempotency keys, optimistic concurrency (a conditional write on a version), and partitioned ownership, where each key is handled by exactly one worker.

Review the deck