Design: distributed job scheduler
Store each job's next run time; sharded schedulers claim due jobs and enqueue a run with a deterministic id; workers execute under heartbeated leases; delivery is at-least-once, so every job must be idempotent.
Fundamentals you'll use
How it works
- Store next_run_at per job; sharded schedulers poll due jobs with
FOR UPDATE SKIP LOCKED. - Enqueue each run with a deterministic run_id (job plus scheduled time), so double enqueues are no-ops.
- Workers hold a lease and heartbeat; if one crashes, the lease expires and another worker retries.
- Delivery is at-least-once: jobs must be idempotent, using run_id as the side-effect key.
- Spread top-of-hour crons with hashed jitter; retry with exponential backoff, then a dead-letter queue.
Check yourself
Answer to mark it learned; your answers aren't scored.
A monthly job charges each subscription. After a worker fleet restart, some customers were charged twice. Workers mark a run DONE only after the charge succeeds. What's the right fix?
Go deeper
Full explanation
Requirements
Functional: register one-off (run_at) and recurring (cron) jobs, run them on time, retry failures, show run history, cancel. Non-functional: never lose a run; start within seconds of the due time; survive scheduler and worker crashes. Assume 100M runs/day ≈ 1.2k/s on average, with spikes at the top of every hour.
API and data model
POST /jobs {schedule | run_at, payload, max_attempts, timeout}jobs(job_id, schedule, next_run_at, bucket), indexed by(bucket, next_run_at)runs(run_id = job_id + scheduled_time, status, attempt, lease_owner, lease_expires_at)
Architecture
- Schedulers each own a set of buckets (
hash(job_id) % N) and poll every second for due jobs withFOR UPDATE SKIP LOCKED. - In one transaction they insert the run (a unique
run_idturns a double enqueue into a no-op) and advancenext_run_atto the next cron tick. - Runs go onto a queue; workers claim one under a lease (say 30 s), heartbeat to extend it, and mark it done.
- A crashed worker stops heartbeating; the lease expires and another worker retries with Retries, backoff & circuit breakers, up to
max_attempts, then a dead-letter queue.
The hard parts
No exactly-once. A worker can finish the work and die before marking it done, so the run repeats: the system is at-least-once. Jobs must be idempotent (Idempotency): pass run_id as the key to every side effect. Where that's impossible, do as Google's cron: it favors skipping a launch over risking a double launch.
Zombie workers. A worker paused past its lease (a GC pause, say) can wake up and write after another worker took over. The attempt number doubles as a fencing token that downstream writes must carry, so stale ones get rejected (Distributed locks and fencing tokens).
The top-of-hour herd. Many crons say 0 * * * *. Spread them by hashing each job into a jitter window, as Google's cron does for its ? syntax.
Code Claim due jobs, then run under a fenced lease
from datetime import datetime
from croniter import croniter
CLAIM = """SELECT job_id, schedule, next_run_at FROM jobs
WHERE bucket = ANY(%s) AND next_run_at <= now()
ORDER BY next_run_at LIMIT 500
FOR UPDATE SKIP LOCKED""" # other schedulers skip these rows instead of waiting
def scheduler_tick(conn, my_buckets):
with conn.transaction():
for job_id, schedule, due in conn.execute(CLAIM, (my_buckets,)).fetchall():
run_id = f"{job_id}:{due.isoformat()}" # same tick -> same id, always
conn.execute("INSERT INTO runs (run_id, job_id, status) VALUES (%s, %s, 'QUEUED') "
"ON CONFLICT (run_id) DO NOTHING", (run_id, job_id))
# from `due`, missed ticks catch up; from now(), they're skipped (a per-job policy)
nxt = croniter(schedule, due).get_next(datetime)
conn.execute("UPDATE jobs SET next_run_at = %s WHERE job_id = %s", (nxt, job_id))
# an outbox relay publishes QUEUED runs, so the commit and the enqueue can't diverge
def work(conn, run_id, payload):
row = conn.execute(
"UPDATE runs SET lease_owner = %s, lease_expires_at = now() + interval '30 s', "
"attempt = attempt + 1 WHERE run_id = %s AND status = 'QUEUED' "
"AND (lease_expires_at IS NULL OR lease_expires_at < now()) RETURNING attempt",
(WORKER_ID, run_id)).fetchone()
if row is None:
return # another worker holds a live lease
fence = row[0] # attempt number = fencing token
with heartbeat(conn, run_id, every_s=10): # extends the lease while we work
execute_job(payload, idempotency_key=run_id, fence=fence)
conn.execute("UPDATE runs SET status = 'DONE' WHERE run_id = %s AND attempt = %s",
(run_id, fence)) # a zombie's late update matches 0 rowsReal example
A billing team schedules "close invoices" for 2M tenants at 0 * * * *. Without jitter, ~2M runs land at :00 and the invoice DB melts; hashed over a 10-minute window, it's ~3.3k runs/s. Worker 7 claims run t4412:2026-11-17T10:00, leases it for 30 s and heartbeats every 10 s. At 10:04 a GC pause freezes it; the lease expires and worker 12 retries as attempt 2. Worker 7 wakes and tries to write, but the invoice service has already seen fence 2 from worker 12 and rejects fence 1. The invoice closes exactly once.
Trade-offs +3 · −3
+ You gain
- Scales out on both axes: buckets spread scheduling and the queue spreads execution.
- No run is lost: state lives in the DB, and expired leases recover crashed workers automatically.
- Deterministic run ids make scheduler retries and failovers safe to repeat.
− You pay
- At-least-once pushes idempotency onto every job author.
- Polling adds up to one poll interval (~1 s) of start delay and constant DB load.
- Lease length is a trade-off: short leases cause false takeovers, long ones slow recovery.
Use it when
Many tenants' recurring or delayed jobs, from thousands to hundreds of millions a day, where a lost run is worse than a late one.
Avoid it when
A handful of jobs: a managed scheduler (EventBridge Scheduler, Cloud Scheduler, Kubernetes CronJob) is enough. Multi-step workflows with branching belong in an orchestrator such as Temporal or Airflow.
Numbers to know 5
- Load (assumed): 100M runs/day ≈ 1.2k/s; if 20% fire in the first minute of each hour, that minute sees ~14k/s (~12×).
- Lease (assumed): 30 s with a heartbeat every 10 s; a crashed worker's run restarts within ~30 s.
- SQS visibility timeout, the same lease idea: 30 s by default, at most 12 h (checked Nov 2026).
- Dropbox's ATF served ~9k async tasks scheduled per second, with at-least-once execution (Nov 2020).
- Retries (assumed): backoff of 1, 2, 4, 8, 16 min spans ~31 min before the dead-letter queue.
Common pitfalls 4
- Assuming exactly-once: a worker that finishes, then dies before acking, runs the job again.
- Random run ids: a scheduler retry after a timeout enqueues the same tick twice.
- A lease shorter than a GC pause or slow call, without fencing: two workers write the same result.
- Instant retries with no cap: a down dependency gets hammered and poison runs clog the queue.
Interview questions 3
Answer out loud first, then reveal.
How do you guarantee a job runs exactly once?Show answer
I don't promise exactly-once execution; I promise at-least-once delivery plus idempotent effects. Runs get a deterministic id, job plus scheduled time, so a duplicate enqueue is a no-op. Workers pass that id as the idempotency key to every side effect, and the lease's fencing token rejects a zombie's late write. For jobs that can't be idempotent, like a newsletter, I'd rather skip a run than double it, as Google's cron does.
A worker is still running when its lease expires. What happens?Show answer
Another worker can claim the run as attempt 2, so two copies may run at once. Three defenses: heartbeats extend the lease while the worker is healthy; the worker re-checks its lease before committing and aborts if it lost it; and downstream writes carry the attempt number as a fencing token, so the stale attempt is rejected. I size the lease at a few heartbeats, like 30 s with 10 s heartbeats.
Every customer schedules their jobs at midnight. How do you cope?Show answer
That's a thundering herd on schedulers, workers and every downstream. I'd let customers opt into a window and hash each job id to a start time inside it, like Google's ? cron syntax; split the midnight time bucket with a hash suffix so it isn't one hot partition; and cap concurrency per tenant and per downstream so the queue absorbs the burst. Workers autoscale on queue age, not CPU.
Deep dive 3
Leases, heartbeats and fencing
A lease is a lock with a deadline: lease_owner plus lease_expires_at, claimed with a conditional update that succeeds only if the run is unleased or the lease expired. The worker heartbeats (every 10 s on a 30 s lease, assumed) to extend it. Short leases recover crashed work fast but risk false takeovers during pauses; long leases are the reverse. Expiry never proves the old holder stopped, so each claim bumps attempt, and downstream writes carry it as a fencing token: the receiver rejects anything lower than the highest it has seen. SQS visibility timeouts are the same idea as a managed service.
Sharding by bucket and by time
One scheduler polling one table is a single point of failure and a throughput ceiling. Hash jobs into fixed buckets (hash(job_id) % 1024) and let schedulers lease ranges of buckets through a coordinator (etcd, ZooKeeper or a DB table); when one dies, its buckets move. For huge volumes of one-off delayed jobs, key storage by time bucket instead, one partition per minute such as due:10:04, so a scheduler reads only the current bucket. The top-of-hour bucket gets hot; split it with a hash suffix (due:10:00:17). SKIP LOCKED lets several schedulers share a bucket without waiting on each other's rows.
Missed runs, retries and the herd
After an outage, decide per job: catch up every missed tick (reports per hour) or skip to the latest (cache refresh). Google's cron generally favors skipping a launch over a double one, since a skip is easier to recover from. Retry failures with exponential backoff and jitter, cap attempts, then park the run in a dead-letter queue and alert its owner; never retry instantly in a loop. Spread start times by hashing each job into its allowed window, and cap concurrency per tenant and per downstream so a burst waits in the queue instead of hitting a database. Autoscale workers on queue age, not CPU.