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.
Video lesson · Chapter 1 of 5
Follow one timed lighting cue through the theater
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
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.
2010
Google describes Percolator, where small tasks start from changes in data and replace a large batch system for the web index.
7 January 2016
PostgreSQL 9.5 adds
SKIP LOCKED, so many workers can claim rows from one table without waiting for each other.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.
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.
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
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';Claim, run, settle
Parts
The four services
| Service | Its work | Grows by |
|---|---|---|
| Submit | Validate, give an id, store, answer | More copies behind a load balancer; it has no state |
| Dispatcher | Find due tasks, claim, hand out | Buckets, each with one owner |
| Worker | Run the handler with a timeout, heartbeat, settle, retry | More workers, pulled work |
| Task store | Task, attempts, history, result; find work after a crash | Replicas, then shards |
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
Choose the lease
Version 2
Three stores: truth, time, distribution
The pipeline for high rates
What lives where
| Store | Holds | Role |
|---|---|---|
| PostgreSQL | Task and payload, history, attempts, results | Source of truth |
| Redis | Sorted set by due time, rate counters, short locks | Hot path |
| Kafka | Tasks ready to run, event stream | Distribution to many workers |
One task through the pipeline
- 1
Submit
The client calls the gateway, which calls the submit service.
- 2
Persist
The row is committed and replicated.
- 3
Index by time
ZADD due <time> <id>. If this step is lost, the sweeper adds it later. - 4
Poll
The dispatcher asks for ids with a time up to now.
- 5
Dispatch
It sends the task to Kafka, and removes the id only after Kafka confirmed.
- 6
Consume
A worker gets it from its partition.
- 7
Claim
It claims the row, with lease and token. A second copy of the message finds the row running or done.
- 8
Execute
The handler runs with a timeout.
- 9
Store the result
Status and result, checked by the token.
- 10
Retry
On failure: later due time in the row and in the sorted set.
The sorted set
| Command | Use | Cost |
|---|---|---|
| ZADD | Add an id with its due time | O(log n) |
| ZRANGE by score, with limit | The first ids that are due | O(log n + m) |
| ZREM | Remove a dispatched id | O(log n) for one |
Gaps
Crash after every step
| Crash after | State | Repair |
|---|---|---|
| Row committed, not in Redis | Task never found | Sweeper: scheduled rows that are overdue |
| Removed from Redis, not in Kafka | Task lost if removed first | Send first, remove second; duplicates are harmless |
| Sent to Kafka, not marked | Sent twice | The claim lets one win |
| Effect done, not settled | Runs again | Idempotency key in the handler |
| Worker dies in the handler | Lease expires | Reaper makes it scheduled again |
| Redis loses its data | No due index | Rebuild from the rows |
The sweeper closes the gaps
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
How each part grows
| Part | Strategy | Watch |
|---|---|---|
| Submit | More instances | CPU, request rate |
| Dispatcher | One leader, then buckets | Age of the oldest due task |
| Workers | More consumers | Lag, run time |
| Redis | Cluster; one sorted set for each bucket | Memory, operations |
| PostgreSQL | Partition by day, then shard by id | Writes, index size |
Many dispatchers, no shared work
Capacity at 100,000 tasks a second, half a second each
| Question | Arithmetic | Answer |
|---|---|---|
| Busy slots | 100,000 x 0.5 | 50,000 |
| Workers, 10 slots, no spare | 50,000 / 10 | 5,000 |
| Workers at 70% use | 50,000 / 0.7 / 10 | 7,143 |
| Row writes a second | 100,000 x 3 | 300,000, so shards |
| Dispatchers at 5,000/s each | 100,000 / 5,000 | 20 |
| Tasks a day | 100,000 x 86,400 | 8.64 billion |
Scaling rules to start from
| If | Then |
|---|---|
| Queue depth over 10,000 | Add workers |
| Oldest due task older than 1 s | Add workers, or dispatchers if slots are free |
| Submit CPU over 80% for 5 minutes | Add submit instances |
| Queue depth under 100 for 10 minutes | Remove workers, letting running tasks finish |
Choices
Trade-offs
| Choice | One side | Other side | Start with |
|---|---|---|---|
| Delivery | At-least-once: simple, durable, needs idempotent handlers | Exactly-once effect by transaction: only inside one store | At-least-once |
| Distribution | Push: low latency, must know who is free | Pull: workers take what they can, small delay | Pull |
| Dispatcher | One leader: simple, limited | Buckets: more throughput, ownership to manage | One leader |
| Partition by | Task type: a hot type blocks its lane | Task id: even, no order | Task id |
Which version do I need?
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.