Distributed locks & coordination
Leader election, lock TTLs and fencing tokens, why "Redis lock" answers need a caveat, saga pattern for cross-service workflows. Senior-round territory.
The mental model
Picture a shared whiteboard in an office where anyone can walk up and write. If two people write at once, you get an unreadable mess. The office solves this with a single marker: you may only write while holding the marker. That is a distributed lock — a token that grants exclusive access to a shared resource.
Now the hard part, the part that makes this a senior-round topic. The person holding the marker walks to lunch and forgets to give it back. You cannot wait forever, so you make a rule: "if nobody has written for five minutes, a new marker appears." Reasonable. But now the original person comes back from lunch — they still physically hold the old marker and start writing, while a second person holds the new one. Two markers. Two writers. Corruption. This is the central problem of distributed locking: you cannot tell the difference between a holder who is dead and a holder who is merely slow (paused for GC, stuck in a syscall, network-partitioned), and any lock with a timeout can be held by two processes at once.
The reason coordination exists as a discipline is that the naive answers are all subtly wrong, and the failures are invisible until they cost money. "Just use a Redis SETNX lock" is the answer that gets a candidate rejected, because it has no defence against the two-holders problem. The correct tools acknowledge that a lock can be double-granted and make the *resource* reject the stale holder — that is what a fencing token does.
Coordination covers three related needs:
- Mutual exclusion — only one worker runs this job / touches this row / sends this email.
- Leader election — exactly one instance is "in charge" (runs the cron, owns the partition, is the write primary).
- Cross-service workflows — a multi-step business process across services that each own their own database, with no distributed transaction available. This is the saga.
Without coordination you get duplicate cron runs, split-brain writes, double-charged customers, and workflows that get stuck half-done with no way to reason about the state.
- Deep dive
- Internal architecture
- Real-world use cases
- Best practices
- Common mistakes
- Performance
- Security
- Production troubleshooting
- Advantages & disadvantages
- Alternatives
- Interview expectations
- Interview questions
- Facts to remember
- Cheat sheet
- Quick revision