AlgoViz

Inside a distributed task scheduler

hard 30 min

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

Video lesson · Chapter 1 of 5

Follow one timed lighting cue through the theater

0:00 / 3:34

Theory

Read or listen first. About 2 min.

What it is

A distributed task scheduler has four jobs: keep tasks, find the ones that are due, hand each one to a worker, and settle the result. Each job can be a separate service, and each can crash on its own.

The heart is the claim. A worker, or a dispatcher for it, changes a task from scheduled to running in one atomic step and receives a lease: the right to run it until a time. If the lease runs out, the task can be claimed again.

Why it exists

Work is lost in the gaps between steps. A task taken out of one system and not yet put into the next exists nowhere. A good design has no such moment, or has a repair that finds it.

Work is doubled for the same reason. A slow worker looks exactly like a dead one, so its task is given away while it still runs. A token decides whose result counts.

A short history

  1. 13 July 2006

    Amazon SQS goes into production. A message that was received is hidden for a time and comes back if it is not deleted: a lease for tasks.

  2. 2010

    Google describes Percolator, where small tasks start from changes in data and replace a large batch system for the web index.

  3. 7 January 2016

    PostgreSQL 9.5 adds SKIP LOCKED, so many workers can claim rows from one table without waiting for each other.

  4. April 2021

    The CronJob of Kubernetes becomes generally available in version 1.21.

Words to know

Claim
The atomic step that gives a due task to one worker.
Lease
The claim's end time. It can be extended by heartbeats.
Fencing token
A number that grows with every claim. A result with an old number is refused.
Dispatcher
The part that finds due tasks. Often just called the scheduler.
Reaper
The part that returns tasks whose lease has expired.
Bucket
A fixed slice of the tasks, owned by one dispatcher at a time.
Dead-letter queue
Where tasks go when attempts are used up.

How it works

Step through the idea, or press Play.

Step 1 of 3

Keep. Rows in a replicated database

Understand it

Start here

The cue board in a theatre

In a theatre every effect has a card with a time: rain, door, moon. Stagehands take cards from the board. They do not own a card. They borrow it for two minutes.

Cards on lease
7:05CUESRain7:10Door7:20Moon7:30

What the theatre wants from the board is the topic Requirements of a task scheduler.

Version 1

One database and some workers

Begin here. At 300 tasks a second this is enough, and it has the fewest ways to fail.

The whole scheduler, first version

Clients call the submit service, which writes tasks to PostgreSQL. Workers claim due tasks from PostgreSQL and write the results back to it.
No dispatcher and no queue. The workers pull from the table.
SQL
CREATE INDEX due ON tasks (due_at) WHERE status = 'scheduled';-- claim up to 100 due tasks; rows another worker is claiming are skippedUPDATE tasks SET status = 'running',       lease_until = now() + interval '30 seconds',       token = token + 1WHERE id IN (  SELECT id FROM tasks  WHERE status = 'scheduled' AND due_at <= now()  ORDER BY priority DESC, due_at  LIMIT 100  FOR UPDATE SKIP LOCKED)RETURNING id, token, payload;-- settle: only the current token may do itUPDATE tasks SET status = 'completed'WHERE id = $1 AND token = $2 AND status = 'running';
The index holds only waiting tasks, so it stays small although millions of old tasks are kept. The database clock decides for everybody. To serve the order by priority, put priority first in that index.

Claim, run, settle

Zero rows changed means the claim was lost. The worker then drops its result.

Parts

The four services

ServiceIts workGrows by
SubmitValidate, give an id, store, answerMore copies behind a load balancer; it has no state
DispatcherFind due tasks, claim, hand outBuckets, each with one owner
WorkerRun the handler with a timeout, heartbeat, settle, retryMore workers, pulled work
Task storeTask, attempts, history, result; find work after a crashReplicas, then shards
Ids are UUIDs or time-ordered ids. Attempt counts live in the store, never in a worker's memory.
  • Find

    Read the first rows of the due index every 100 ms to 1 s.

  • Claim

    One atomic change. Two workers cannot both win.

  • Lease

    30 seconds, extended every 10.

  • Token

    Grows with every claim.

  • Retry

    A later due time on the same row.

  • Dead letter

    Kept and shown, never deleted quietly.

