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

The scheduler that never polls

1:25Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

A job scheduler keeps promises about time. You give it a piece of work and a rule, and it runs the work at the right moments, until you cancel it.

Inside there is a priority queue ordered by time. The earliest alarm is on top, so one look tells what is due and, if nothing is, how long to sleep.

The rest is care: a sleep that can be cut short, work that runs without the lock, and a clear rule for what happens after a run, a failure or a cancel.

Why it exists

Programs are full of later: send the reminder, refresh the token, give up after 30 seconds, write the report at night. Without a scheduler each of them gets its own thread with its own sleep.

The problem is a favourite because it needs three things at once: a data structure, waiting between threads, and a model that does not grow a tree of job types.

Its small questions are real ones. Overlap, missed runs, clock changes and lost jobs are what people are called for at night.

A short history

  1. 1964

    J. W. J. Williams invents heapsort and introduces the binary heap, the structure inside most schedulers.

  2. 1975

    The first release of cron, AT&T Bell Laboratories' time-based job scheduler for Unix, is dated May 1975.

  3. 1987

    George Varghese and Tony Lauck present hashed and hierarchical timing wheels at the ACM symposium on operating systems principles.

  4. 2004

    Java 5 brings ScheduledThreadPoolExecutor: fixed rate, fixed delay, and no overlap of one task.

  5. 2015

    Apache Kafka's request purgatory is described with hierarchical timing wheels in place of a delay queue.

Words to know

Alarm
A moment, a number and a job. What the heap holds.
Trigger
The rule that gives the next moment.
Fixed rate
The next moment is counted from the plan.
Fixed delay
The next moment is counted from the end.
Misfire
A run that could not start at its moment.
Coalesce
Run once for several missed moments.
Stale alarm
An alarm of a job that was cancelled or moved.
Condition
A place to wait for a change, tied to a lock.
Monotonic clock
A clock that never goes back. For gaps.
Lease
A right that ends by itself.
Jitter
Chance in a wait, so that many do not come back together.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

Solve it like an interview

New to it? Start with Approach. Revising? Go straight to the mock.

  1. 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
  2. 2ScopeAsk what changes the design, then commit to a short list.
  3. 3API and dataThe contract first, then the data that serves it.
  4. 4DesignStart with the smallest system that works. Change it only when something breaks.
  5. 5Deep divesCompare the options before you open them, then say which you would pick.
  6. 6Explain your choicesAnswer first. Then compare your reasoning.
  7. 7By levelThe same question is judged differently for mid, senior and staff.
  8. 8MockAnswer against the clock, then score yourself.

How it works

Step through the idea, or press Play.

Step 1 of 3

Submit. The trigger gives the first moment, an alarm goes into the heap, the sleeper is signalled

Understand it

Start here

The rooster with the alarm strings

How one rooster keeps a whole farm on time
5:006:00milk7:00eggs8:00cartZz

What an interviewer looks for

  • Do they separate when from what?

    The trigger says when, the task says what, the retry rule says what after a failure. Three small parts instead of a tree of job types.

  • Do they wait properly?

    Sleep until the earliest alarm, and wake up early if an earlier one arrives. This is the heart of the problem.

  • Do they run outside the lock?

    A job may take an hour. If the lock is held, nobody can even cancel it.

  • Can they test it?

    The clock is passed in, and one step can be made without a thread. A night passes in a microsecond.

How to spend the round

  1. 1

    Ask

    Once or repeating? What if a run is longer than the period? What after a failure? Does it survive a restart?

  2. 2

    Cut

    In scope: submit, cancel, once, fixed rate, fixed delay, retries, several workers. Out: disk, calendars, several machines.

  3. 3

    Draw

    Scheduler, Job, Trigger, Retry, Workers. One heap, one lock, one condition.

  4. 4

    Code

    Take what is due, wait for what is next, finish a run. These three methods are the answer.

  5. 5

    Trace

    An earlier job arrives. A job is cancelled while it runs. A task fails twice.

  6. 6

    Extend

    One of: missed runs, a million timers, a restart, a calendar.

Questions

Six questions, and what each answer changes

AskIf yesIf no
Do jobs repeat?A trigger that gives the next momentA heap of moments is enough
May two runs of one job overlap?The next alarm is set before the runIt is set after the run: our choice
Must missed runs be made up?A rule: skip, one, or allThe next tick in the future
Must it survive a restart?A store, leases, tasks by nameFunctions in memory
Do jobs wait for other jobs?A graph of counts: a job gets its alarm when its count is 0Independent alarms
Is a second early or late important?Monotonic clock, short waits, real-time threadsA timer wheel with coarse ticks is fine
Six answers take two minutes and remove half of the possible classes.

Design, first try

The loop most people write first

The design to avoid: one loop that looks, waits and works

JobScheduler- jobs: List<Job>- running: bool+ add(job)+ loop()+ runCron(job)+ runOnce(job)+ sendEmail(job)

1/4One class does everything

It keeps the list, watches the time, knows the kinds of job and runs the work. A slow email stops all other jobs, because looking and working share one thread.

owns (dies together)usesextends (is a)

