Skip to content
SD-23 · Back to the write-up

Design a Job Scheduler

An index finds due jobs, one leased scheduler per shard enqueues them, and leased workers run each one at least once with an idempotency key.

Follow a request

Clients
Control
Scheduling
Running
ClientTeam or service
API serversStateless
Job store16 shards
CoordinatorShard leases
SchedulerOne per shard
Run queueDue runs
WorkersAutoscaled
TargetTenant endpoint
Dead lettersFailed runs
1scheduler → coord · renew lease, shard 7Every 3 seconds the scheduler renews its lease on shard 7 and learns its fencing token, 41.1 / 4

The numbers, at a glance

The top of the minuteRuns starting in one second, at 2,300/s average
For every 16 shards……exactly one scheduler owns each
4 standbys16 lease holders
Most runs are shortAverage 500 ms; a few run for hours
So heartbeats and leases matter for a few runs, but every run pays for them.

A run, in order

The scheduler is done at step 4. Steps 5 to 10 are the worker’s, and repeat if a lease runs out.

Coordinator
Scheduler
Job store
Run queue
Worker
API server
Target
1 renew lease (token 41)
2 jobs due in next 30 s
3 claim run + advance
4 enqueue run
5 take (30 s lease)
6 POST + Idempotency-Key
7 heartbeat
8 200 OK
9 succeeded (token 1)
10 write if token matches
RequestResponseAsync, does not block

Finding due runs

The decision this question is really about.

Scan the table
Breaks early
every second
scan 50M rows
runs late
+ Simple.− 25 s per pass over 50M rows.
Timer wheel only
Use as a buffer
load all jobs
in-memory wheel
restart = rebuild
+ Exact ticks.− 50M timers lost on restart.
Index + 30 s timer
Our pick
index next_run_at
next 30 s → timerclaim + advance
queue → workers
+ Durable and on time.− A query per shard each second.

How it grows

Add a box only when a number forces you to. Highlighted boxes are new at each stage.

Stage 1 · ≈ 100 runs/sMake it work
Clients
API serverScheduler
DatabaseTargets
One scheduler scans the table and runs each job itself.
Stage 2 · ≈ 500 runs/sQueue the runs
Clients
Load balancerAPI × N
Job store + indexScheduler
Run queueWorkers
Index due times; workers run jobs from a queue.
Stage 3 · ≈ 20,000 runs/sShard and spread
Clients
Load balancerAPI × N
Job store × 16Schedulers × 16Coordinator
Run queueWorkers
Jitter the :00 spike; 16 shards, each with a leased scheduler.
Stage 4 · 20,000 runs/s, safelyRun it safely
Clients
Load balancerAPI × N
Job store × 16Schedulers × 16Coordinator
Run queue + leasesWorkersDead letters
Run leases with fencing, idempotency keys, retries, dead letters, quotas.
Was this walkthrough useful?Your vote tells us what to improve next.