Lease

Why a lock alone is not enough

A common design takes a lock in Redis with an expiry before it runs the task. It helps against duplicates, and it has three holes. The lock can expire while the handler still runs. A worker that fails keeps the lock until it expires, so the retry is refused. And nobody checks the lock when the result is written.

A pause longer than the lease

The store refuses the late result. The handler's own effect needs a key as well: see idempotency.

Choose the lease

lease≥3×heartbeat30 s=3×10 s\text{lease} \ge 3 \times \text{heartbeat} \qquad 30 \text{ s} = 3 \times 10 \text{ s}
Two lost heartbeats are tolerated. A crashed worker delays its task by at most 30 seconds. A task of any length works, because the lease is extended. SQS calls it visibility timeout: 30 seconds by default and at most 12 hours from the first receive.

Version 2

Three stores: truth, time, distribution

The pipeline for high rates

Clients call the submit service. It writes the task to PostgreSQL and its due time to Redis. The dispatcher reads due ids from Redis and sends the tasks to Kafka. Workers consume from Kafka and write results to PostgreSQL.
PostgreSQL is the truth. Redis and Kafka can be rebuilt from it. Kubernetes or any other manager keeps the workers running.

What lives where

StoreHoldsRole
PostgreSQLTask and payload, history, attempts, resultsSource of truth
RedisSorted set by due time, rate counters, short locksHot path
KafkaTasks ready to run, event streamDistribution to many workers
Keep the dead letters in the source of truth, with a status. A list in memory is a poor place for the tasks you must not lose.

One task through the pipeline

  1. 1

    Submit

    The client calls the gateway, which calls the submit service.

  2. 2

    Persist

    The row is committed and replicated.

  3. 3

    Index by time

    ZADD due <time> <id>. If this step is lost, the sweeper adds it later.

  4. 4

    Poll

    The dispatcher asks for ids with a time up to now.

  5. 5

    Dispatch

    It sends the task to Kafka, and removes the id only after Kafka confirmed.

  6. 6

    Consume

    A worker gets it from its partition.

  7. 7

    Claim

    It claims the row, with lease and token. A second copy of the message finds the row running or done.

  8. 8

    Execute

    The handler runs with a timeout.

  9. 9

    Store the result

    Status and result, checked by the token.

  10. 10

    Retry

    On failure: later due time in the row and in the sorted set.

The sorted set

CommandUseCost
ZADDAdd an id with its due timeO(log n)
ZRANGE by score, with limitThe first ids that are dueO(log n + m)
ZREMRemove a dispatched idO(log n) for one

Gaps

Crash after every step

Crash afterStateRepair
Row committed, not in RedisTask never foundSweeper: scheduled rows that are overdue
Removed from Redis, not in KafkaTask lost if removed firstSend first, remove second; duplicates are harmless
Sent to Kafka, not markedSent twiceThe claim lets one win
Effect done, not settledRuns againIdempotency key in the handler
Worker dies in the handlerLease expiresReaper makes it scheduled again
Redis loses its dataNo due indexRebuild from the rows
Walk through this table in an interview. It shows that you know where work disappears.

The sweeper closes the gaps

One slow, simple job makes a fast, leaky path safe.

Timing

Recurring tasks

A schedule is a rule. A task is one run of it. When the dispatcher claims a run, it inserts the next run in the same transaction, with the id made from schedule and time. If two dispatchers try, the second insert meets the same id and does nothing.

Next run from the planned time

  • 07:00, 08:00, 09:00, whatever the delay
  • Missed runs can be counted
  • Id: schedule plus planned time

Next run from now

  • Each delay is added: 07:00, 08:02, 09:05
  • Missed runs are invisible
  • Right only for "every hour after the last one ended"

Scale

Where each part stops

The polling loop has a ceiling

