Skip to content

< all problems99 · Level 08, Production

Elect One Leader With a Lease

hard · implement · Production

Three copies of the scheduler agent run so that one crash does not stop the schedule. Only one may act at a time. Implement LeaseLock(store, ttl), a lease on a shared store, with a term number that fences out a leader that does not know it has lost.

store is shared and starts empty: holder, expires, term, log, rejected. All times are ticks passed in by the caller.

  1. try_acquire(node, now): succeeds when there is no holder, or the lease has expired (now >= store.expires), or node holds it right now. Every acquisition bumps store.term by one, except a holder re-acquiring its own unexpired lease, which keeps its term; a node that let its lease expire gets a new term like anyone else. On success set store.expires = now + ttl and return the term. On failure return None and change nothing.
  2. renew(node, now): only the current holder, while unexpired, may extend the lease to now + ttl. Returns True or False.
  3. holder(now): the holder, or None once the lease has expired.
  4. act(node, term, now, value): appends (term, value) to store.log only when node is the unexpired holder and term == store.term. Otherwise appends (node, term, value) to store.rejected and returns False. Returns True on a write.

The term is the part people skip. A leader that paused for longer than its TTL will come back and act, believing it still leads; its stale term is what stops the write. Kubernetes' Lease objects and resourceVersion do the same job for its controllers.