Topic 13.9
Distributed Locks (deep)
In one line
The lease + fencing story done properly — and when a lock is the wrong tool (idempotency often beats locks).
Think of it like this
The shared bathroom key idea from microservices, but now with clear rules for what happens if whoever's holding the key falls asleep and never returns it (lock expiry), so the bathroom doesn't stay locked forever.
Key ideas
- 01
Redis SETNX-with-lease + fencing token covers the simple case; the resource must reject stale tokens (13.7).
- 02
Redlock: multi-node Redis consensus-lock — academic and contested (side-effects under GC pauses).
- 03
Zookeeper/etcd locks: session + sequence — stronger guarantees for cross-host mutual exclusion.
- 04
Prefer: optimistic concurrency / idempotency / unique indexes wherever possible — locks are for truly exclusive sections.
- 05
Lock scope: keep the critical section tiny; never hold a distributed lock across a user-facing wait.
- 06
The full production code + the GC-pause problem live in phase-11 → distributed-locking.
- 07
Interview: 'I use a lease with fencing, or — better — I design the operation to be idempotent instead'.
Explain without notes
'I'll never need locks — idempotency is enough.' Where is that claim false (true exclusivity needed)?
Practice
Compare lock-based vs idempotency-based solutions for the same 'hit counter' and 'seat claim' problems.
Trade-offs
- ↔
Locks serialize + orphan-risk; idempotency + xou unique-constraints scale better at the cost of design effort.
Run it in production
You've designed it. Now build, operate, and break the same idea hands-on in the DevOps courses:
Completion checklist
I reach for leases+fencing when locked, and prefer idempotency whenever possible.