Design a job scheduler
hard 80 minBuild 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
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
1964
J. W. J. Williams invents heapsort and introduces the binary heap, the structure inside most schedulers.
1975
The first release of cron, AT&T Bell Laboratories' time-based job scheduler for Unix, is dated May 1975.
1987
George Varghese and Tony Lauck present hashed and hierarchical timing wheels at the ACM symposium on operating systems principles.
2004
Java 5 brings
ScheduledThreadPoolExecutor: fixed rate, fixed delay, and no overlap of one task.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.
- 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
- 2ScopeAsk what changes the design, then commit to a short list.
- 3API and dataThe contract first, then the data that serves it.
- 4DesignStart with the smallest system that works. Change it only when something breaks.
- 5Deep divesCompare the options before you open them, then say which you would pick.
- 6Explain your choicesAnswer first. Then compare your reasoning.
- 7By levelThe same question is judged differently for mid, senior and staff.
- 8MockAnswer against the clock, then score yourself.
How it works
Step through the idea, or press Play.
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
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
Ask
Once or repeating? What if a run is longer than the period? What after a failure? Does it survive a restart?
- 2
Cut
In scope: submit, cancel, once, fixed rate, fixed delay, retries, several workers. Out: disk, calendars, several machines.
- 3
Draw
Scheduler, Job, Trigger, Retry, Workers. One heap, one lock, one condition.
- 4
Code
Take what is due, wait for what is next, finish a run. These three methods are the answer.
- 5
Trace
An earlier job arrives. A job is cancelled while it runs. A task fails twice.
- 6
Extend
One of: missed runs, a million timers, a restart, a calendar.
Questions
Six questions, and what each answer changes
| Ask | If yes | If no |
|---|---|---|
| Do jobs repeat? | A trigger that gives the next moment | A heap of moments is enough |
| May two runs of one job overlap? | The next alarm is set before the run | It is set after the run: our choice |
| Must missed runs be made up? | A rule: skip, one, or all | The next tick in the future |
| Must it survive a restart? | A store, leases, tasks by name | Functions in memory |
| Do jobs wait for other jobs? | A graph of counts: a job gets its alarm when its count is 0 | Independent alarms |
| Is a second early or late important? | Monotonic clock, short waits, real-time threads | A timer wheel with coarse ticks is fine |
Design, first try
The loop most people write first
The design to avoid: one loop that looks, waits and works
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)
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 nightDesign, better
The design to reach
The design to reach: a list of alarms, and three small answers
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
Who owns what
| Class | Knows | Decides | Does not know |
|---|---|---|---|
Scheduler | Jobs, alarms, the clock | What is due, what comes after a run | What a task does |
Job | Its state and its valid alarm | Nothing: it is a record | The heap |
Trigger | A period or a delay | The next moment | Failures |
Retry | A number of tries and a wait | Whether and when to try again | The period |
Workers | Threads | Nothing: ask, run, ask again | Time |
States
The life of a job
One job
The hard part
Sleeping until the right moment
An earlier job arrives while the worker sleeps
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
| Run | Fixed rate starts | Fixed delay starts | Fixed rate, when run 2 takes 25 |
|---|---|---|---|
| 1 | 10 | 10 | 10 |
| 2 | 20 | 22 | 20, ends at 45 |
| 3 | 30 | 34 | 50: the ticks 30 and 40 are skipped |
| 4 | 40 | 46 | 60 |
Which trigger?
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))Cancel
A cross on the tag
What the heap does with a stale alarm
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
sleepin 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
| Call | Steps | Why |
|---|---|---|
submit | O(log n) | One push |
cancel | O(1) | One number, the alarm stays |
take | O(log n), plus the stale ones on top | Each stale alarm is thrown away once |
wait | Nothing while asleep | The thread is parked |
| 1,000,000 waiting jobs | 20 steps for a push | 2 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
- Java SE 21 API: ScheduledThreadPoolExecutor
- Python: heapq, priority queue notes
- Python: threading, condition objects
- Python: asyncio event loop
- APScheduler user guide
- Quartz: more about triggers
- Go source: runtime/time.go
- Netty API: HashedWheelTimer
- Varghese and Lauck: Hashed and Hierarchical Timing Wheels
- Confluent: Purgatory and hierarchical timing wheels
- Kubernetes: CronJob
- systemd.timer
- Celery: periodic tasks
- Wikipedia: cron
- Wikipedia: Heapsort