100 taskspass×10 passess=1,000 tasks/s\frac{100 \text{ tasks}}{\text{pass}} \times \frac{10 \text{ passes}}{\text{s}} = 1{,}000 \text{ tasks/s}
A loop that fetches 100 and then sleeps 100 ms cannot do more, however strong the machine. Do not sleep when a batch was full, raise the batch, and then split into buckets.

How each part grows

PartStrategyWatch
SubmitMore instancesCPU, request rate
DispatcherOne leader, then bucketsAge of the oldest due task
WorkersMore consumersLag, run time
RedisCluster; one sorted set for each bucketMemory, operations
PostgreSQLPartition by day, then shard by idWrites, index size
One sorted set is one key and lives on one node, so a Redis cluster helps only after the set is cut into buckets. More in sharding.

Many dispatchers, no shared work

Dispatcher A owns buckets 0 to 7 and dispatcher B owns buckets 8 to 15. Both get their ownership from etcd and both send to worker queues for high and normal priority.
Bucket = hash of the task id, modulo 16. An owner holds a lease on its buckets.

Capacity at 100,000 tasks a second, half a second each

QuestionArithmeticAnswer
Busy slots100,000 x 0.550,000
Workers, 10 slots, no spare50,000 / 105,000
Workers at 70% use50,000 / 0.7 / 107,143
Row writes a second100,000 x 3300,000, so shards
Dispatchers at 5,000/s each100,000 / 5,00020
Tasks a day100,000 x 86,4008.64 billion
The last row is the sanity check. Few systems have that many. Ask before you design for it. 5,000 a second for one dispatcher is an assumption to be measured.

Scaling rules to start from

IfThen
Queue depth over 10,000Add workers
Oldest due task older than 1 sAdd workers, or dispatchers if slots are free
Submit CPU over 80% for 5 minutesAdd submit instances
Queue depth under 100 for 10 minutesRemove workers, letting running tasks finish
The numbers are examples. Age is better than depth: 10,000 short tasks are nothing, 100 long ones may be an hour.

Choices

Trade-offs

ChoiceOne sideOther sideStart with
DeliveryAt-least-once: simple, durable, needs idempotent handlersExactly-once effect by transaction: only inside one storeAt-least-once
DistributionPush: low latency, must know who is freePull: workers take what they can, small delayPull
DispatcherOne leader: simple, limitedBuckets: more throughput, ownership to manageOne leader
Partition byTask type: a hot type blocks its laneTask id: even, no orderTask id
Type order is rarely needed. If tasks of one customer must be in order, use the customer id as key.

Which version do I need?

The threshold is a rule of thumb. Measure your own database.

Leaders and bucket owners are chosen with a lock service that gives leases. An old owner that wakes up may still dispatch, and the claim on the row makes that harmless.

Rules

Do and do not

Do

  • Commit the row before anything else
  • Claim with lease and token
  • Extend the lease while running
  • Grow the delay between retries, with jitter
  • Watch age, depth and dead letters

Do not

  • Put large payloads in Redis or Kafka: store a reference
  • Retry without a limit
  • Run without a timeout: one stuck handler holds a slot for ever
  • Wait without end for a lock
  • Depend on order across types
  • Run one dispatcher without a standby

Summary

The whole topic in one minute.

Start with one database. Tasks are rows, an index orders them by due time, workers claim a batch with a lease and a token, and a reaper returns expired leases. It has no gap between systems and reaches far.

Add systems for a reason. A sorted set in Redis gives a faster due index, a log or queue gives many workers, and buckets give many dispatchers. Each new step adds a gap, and the repair job that closes it belongs to the design.

  • The row is the truth. Everything else can be rebuilt from it.
  • Claim in one atomic step, with a lease and a growing token.
  • Send first, remove second. A duplicate is harmless, a gap is not.
  • A sweeper finds overdue and expired tasks.
  • Priority is a separate queue, not an amount added to the time.
  • Partitions limit consumers, and a polling loop has a ceiling you can calculate.

Sources