Requirements of a task scheduler
medium 26 minA task scheduler runs work later, in the right order, on many machines, and does not forget it.
Video lesson · Chapter 1 of 5
Promise a reminder for nine o'clock
Theory
Read or listen first. About 2 min.
What it is
A task is a piece of work that does not have to finish while the user waits: send an email, resize a picture, build a report. A distributed task scheduler stores such tasks and runs each one on some machine at the right time.
Its requirements say what it accepts, when a task may start, how many times it may run, what happens on failure, and how much of it there is. They are agreed before anyone chooses a database or a queue.
Why it exists
Without a scheduler every program grows its own timers. A timer in memory disappears when the process restarts, and nobody notices the report that never came.
Most surprises come from three questions that nobody asked. May a task run twice? How late may it start? What happens to it when the worker dies? The answers decide the whole design.
A short history
1987
Paul Vixie writes Vixie cron, which runs commands at set minutes on one Unix machine. Its five time fields are still the common way to write a schedule.
October 2014
Airflow is started at Airbnb by Maxime Beauchemin. Tasks now form graphs, where one runs after another.
7 January 2016
PostgreSQL 9.5 adds
SKIP LOCKED, which lets many workers take different rows from one table.April 2021
CronJob becomes generally available in Kubernetes 1.21: cron for a cluster.
10 November 2022
AWS launches EventBridge Scheduler, a managed service for one-time and recurring schedules.
Words to know
- Task
- Work to be done once, with a payload, a time, a priority and rules for failure.
- Worker
- A process that takes tasks and runs them.
- Start latency
- The time between when a task was due and when it began.
- At-least-once
- Every accepted task runs, and some may run more than once.
- Idempotent
- Running it twice has the same effect as running it once.
- Dead-letter queue
- The place for tasks that used up their attempts, kept for a person to look at.
- Lease
- A worker's right to a task for a limited time.
How it works
Step through the idea, or press Play.
Say what people do. Submit, cancel, pause, list and watch tasks
Understand it
Start here
Planning the chores on a farm
A farm has hens to feed, eggs to fetch and gates to mend, and a few helpers to do it. Asha plans the work. Each decision is a requirement of a task scheduler.
The inside of the machine that does this is Design of a distributed task scheduler.
The idea
A task and its life
Every state a task can be in
What one task carries
| Field | Example | Why |
|---|---|---|
| Id | a UUID | To ask about it later |
| Type and payload | send email, with a reference | What to do. Keep it small |
| Due time | Friday 09:00 UTC | When it may start |
| Priority | low, medium, high, critical | Who goes first |
| Dependencies | after the export | A before B |
| Timeout | 30 seconds | When to give up on one attempt |
| Retry policy | 3 retries, doubling from 1 s | What to do after a failure |
| Idempotency key | order 42, receipt | So that a repeated submit makes one task |
Inside the promise, outside the promise
Scope
Who uses it, and for what
Email
Asynchronous. Minutes late is fine, twice is annoying.
Payments
Transactional. Twice is a disaster, so a key is required.
Reports
Batch. Long, heavy, at night.
Data sync
Recurring. Two overlapping runs are the danger.
Images
CPU-heavy. Workers of a special kind.
Push messages
Time-sensitive. An hour late is useless, so tasks expire.
Ask which two matter. A scheduler for reports can poll once a minute. A scheduler for push messages cannot.
Functional
What it must do
Four groups
- 1
Submit
Accept payload, priority and time. Validate first. Return a unique id at once. Support one-time, delayed and recurring tasks.
- 2
Execute
Run on available workers, in priority order, after dependencies, with a timeout for each attempt.
- 3
Manage
Cancel, pause, resume. Show status and history. List by status, type and date.
- 4
Handle failure
Retry by policy with growing delays, move exhausted tasks to a dead-letter queue, and tell someone.
The API
| Request | Meaning | Answer |
|---|---|---|
POST /tasks | Submit | 202 and an id |
GET /tasks/{id} | Status and history | 200 |
DELETE /tasks/{id} | Cancel | 202, or 409 if it is done |
GET /tasks with filters | List, page by page | 200 and a cursor |
POST /schedules | Create a recurring task | 201 |
POST /queues/{name}/pause | Stop taking new work | 200 |
Promises
How well it must do it
Service level objectives
| Quality | Target | How it is measured |
|---|---|---|
| Submit latency | p50 50 ms, p99 200 ms | API call to acknowledgement |
| Start latency | p99 under 5 s | Due time to start of the first attempt |
| Success rate | Over 99.9% | Completed tasks of all finished tasks |
| Availability | 99.99% | Successful submits of all submits |
| Durability | No acknowledged task lost | Reconcile accepted against finished |
| Throughput | A number from your traffic | Finished tasks a second |
Why five nines of durability is far too weak
What 99.99% availability leaves
Reliability and scale
- At-least-once execution
- Handlers safe to repeat
- No single point of failure
- More workers give more throughput, until a shared part is full
- Scale on age of the oldest waiting task and queue depth
Observability (do not forget it)
- Metrics: depth, age, run time, success and failure
- Logs: each state change with the task id
- Alerts: failures, growing queues, late starts
- A person can find one task and its history
Times
What on time means
- 1
Not before
A due time is the earliest moment. Nothing can promise the exact moment, because workers may be busy.
- 2
How late is too late?
A push message about a match expires after an hour. A bill does not. Give tasks an optional deadline.
- 3
Missed runs
The system was down at 02:00 and is back at 05:00. Run once, run all missed ones, or skip? Choose per schedule.
- 4
Overlap
The run of 02:00 is still going at 03:00. Forbid, allow or replace.
- 5
Time zones
At 02:30 local time, clocks may jump. One run may not exist, or exist twice. Store times in UTC and keep the zone with the schedule.
Submit
What one submit must guarantee
Store first, answer second
The client may send the same submit twice, because the answer was lost. A key chosen by the client makes both submits give the same task. The full treatment is idempotency.
Failure
What happens when it goes wrong
After one failed attempt
Delay before retry n
Six hard problems and the requirement for each
| Problem | What happens | Requirement |
|---|---|---|
| Exactly once | A network failure causes a second run or a missed one | At-least-once, plus handlers that detect repeats |
| Clocks | Machines disagree, so tasks fire early or late | Synchronised clocks, one clock decides, a tolerance |
| Starvation | Low priority never runs | Aging, or capacity reserved for each level |
| Hot partitions | One type or customer fills a queue | Limits for each tenant, work stealing, fair sharing |
| Zombie tasks | Running for ever after a crash | Heartbeat and lease; take it back when it expires |
| Cascades | A failing dependency causes a storm of retries | Circuit breaker, growing delays with jitter, limited retry rate |
Order
Priority without starvation
Which waiting task is next?
Do not promise an order that nobody needs. Tasks of one customer may need to be in order. Tasks of different customers almost never do, and global order would force one lane for everybody.
Numbers
How much: a capacity estimate
Our example is a school message service. Assumptions: 10 million tasks a day, 2 seconds for each, peak 3 times the average, 1 KB a task, kept for 30 days.
| Question | Arithmetic | Answer |
|---|---|---|
| Average rate | 10,000,000 / 100,000 | 100 tasks/s |
| Peak rate | 100 x 3 | 300 tasks/s |
| Busy slots at peak | 300 x 2 s | 600 |
| Slots at 70% use | 600 / 0.7 | 858 |
| Workers, 10 slots each | 858 / 10 | 86 |
| Stored a day | 10,000,000 x 1 KB | 10 GB |
| Stored, 30 days | 10 GB x 30 | 300 GB before copies |
| State changes at peak | 300 x 3 | 900 writes/s |
Each number leads to a decision
The nine o'clock spike
Rules
What callers must agree to
Do
- Make handlers idempotent
- Grow the delay between retries
- Set a timeout for every task
- Store before acknowledging
- Watch depth and age
Do not
- Assume exactly one run
- Retry without a limit
- Put large payloads in the task: store the file, send a reference
- Depend on order unless it was promised
- Skip validation at submit
Summary
The whole topic in one minute.
Functional requirements come in four groups: submit, execute, manage and handle failure. Around a task sit an id, a payload, a time, a priority, dependencies, a timeout and a retry policy.
The promises are: an accepted task is not lost, it starts within a stated time, and it runs at least once, so handlers must be idempotent. Say each as a number, then turn tasks a day into tasks a second, busy slots and stored bytes.
- Four groups: submit, execute, manage, handle failure.
- Acknowledged means stored. Say it as a rule, not as a percentage.
- At-least-once running plus idempotent handlers gives an exactly-once effect.
- A due time is the earliest start. Promise a start latency and measure it.
- Every task has a timeout, a limited number of attempts and a place to go when they are used up.
- Estimate busy slots as rate times duration, and look at the spike on the full hour.