Leader election, leases and locks
A subscription company runs its monthly billing job at 1 a.m. on two servers, so that one can take over if the other dies. A Redis lock with a 30 second expiry makes sure only one runs at a time. One night the first server freezes for 40 seconds in a long garbage collection. Its lock expires, the second server takes it and starts billing, and then the first server wakes up and carries on from where it was. Thousands of customers are charged twice before anyone looks at a graph.
The lock worked exactly as designed. The design was missing one number, and this chapter is about that number.
A worker holds a lock with a 30 second expiry, checks that it still holds it, then freezes for 40 seconds and writes. What would the storage need to know to reject that write?
Why you need exactly one#
A lot of work must be done by one machine at a time. The nightly billing run. The scheduler that hands out jobs. The single writer for a shard. The primary database. Running two of them at once means double charges, double emails or two diverging copies of the data.
Picking that one machine and agreeing on it is leader election. A lock is the same idea for a shorter piece of work: "I am the one doing this, until I say I am done". Both have to answer the same hard question: what happens when the holder stops responding?