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=3mean? 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:
| Field | Holds | Why |
|---|---|---|
order | id to enqueue number | a task's place, forever |
state | id to waiting, reserved, done or dead | status and every check |
failures | id to failed attempts | the dead-letter limit |
holder | id to (worker, lease number) | who may ack, and which heap entry is live |
ready | heap of (order, id) | which task goes next |
cooling | heap of (ready_at, order, id) | when a failed task may go again |
leases | heap of (deadline, lease number, id) | which lease ends next |
dead | list of ids | dead_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.