13/28
Part 3 of 6 · Leases and timeLearn and do

Check the leases on every call, not on a timer

When does the queue notice that a lease ended? The first idea is a background thread that wakes up every second. That brings threads and locks into a 60-minute interview, and it still notices up to a second late.

There's a simpler way. The queue only has to be right when someone asks it something. So every public method starts by bringing the leases up to date with the clock: end every lease whose deadline has passed, then answer. This is lazy expiry. Nothing happens between calls, and nothing needs to.

The rule is every public method, with no exceptions. reserve must check, or it hides a task that's free again. status must check, or it reports a dead lease as reserved. And ack must check, or a worker whose lease ended can still finish a task another worker may be running.

That last one is the bug in the editor. w1 reserves a at 0, with a timeout of 10. Nobody calls reserve after that. At 12, w1 sends its ack. The lease is still in self.leases, because only reserve cleans them up, so the ack wins.

Why does a late ack matter if the work got done? Because the queue has already decided the work wasn't done. In a real system, another worker could have the task by now, and both would write a result. The queue has to give one answer about who holds a task, and the clock decides it.

In the editor, WorkQueue lets w1's late ack count. It keeps waiting as a plain list, as the early steps did, to stay short, so leave that alone: the bug is in the leases. Find the method that reads the leases without bringing them up to date first, and fix it.