Nothing here is wrong in the first hour. It is wrong on the day when one task takes ten minutes.
Python
import timeclass BadScheduler:    def __init__(self):        self.jobs = []    def add(self, name, task, every):        self.jobs.append([name, task, every, time.time() + every])    def loop(self):        while True:            for job in self.jobs:                 # every job, every second                if time.time() >= job[3]:                    job[1]()                      # a slow or failing task stops all                    job[3] = time.time() + job[2] # the run slips a little each time            time.sleep(1)                         # up to a second late, awake all night
Four faults in twelve lines: it wakes up for nothing, it is up to a second late, one slow task stops everything, and a task that raises ends the loop for good.

Design, better

The design to reach

The design to reach: a list of alarms, and three small answers

Scheduler- jobs: Map<Id, Job>- heap: MinHeap<Alarm>- now: () -> ms+ submit(id, task, trigger)+ cancel(id): bool+ wait(): Job?+ run(job)

1/5One owner of time

Scheduler keeps the jobs by id and the alarms in a heap, earliest on top. Nobody else decides what is due. The clock is passed in.

usesowns (dies together)has (lives on)implements

A question mark means that the answer may be nothing: no next run, no further try, closed.

Who owns what

ClassKnowsDecidesDoes not know
SchedulerJobs, alarms, the clockWhat is due, what comes after a runWhat a task does
JobIts state and its valid alarmNothing: it is a recordThe heap
TriggerA period or a delayThe next momentFailures
RetryA number of tries and a waitWhether and when to try againThe period
WorkersThreadsNothing: ask, run, ask againTime

States

The life of a job

One job

A repeating job that fails all its tries does not end. The run is given up, and the job waits for its next run.

The hard part

Sleeping until the right moment

An earlier job arrives while the worker sleeps

The worker is woken for nothing once. That is cheap. The rule is: a wake-up is a reason to look, never a reason to act.

How does a worker wait for the next job?

BreaksLook every second
How
while True: run_due(); sleep(1)
Limit
Up to a second late. A thousand looks for nothing while the heap is empty.
Choose when
A script for one person.
BreaksSleep until the first alarm
How
sleep(first.due - now)
Limit
A job that arrives later and is due earlier is found too late: a sleep cannot be cut short.
Choose when
Only if all jobs are known at the start.
WorksA condition with a time limit
How
wait(gap) releases the lock, ends after the gap or at a signal, and the loop looks again.
Limit
Signals must be complete: after every push, and after every take if alarms are left.
Choose when
The answer for this round.
StrongThe same, and say who watches
How
With several workers only one needs to watch the next alarm. When it leaves with a job, it wakes another one to watch.
Limit
More thinking. See waiting well.
Choose when
As soon as there are two workers.

Repeat

Fixed rate or fixed delay

A job of 2 seconds, period 10

RunFixed rate startsFixed delay startsFixed rate, when run 2 takes 25
1101010
2202220, ends at 45
3303450: the ticks 30 and 40 are skipped
4404660
Rate counts from the plan, so it stays on the grid. Delay counts from the end, so there is always a pause of 10.

Which trigger?

Python
PERIOD, WORK, WAKE_LATE = 60_000, 2_500, 40      # millisecondsdef from_finish(planned: int, finished: int) -> int:    return finished + PERIODdef on_the_grid(planned: int, finished: int) -> int:    missed = max(0, finished - planned) // PERIOD    return planned + (missed + 1) * PERIODfor rule in (from_finish, on_the_grid):    due = PERIOD    for run in range(24 * 60):        started = due + WAKE_LATE        last, due = due, rule(due, started + WORK)    print(rule.__name__, "run 1440 was planned for minute", round(last / 60_000, 2))
A task of 2.5 seconds and a wake-up that is 40 milliseconds late. Counted from the end, the last run of the day slips by an hour.
Edit and run it in your browser

Cancel

A cross on the tag

What the heap does with a stale alarm

A job has one valid ticket number. Cancel sets it to 0. Every alarm with another number is dead.

Do

  • Pass the clock in, in whole milliseconds
  • Keep the task out of the lock
  • Set the next alarm after the run
  • Wait in a loop
  • Give each alarm a number, so that ties keep their order and stale ones are known

Do not

  • Call sleep in the scheduler
  • Make a class for each kind of job
  • Search the heap to cancel
  • Use the wall clock for a gap
  • Let an exception in a task end a worker

Cost

What each call costs

CallStepsWhy
submitO(log n)One push
cancelO(1)One number, the alarm stays
takeO(log n), plus the stale ones on topEach stale alarm is thrown away once
waitNothing while asleepThe thread is parked
1,000,000 waiting jobs20 steps for a push2 to the power of 20 is 1,048,576

Summary

The whole topic in one minute.

Jobs in a map, alarms in a heap, one condition for both. A worker throws away stale alarms, takes what is due, or sleeps for the gap. Every push and every take that leaves alarms behind sends a signal.

The task runs without the lock. Afterwards the scheduler decides: another try, the next run, or the end. When and what after a failure are separate parts, and the clock is an argument.

  • When, what and what after a failure are three parts. They combine freely.
  • One heap, one lock, one condition. Sleep until the top, and signal after every push.
  • A wake-up is a reason to look again.
  • The task runs without the lock. The next alarm is set when it ends.
  • Cancel is a number, not a search.
  • The clock is an argument.

Sources