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.
See it run
One task from submit to done, and the rules for order, failure and capacity.
Operations
Life of one task
Eight steps from the request to the result. Watch when the client gets its answer.
Step 1 of 8
Submit
A new task
The client sends payload, priority and time.
Step 1: Submit
def submit(task): validate(task) task.id = new_id() store.save(task) # durable first queue.put(task) return task.id # 202, not done yetdef work(task): try: run(task, timeout=task.timeout) store.mark(task, "completed") except Exception as e: retry_or_bury(task, e)- Promise
- Accepted means stored
- Price
- One write before the answer
Say out loud what 202 means: stored, not done.
In the real world
The same requirements of a task scheduler doing real jobs. Pick one and step through it.
One million reminders are due at 09:00.
Step 1 of 4
08:59
- Workers busy
- 20%
Quiet
Everything is calm. The tasks are stored and waiting.
Step 1: 08:59
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Answering before storing
criticalA crash between the answer and the write loses a task that the client believes in.
Wrongreply(202, task.id)store.save(task)Rightstore.save(task)reply(202, task.id)No timeout
criticalOne handler that hangs holds its slot for ever. Enough of them stop the whole system.
Wrongrun(task)Rightrun(task, timeout=task.timeout)Retrying everything for ever
majorA task with a wrong address never succeeds and takes capacity from others.
Wrongwhile True: try_again(task)Rightif permanent(error) or attempts > limit: dead_letter(task)Strict priority only
majorAs long as urgent tasks arrive, low ones wait without limit.
Wrongmax(due, key=lambda t: t.priority)Rightmax(due, key=lambda t: t.priority + waited(t) // 60)
Interview tips
How to explain it
- Store first, answer second.
- At least once, so handlers are idempotent.
- Start latency is ours, run time is the handler's.
Memory trick: TASKS
- Throughput and Availability.
- Scalability.
- Kinetics: latency.
- Safety: nothing accepted is lost.
Questions that score
- May it run twice?
- How late is too late?
- What if a run is missed or overlaps?
Watch out
- Percentages for durability.
- Large payloads in tasks.
- Everybody choosing 09:00.