Skip to content

< all problems98 · Level 08, Production

Fix the Worker That Drops Its Task on Shutdown

medium · debug · Production

Every deploy loses a few tasks. The rolling update sends each worker a stop signal, and the worker exits on the spot, with a task half done and nowhere. Fix worker_loop(queue, term_at, grace).

queue has pop() (the head, or None when empty), push_front(task) and items. A task is {"id", "duration"}. The stop signal arrives at tick term_at; grace is how many ticks the worker has after it before it is killed.

Return the event log, a list of tuples:

  1. Before taking a task, if now >= term_at, the worker takes nothing more and logs ("exit", now).
  2. Taking a task logs ("start", id, now); it ends at now + duration and logs ("done", id, end).
  3. If the signal arrives while a task is running (term_at < end): the task finishes when end <= term_at + grace, then the worker exits at end. Otherwise, at term_at + grace, the task goes back to the front of the queue, logged ("requeue", id, term_at + grace), and the worker exits then.
  4. An empty queue means exit at once.

Nothing is lost: after the loop, every task is either done once or back on the queue. This is what SIGTERM, terminationGracePeriodSeconds and a queue with redelivery add up to; the fix is in the worker, which has to stop taking work before it stops working.