Distributed Locking
Making sure that when many machines want the same thing, only one of them gets it at a time.
Distributed locking in 30 seconds
- What: make sure only one of many machines acts on a shared resource at a time.
- How: acquire a key in a shared store (Redis/ZooKeeper/etcd), do the work, release it; a lease (timeout) stops a crashed holder blocking forever.
- The gotcha: a holder can freeze, its lease expires, someone else takes the lock, then the frozen one wakes and writes — two writers.
- The fix: fencing tokens — an increasing number per grant; the resource rejects any write with a stale (lower) token.
- First ask: can I avoid the lock? Idempotency, partitioning per key, or a unique DB constraint often remove the need.
- Tooling: Redis for speed (rare miss OK), ZooKeeper/etcd when correctness is non-negotiable.
Start with a kitchen, not a cluster
Picture a shared office kitchen with one microwave. If two people walk up at the same moment, they don't both shove their lunch in — someone goes first, the other waits. That unspoken 'one at a time' rule is a lock. On a single computer, the operating system hands these out easily. The trouble starts when the people aren't in the same room — when the 'microwave' is a shared file or a bank balance, and the 'people' are servers scattered across a data center that can only talk over a flaky network.
Why we even need one
Here's the kind of moment that pushes you toward a distributed lock:
- Two servers both run a nightly job that charges customers — and a customer gets billed twice.
- Two workers pick up the same task off a list and do the same work, wasting effort or corrupting data.
- Two requests both update the same inventory count and one silently overwrites the other.
The common thread: some action must happen once, by one actor, even though many could attempt it. A distributed lock is the referee that picks the one.
The gap a normal in-process lock can't fill
Every language ships with locks — a mutex, a synchronized block, a threading.Lock. So why not just use one of those? Because an in-process lock only governs threads inside one process on one machine. It lives in that machine's memory and means nothing to any other machine. The instant your 'one at a time' guarantee has to hold across two servers — two replicas of the same service, two workers on two boxes — a local lock is invisible to the other side, and both proceed as if they're alone.
import threading
lock = threading.Lock() # lives in THIS process's memory only
def charge_customer(id):
with lock: # safe against other threads HERE...
do_charge(id) # ...but a second server runs its OWN lock,
# sees nothing of ours, and charges again.
# Two machines => two independent locks => the guarantee is gone.
# We need a lock that lives OUTSIDE any single machine — a shared one.That's the whole reason a distributed lock exists: it moves the 'do not disturb' sign out of any one machine's memory and into a shared store every machine can see — so 'only one at a time' holds across the whole fleet, not just within a single process.
How it actually works
Strip away the jargon and the idea is simple — it's a shared note everyone can read:
- Acquire — a worker asks a shared store (Redis, ZooKeeper, etcd) to set a key only if nobody else holds it. 'I've got the microwave.'
- Do the work — the holder, and only the holder, touches the protected resource.
- Release — when done, it deletes the key so the next worker can take a turn.
- Expire — every lock carries a timeout (a lease), so if the holder crashes mid-task, the lock doesn't get stuck forever.
# SET key value NX PX <ms>: set only if absent (NX), auto-expire after PX ms.
# The random token proves WE are the owner when we release.
def acquire(redis, key, ttl_ms):
token = uuid4()
ok = redis.set(key, token, nx=True, px=ttl_ms) # atomic: only one winner
return token if ok else None
def release(redis, key, token):
# Only delete if we still hold it — never free someone else's lock.
if redis.get(key) == token:
redis.delete(key)
token = acquire(redis, "lock:invoice:42", ttl_ms=30000)
if token:
try:
charge_customer(42) # do the work — only the holder gets here
finally:
release(redis, "lock:invoice:42", token)
else:
pass # someone else holds it — back off and retry laterTwo subtle things in that snippet carry most of the correctness: the NX flag makes 'set only if nobody holds it' a single atomic step (no check-then-set race), and the random token means release only ever frees our lock, never one that already expired and was re-taken.
The trap that catches almost everyone
That lease — the safety timeout — is also where things get sneaky. Follow the story:
- Worker 1 grabs the lock with a 30-second lease and starts working.
- It freezes — a long garbage-collection pause, a slow disk, a network hiccup. It doesn't know it froze.
- The 30 seconds pass. The lock expires. Worker 2 legitimately grabs it and starts working.
- Worker 1 wakes up, still believing it holds the lock, and writes to the shared resource. Now two workers are writing. The lock failed at the one job it had.
// The lock service hands out a strictly increasing token with each grant.
long token = lockService.acquire("invoice:42"); // e.g. Worker 1 gets 33
// Every write carries its token. The storage keeps the highest it has seen.
class FencedStore {
long highestSeen = 0;
synchronized boolean write(long token, Data data) {
if (token < highestSeen) {
return false; // stale holder — reject the write
}
highestSeen = token;
persist(data);
return true;
}
}
// Timeline:
// Worker 1 (token 33) freezes, lease expires.
// Worker 2 (token 34) writes -> highestSeen = 34.
// Worker 1 wakes, writes with 33 -> 33 < 34 -> REJECTED. Data stays safe.Picking a tool (and the trade-offs)
| Option | The pitch | The catch | Reach for it when |
|---|---|---|---|
| Redis (single) | Fast and dead simple to set up. | If that Redis node dies, locking is down; edge cases under failover. | Speed matters and the odd missed lock is survivable. |
| Redis (Redlock, multi-node) | More resilient across several nodes. | Debated correctness under bad clocks/pauses; complex. | You want Redis but need more safety — with eyes open. |
| ZooKeeper / etcd | Built for coordination; strong guarantees. | More moving parts; a bit slower to operate. | Correctness is non-negotiable (leader election, config). |
The honest question to ask first
Before adding a lock, pause and ask: do I actually need one? Locks add latency, a new dependency, and a fresh set of failure modes. Often there's a lighter way out:
- Make the operation idempotent so running it twice is harmless — then you don't care who runs it. (See Idempotency.)
- Partition the work so each key is only ever handled by one worker, removing the contention entirely.
- Use a database constraint (a unique key) to let the database reject the duplicate for you.
A good engineer reaches for a distributed lock last, not first — because the cheapest lock is the one you designed away.
Locking looks like a small, local detail, but it's really about correctness under concurrency — one of the quiet forces that decides whether a distributed system stays trustworthy as it grows.
Why it matters
- It's the guardrail that keeps 'exactly once' promises honest when many machines compete for the same resource.
- It protects the moments that cost real money or trust — payments, inventory, bookings — from double execution.
- It underpins higher-level machinery: leader election, scheduled jobs, and safe writes to shared state all lean on it.
If ignored
- Silent duplicates: customers charged twice, inventory oversold, the same job run by two workers.
- Data corruption from two writers racing on the same record, often invisible until it's expensive.
- The nastiest kind of bug — intermittent, load-dependent, and nearly impossible to reproduce on demand.
Where it fits
- Sits in the write path, right where a shared resource is about to change.
- Lives inside coordination services and job schedulers rather than in your business logic.
- Usually the last line of defense, after you've tried to design the contention away.
Related topics
- Idempotency: the lighter alternative — often removes the need for a lock entirely
- Consensus: a correct lock service relies on consensus underneath
- Consistency models: locks are how you enforce strong consistency on a shared resource
- Distributed transactions: an alternative way to coordinate multi-step changes safely
Interview lens
Questions it unlocks
- Two servers run the same cron job — how do you stop double execution?
- What goes wrong with a lock that only uses a timeout?
- Would you reach for Redis or ZooKeeper for locking, and why?
60-second answer
I first ask whether I can avoid the lock — by making the operation idempotent, partitioning work per key, or using a unique constraint — because a lock adds latency and failure modes. If I genuinely need one, I use a lease so a crashed holder doesn't block forever, and crucially a fencing token so a frozen-then-resumed holder can't corrupt data: the resource rejects any write with a stale token. For the tool, Redis when speed matters and a rare miss is survivable, ZooKeeper or etcd when correctness is non-negotiable.
Common traps
- Relying on a timeout alone, with no fencing token, and allowing a stale holder to write.
- Reaching for a distributed lock when idempotency or partitioning would remove the need.
- Assuming single-node Redis locking is safe across failover without thinking it through.