AlgoViz

Requirements of a task scheduler

medium 26 min

A 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

0:00 / 3:42

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

  1. 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.

  2. October 2014

    Airflow is started at Airbnb by Maxime Beauchemin. Tasks now form graphs, where one runs after another.

  3. 7 January 2016

    PostgreSQL 9.5 adds SKIP LOCKED, which lets many workers take different rows from one table.

  4. April 2021

    CronJob becomes generally available in Kubernetes 1.21: cron for a cluster.

  5. 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.

Step 1 of 3

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.

Six decisions before the first chore
CHORESFeed hensFetch eggsMend gate

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

Write down the allowed moves. A completed task must never go back to running.

What one task carries

FieldExampleWhy
Ida UUIDTo ask about it later
Type and payloadsend email, with a referenceWhat to do. Keep it small
Due timeFriday 09:00 UTCWhen it may start
Prioritylow, medium, high, criticalWho goes first
Dependenciesafter the exportA before B
Timeout30 secondsWhen to give up on one attempt
Retry policy3 retries, doubling from 1 sWhat to do after a failure
Idempotency keyorder 42, receiptSo that a repeated submit makes one task

Inside the promise, outside the promise

Client programs send a task to the API of the scheduler. The API writes it to the task store. A dispatcher reads due tasks and hands them to a worker. The mail service that the worker calls is outside the system.
We promise to run the handler. What the mail service does with the request is not ours.

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. 1

    Submit

    Accept payload, priority and time. Validate first. Return a unique id at once. Support one-time, delayed and recurring tasks.

  2. 2

    Execute

    Run on available workers, in priority order, after dependencies, with a timeout for each attempt.

  3. 3

    Manage

    Cancel, pause, resume. Show status and history. List by status, type and date.

  4. 4

    Handle failure

    Retry by policy with growing delays, move exhausted tasks to a dead-letter queue, and tell someone.

The API

RequestMeaningAnswer
POST /tasksSubmit202 and an id
GET /tasks/{id}Status and history200
DELETE /tasks/{id}Cancel202, or 409 if it is done
GET /tasks with filtersList, page by page200 and a cursor
POST /schedulesCreate a recurring task201
POST /queues/{name}/pauseStop taking new work200
202 means accepted, not done. Filters for lists are the topic search and filtering.

Promises

How well it must do it

Service level objectives

QualityTargetHow it is measured
Submit latencyp50 50 ms, p99 200 msAPI call to acknowledgement
Start latencyp99 under 5 sDue time to start of the first attempt
Success rateOver 99.9%Completed tasks of all finished tasks
Availability99.99%Successful submits of all submits
DurabilityNo acknowledged task lostReconcile accepted against finished
ThroughputA number from your trafficFinished tasks a second
Our example targets. Measure start latency apart from run time: the scheduler owns the first, the handler owns the second.

Why five nines of durability is far too weak

10,000,000 tasks a day×(1−0.99999)=100 lost tasks every day10{,}000{,}000 \text{ tasks a day} \times (1 - 0.99999) = 100 \text{ lost tasks every day}
At 100,000 tasks a second it would be one lost task each second. Write the promise as a rule (acknowledged means stored on two machines) and not as a percentage.

What 99.99% availability leaves

365×24×60 min×0.0001=52.6 minutes a year365 \times 24 \times 60 \text{ min} \times 0.0001 = 52.6 \text{ minutes a year}
Workers can be down longer than that without breaking this promise, as long as submits are accepted and tasks start late rather than never.

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. 1

    Not before

    A due time is the earliest moment. Nothing can promise the exact moment, because workers may be busy.

  2. 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. 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. 4

    Overlap

    The run of 02:00 is still going at 03:00. Forbid, allow or replace.

  5. 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

If the process dies after the save, the task still exists. If it dies before the save, the client got no answer and tries again with the same key.

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

A wrong address never becomes right. Retry only errors that may pass.

Delay before retry n

dn=min⁡(dmax,;d0×2 n)d0=1 s:;1,2,4,8,…d_n = \min(d_{max},; d_0 \times 2^{\,n}) \qquad d_0 = 1\text{ s}: ; 1, 2, 4, 8, \ldots
A linear policy uses d0 x (n + 1). In both, choose a random time inside the delay, so that a thousand failed tasks do not return together. More in retries.

Six hard problems and the requirement for each

ProblemWhat happensRequirement
Exactly onceA network failure causes a second run or a missed oneAt-least-once, plus handlers that detect repeats
ClocksMachines disagree, so tasks fire early or lateSynchronised clocks, one clock decides, a tolerance
StarvationLow priority never runsAging, or capacity reserved for each level
Hot partitionsOne type or customer fills a queueLimits for each tenant, work stealing, fair sharing
Zombie tasksRunning for ever after a crashHeartbeat and lease; take it back when it expires
CascadesA failing dependency causes a storm of retriesCircuit breaker, growing delays with jitter, limited retry rate

Order

Priority without starvation

Which waiting task is next?

With one point for every minute of waiting, a low task overtakes a new high one in the end. More about it in priority queues.

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.

QuestionArithmeticAnswer
Average rate10,000,000 / 100,000100 tasks/s
Peak rate100 x 3300 tasks/s
Busy slots at peak300 x 2 s600
Slots at 70% use600 / 0.7858
Workers, 10 slots each858 / 1086
Stored a day10,000,000 x 1 KB10 GB
Stored, 30 days10 GB x 30300 GB before copies
State changes at peak300 x 3900 writes/s
Three writes for each task: saved, running, completed. One good database can do 900 small writes a second, so one is enough to begin with.

Each number leads to a decision

The spike matters more than the average.

The nine o'clock spike

1,000,0005 s=200,000/s1,000,000600 s≈1,667/s\frac{1{,}000{,}000}{5\text{ s}} = 200{,}000\text{/s} \qquad \frac{1{,}000{,}000}{600\text{ s}} \approx 1{,}667\text{/s}
People choose round times. Allowing a ten-minute window makes the same work 120 times easier. EventBridge Scheduler calls this a flexible time window.

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.

Sources