Module 5 · Distributed systemsLesson 50 of 887 minAdvanced

Distributed locking

A distributed lock makes sure only one machine does something at a time. It needs an expiry, and an expiry needs a fencing token.

Try it

Play "Normal", then "Pause past lease" and watch the old lock holder overwrite newer data. Then play "Fencing token".

Sometimes only one machine should do a thing at a time: run the nightly billing job, process a particular user's account, rebuild a cache entry.

Why it's harder than a local lock

On one machine, if a process holding a lock crashes, the operating system releases it. Across machines, a crashed holder can't release anything. So distributed locks have a lease: the lock expires after, say, 10 seconds unless renewed.

But leases create a new problem. A holder can pause (garbage collection, a slow disk, a VM migration) for longer than its lease. It wakes up believing it still holds the lock, while the lock service has already given it to someone else. Two holders, one resource.

Fencing tokens

The fix is to make the protected resource check:

  1. Each time the lock is granted, the service returns an increasing number: 33, then 34...
  2. Every write to the resource includes the token.
  3. The resource remembers the highest token it has seen and rejects any lower one.

The paused holder with token 33 is now harmless.

Choosing a lock service

  • etcd, ZooKeeper, Consul: built on consensus, provide leases and increasing revision numbers usable as fencing tokens. The safe choice when correctness matters.
  • Redis (SET key value NX PX 10000): fast and simple, fine for efficiency locks (avoiding duplicate work). On its own it doesn't provide fencing tokens, so be careful using it for correctness.
  • Database row locks: if everything already lives in one database, SELECT ... FOR UPDATE is often simplest of all.

Better: avoid needing one

Locks are a source of bugs and slowdowns. Often you can design them away: partition work so each item has one owner, use atomic conditional writes, or make the work idempotent so running it twice is harmless.

Quick check

What does a fencing token protect against?