20/28
Part 5 of 6 · The worked exampleLearn and do

A worked example: clarify, then name the state

Here is the full problem, solved the way you'd do it in the room. Spend the first minutes asking, and say the answer you'll assume if the interviewer shrugs:

  • What does a reserve return when nothing is ready? None.
  • Who may ack or fail a task? Only its holder, and only while the lease is live. Others get False.
  • Where does a failed task go? Back in its original place.
  • What does max_attempts=3 mean? Three tries. The third failure is the last.
  • Does a timeout count as a failure? Yes, at its deadline.
  • Time? An injected clock.
  • One thread? Yes for now. A lock is a follow-up.

Then name the state, one field per job:

FieldHoldsWhy
orderid to enqueue numbera task's place, forever
stateid to waiting, reserved, done or deadstatus and every check
failuresid to failed attemptsthe dead-letter limit
holderid to (worker, lease number)who may ack, and which heap entry is live
readyheap of (order, id)which task goes next
coolingheap of (ready_at, order, id)when a failed task may go again
leasesheap of (deadline, lease number, id)which lease ends next
deadlist of idsdead_letters()

The heart of the class is one private method that every public method calls first. It ends every lease whose deadline has passed, calling the failure handler at the deadline. Then it moves every cooled task to ready. The order of those two steps matters. A lease that ends at 10, with no cooldown, makes its task ready at 10. If you release the cooling tasks first, that task waits until the next call.

WorkQueue in the editor is the timed part of the queue: three heaps, the holders, and _failed, which starts a task's cooldown. Write _tick, the method every public call runs first.