Inside a distributed task scheduler
hard 30 minHow a scheduler finds due tasks, gives each to one worker, survives crashes at every step and grows: a store that is the truth, a claim with a lease, tokens that stop late workers, and partitions.
See it run
Follow a task through the pipeline, then break it at each step.
Operations
The pipeline
Ten steps through database, due set and queue.
Step 1 of 10
Submit
t1, due 10:00
The client calls the submit service.
Step 1: Submit
def submit(task): db.save(task) # truth redis.zadd("due", {task.id: task.due})def dispatch(): ids = redis.zrange("due", 0, now(), byscore=True, num=100) for i in ids: kafka.send(topic(i), i) # send first redis.zrem("due", i) # remove seconddef work(i): c = db.claim(i) # lease and token if c is None: return try: r = run(c.task, c.timeout) db.complete(i, c.token, r) except Exception: due = db.retry_or_bury(i, c.token) if due: redis.zadd("due", {i: due})- You get
- High rates
- You pay
- Two more systems, and gaps between them
Start the interview with one database. Add this only when a number asks for it.
In the real world
The same inside a distributed task scheduler doing real jobs. Pick one and step through it.
The queue grows although workers were added.
Step 1 of 3
Lag
Add workers?
Ten workers read ten partitions and cannot keep up.
Step 1: Lag
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Read, then write
criticalTwo workers read the same scheduled task and both run it.
Wrongif task.status == "scheduled": task.status = "running"RightUPDATE tasks SET status = 'running'WHERE id = 1 AND status = 'scheduled'A lock without a token
criticalThe lock expires during a pause, and the late worker overwrites the new result.
Wrongredis.set(lock, "1", nx=True, px=30000)Rightid, token = claim(now)settle(id, token)Returning failed when the lock is taken
majorAnother worker is running the task. Counting this as a failure uses up its attempts.
Wrongif not locked: return handle_failure(task)Rightif claim is None: return # nothing to doA negative partition
minorIn Java, Math.abs of the smallest int is still negative.
Wrongabs(task_id.hashCode()) % 10RightfloorMod(task_id.hashCode(), 10)
Interview tips
How to explain it
- The row is the truth.
- Claim, lease, token.
- Sweeper for the gaps.
Memory trick: SCHED
- Submit, Cache by time.
- Hand off, Execute.
- Done or retry.
Draw first
- One database and workers.
- Then say at which number it stops.
Watch out
- More consumers than partitions.
- Sleeping after a full batch.
- Timeouts that do not stop.