Distributed locks and fencing tokens
A distributed lock lets one process at a time, among many machines, work on something: one worker paying a merchant, one job rebuilding a report. It's harder than a lock inside one program, because the holder can pause, crash or lose touch while holding it. Interviewers listen for two things: what the lock is for, and what stops a holder that lost the lock without knowing.
The hotel key card
A hotel's front desk gives you a key card that works until checkout. If you stay past checkout and the desk gives the room to a new guest, the new card carries a higher number. The door remembers the highest number it has seen, so once the new guest has opened it, your old card stops working, even though it still looks fine in your pocket.
- the front desk → a lock service (Redis, etcd, ZooKeeper)
- you and the new guest → two workers after the same lock
- works until checkout → a lock with a lease that expires, so a crashed holder can't block everyone forever
- the new guest's higher number → a fencing token, and your old card → worker 1's older token
- the door that remembers → storage that checks the token on every write