Distributed scheduler
Other services register work to happen later: send this reminder in 30 minutes, expire this order in 15, retry this webhook with backoff. Millions of jobs are pending at any moment and most are far in the future.
Envelope20M jobs pending · fires within 1 s of due time · never runs twice
What the design must do
- Due jobs found without scanning millions of pending rows
- Exactly one worker executes a given job at a given time
- A worker that dies mid-execution does not lose the job
- Every pending job survives a restart of every component
The worked envelope
Assumed. 20M jobs pending, spread over 30 days but heavily clustered on round times, must fire within one second of due.
| Pending state | 20M × 200 B = 4 GB |
| Average fire rate | 20M ÷ 2.6M s ≈ 8/s |
| Clustered peak | everyone schedules 09:00 → 100k in one second |
| Burst ratio | 12,000× the average |
| Naive poll | scanning 20M rows/s: impossible |
| Indexed poll | range scan of the next 1,000 by due time: trivial |
What the numbers decide. The average is eight jobs a second and the peak is a hundred thousand. A twelve-thousand-fold burst ratio is not a detail to handle later — it is the defining property of the workload, and it comes from human behaviour: people schedule things on the hour, never at 09:07:23.
So sizing anything for the average is wrong, and firing jobs directly from the scheduler is wrong, because 100k executions in one second is not something you can absorb. The scheduler's job is to detect due-ness cheaply and hand off; the queue behind it turns the spike into a drain. And the second pair of rows makes the storage decision for you: it is only impossible if you scan, and it is trivial if you index by due time.
The decisions, and what each one costs
An index ordered by due time; poll the next N due, never scan
- Because
- Only the earliest jobs matter at any instant, so the query is a bounded range scan regardless of whether 20M or 200M jobs are pending
- The cost
- The index must be maintained on every insert and reschedule, which is the cost of 20M pending rows
- Rejected
- Scanning for due jobs on a timer, which passes review at 10k rows and melts at 20M
Scheduler detects due-ness and enqueues; workers execute
- Because
- A 12,000× burst cannot be executed as it arrives, and separating detection from execution lets the queue absorb the spike
- The cost
- Firing "within one second" now means enqueued within one second — the execution may be later under burst
- Rejected
- Executing inline in the scheduler, which makes 09:00 an outage every day
Claim with a lease that expires, not a boolean flag
- Because
- Nothing can distinguish a dead worker from a slow one, so recovery has to be time-based rather than event-based
- The cost
- A slow-but-alive worker’s job gets picked up by someone else, so every handler must be idempotent
- Rejected
- A claimed flag with no expiry, where one crashed worker strands a job until a human notices
At-least-once execution, idempotency pushed to the handler
- Because
- Exactly-once across a claim, an execution and an acknowledgement does not exist; pretending otherwise hides the duplicate rather than preventing it
- The cost
- Every job author has to think about repeat execution, which is a real tax on the people using this system
- Rejected
- Two-phase commit between the scheduler and each handler, which couples them and still fails
Components in the reference design
- Client
- Browser or mobile app
- API Gateway
- Auth, routing, quota enforcement
- App Service
- Stateless business logic
- SQL DB
- Relational, ACID, joins
- Queue
- Work distribution, one consumer per message
- Worker
- Async consumer, background jobs
What not to draw
- Cache — A cache is not a job store. Jobs must survive a restart, and a store that evicts under memory pressure will silently drop the reminder nobody notices is missing.
The reference design
Finding what is due. Only the earliest jobs matter at any instant, so the access pattern is "give me everything past its due time" over an index on due_at — not a scan. Twenty million pending rows with a handful ready is exactly the selectivity an index is for (Lesson 3.02). The version that scans works perfectly in testing and melts at a million rows.
The claim must be atomic. Two workers poll at the same instant and both see the same due job. Reading it and then updating its status is Lesson 2.05's check-then-act, now spread across machines — both read pending, both write claimed, both run. The claim has to be one indivisible operation:
UPDATE jobs SET claimed_by = :worker, lease_until = now() + interval '60 s' WHERE id = :job AND (claimed_by IS NULL OR lease_until < now())
Exactly one worker gets a row back. A mutex cannot help here — it orders threads within one process, and these are different machines.
Leases, not flags. Nothing can distinguish a dead worker from a slow one, so recovery must be time-based: the claim carries an expiry, and an unrenewed lease returns the job to the pending set. The consequence is that a job can run twice — once by the worker that was merely slow — which is why every handler must be idempotent. At-least-once is what this design buys, and it is the only thing on offer.
Why a queue as well as a database. The database is the durable schedule; the queue is the dispatch mechanism that spreads due work across a worker pool without every worker polling the same rows. Keeping them separate means the scheduler scales on storage and the executors scale on throughput.
The thundering herd nobody plans for. Thousands of jobs scheduled for exactly 09:00 all fire together. Jitter the due times when you enqueue, or the scheduler becomes a periodic self-inflicted load test.