AlgoViz

Design a job scheduler

hard 80 min

Build a library that runs jobs later and again in one process: a heap of alarms, workers that sleep for exactly the gap, cancel without a search, retries that are alarms, and tests without a single sleep.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:30

See it run

Workers asleep, alarms in a heap: watch who wakes whom, and which lines decide it.

Operations

Submit and run

A job for second 5, one sleeping worker.

Step 1 of 7

Nothing to do

appcallerschedulerSchedulernow0heap topnonejobs0worker 1Workerstateasleepsleeps toa signal

The heap is empty. The worker sleeps without a limit.

Step 1: Nothing to do

def wait(self):    with self._changed:        while not self._closed:            job = self._take()            if job is not None:                return job            gap = self._gap_to_top()            self._changed.wait(gap)        return None
Cost
O(log n)
Guarantee
Never early

The worker gives the lock back while it sleeps.

In the real world

The same job scheduler doing real jobs. Pick one and step through it.

Marked now, ended at the end. The id stays taken.

Step 1 of 4

Running

appcallerschedulerSchedulernow60heap topnonejobs1worker 1Workerstateruns backupsleeps tononebackupJobstaterunningticket4

Worker 1 runs backup.

Step 1: Running

def _finish(self, job, problem):    with self._changed:        now = self._now()        if job.state is State.CANCELLED:            self._end(job, State.CANCELLED)            return        if problem is not None:            job.failed += 1            wait = job.retry.wait_ms(job.failed)            if wait is not None:                self._set_alarm(job, now + wait)                return        following = job.trigger.after(job.planned, now)

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Sleeping in place of waiting

    critical

    A sleep cannot be cut short. An earlier job is found too late.

    Wrong
    time.sleep(top.due - now)
    Right
    self._changed.wait(top.due - now)   # ends at a signal
  • Running under the lock

    critical

    One slow task stops submit, cancel and all workers.

    Wrong
    with self._changed:    job = self._take()    job.task()
    Right
    with self._changed:    job = self._take()job.task()                          # outside
  • No signal after a take

    critical

    The only worker that watched the clock has left with a job. The next alarm rings for nobody.

    Wrong
    heapq.heappop(self._heap)return job
    Right
    heapq.heappop(self._heap)if self._heap:    self._changed.notify()return job
  • Setting the alarm before the run

    major

    A run longer than its period overlaps with itself, and each makes the other slower.

    Wrong
    self._set_alarm(job, due + period)job.task()
    Right
    job.task()self._finish(job, problem)          # sets the next alarm
  • A retry that sleeps

    major

    Ten failing jobs take ten workers for a minute.

    Wrong
    except Exception:    time.sleep(backoff)    job.task()
    Right
    except Exception as problem:    self._finish(job, problem)      # another alarm
  • The wall clock for gaps

    major

    Somebody sets the clock back, and every job is an hour late.

    Wrong
    now=lambda: int(time.time() * 1000)
    Right
    now=lambda: time.monotonic_ns() // 1_000_000

Interview tips

  • Open with

    • One process, or many?
    • Overlap, failure, restart?
    • Never early, sometimes late.
  • Reject aloud

    • CronJob is a trigger.
    • An alarm is a tuple.
    • A task is a function.
  • Prove it

    • Two workers, same second.
    • Cancel while running.
    • Planned 20, ends 45, next 50.
  • Never

    • Sleep in a worker.
    • Task under the lock.
    • notify at close.