Design a Job Scheduler
How a distributed job scheduler stores, finds, dispatches and retries delayed and recurring jobs, and what interviewers ask about at-least-once execution.
On this page
A job scheduler is a shared service that lets other teams say "run this job at this time" or "run this job on this schedule", for example a reminder email in 24 hours, a retry in 5 minutes or a report every day at 06:00. The scheduler stores each job durably and makes sure a worker starts it close to the requested time. Without one, each team keeps timers on its own servers, and those jobs are lost when a server restarts.
The question is hard because of three things: finding the few jobs that are due among millions that are waiting, giving each due job to one worker even though workers crash and pause, and getting the effect of "exactly once" from a system that can only promise to run a job at least once. The steps follow A Framework for Any Design.
Clarify the problem
Design a distributed job scheduler.
Do you want one-off jobs, recurring cron schedules, or both? And does the scheduler run the job's code, or does it hand the job to workers that each team runs?
Both kinds of jobs. Teams run their own workers, and you store, schedule and dispatch the jobs.
How many jobs do we expect, and how precise does the start time have to be?
About 100 million runs a day and a million recurring schedules. Starting within a few seconds of the due time is fine.
Then I will promise three things. An accepted job is never lost, it starts within 10 seconds of its due time under normal load, and it runs at least once. Because a job can run twice, handlers have to be idempotent.
- Functional requirements: schedule one-off and recurring (cron) jobs, cancel a job, show its status and attempts, and retry a failed job with backoff up to a limit.
- Non-functional requirements: no accepted job is lost, jobs start within 10 seconds of their due time under normal load, execution is at least once, and no single machine can stop the scheduling.
- Out of scope: running the job code, job dependencies and workflows, and priorities.
Estimate the scale
- Job runs: 100 million a day divided by 86,400 seconds is about 1,200 runs a second on average.
- Writes: each run is written four times (created, enqueued, claimed and finished), which is about 4,800 writes a second on average. That is more than one primary should carry once peaks and replication are included, so the store is sharded.
- Waiting jobs: assume 10% of jobs are scheduled a week ahead and the rest within the hour. Then 100 million × 0.1 × 7 days = 70 million jobs are waiting at any moment, which is 70 GB at 1 KB each.
- The burst: if 20% of the million schedules say "every hour, on the hour", then 200,000 jobs become due in the same second at every :00.
For the worker fleet, assume each job takes 2 seconds and a worker runs 10 jobs at a time. The average load is 1,200 × 2 = 2,400 jobs running at once, which is 240 workers, and with 50% headroom 360 workers, which can start 360 × 10 ÷ 2 = 1,800 jobs a second.
At 10:00:00, 200,000 hourly jobs become due at once. Ignoring other traffic, how long until the last one starts?
- 200,000 jobs due at the same second
- The fleet runs 1,800 jobs a second at full speed
Show the working
- 200,000 ÷ 1,800 per second ≈ 111 seconds, almost 2 minutes
Estimate 111 seconds (anything from 40 seconds to 5 minutes is a good answer)
That breaks the 10-second promise for most of the burst. Meeting it would need 20,000 starts a second, about 11 times the fleet, and that fleet would sit idle for the rest of the hour.
Write the calls for scheduling, cancelling and inspecting a job, and the calls a worker uses to get work and report the result. Decide whether workers pull jobs or the scheduler pushes them.
Compare with a model answer
There are calls to create, cancel and read a job and to create a schedule. Workers pull jobs: a worker leases a job, sends heartbeats while it runs, and reports the result together with its attempt number.
Define the API Optional
Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.
POST /jobs
body: { "queue": "emails", "payload": {...}, "run_at": "2026-11-15T10:05:20Z",
"max_attempts": 5, "timeout_s": 60,
"idempotency_key": "remind-u42-d15" } (idempotency_key is optional)
201 { "job_id": "j_a8f3c1" }
400 run_at too far in the future, or payload over 64 KB
POST /schedules
body: { "queue": "reports", "cron": "0 6 * * *", "time_zone": "Asia/Tokyo",
"on_overlap": "skip", "on_missed": "run_once" }
201 { "schedule_id": "s_311" }
DELETE /jobs/{id} 200 cancelled 409 already running
GET /jobs/{id} 200 { "status": "running", "attempt": 2, "last_error": "..." }
Worker side:
POST /queues/{q}/lease 200 [ { "job_id", "attempt", "lease_until", "payload" } ]
POST /jobs/{id}/heartbeat body: { "attempt": 2 } 200, or 409 lease lost
POST /jobs/{id}/complete body: { "attempt": 2, "ok": true } 200, or 409 lease lostThe decision to argue is pull instead of push. With push, the scheduler has to track each worker's capacity, and a slow worker backs up into the scheduler. With pull, each worker takes only what it can run, and the backlog waits in the queue. The attempt number in every worker call lets the scheduler reject a worker that has already lost its lease.
Design the job record and its key. Then decide how to make the question "which jobs are due now?" cheap when 70 million jobs are waiting.
Compare with a model answer
The job is stored under its id, and a separate, small "due" index is keyed by shard and by the minute of the run time. A dispatcher then reads only the current minute's partition.
Model the data
jobs -- one row per job, found by id
job_id VARCHAR(64) PRIMARY KEY -- random, or "s_311@2026-11-15T06:00" for a schedule run
shard SMALLINT -- hash(job_id) % 64
queue VARCHAR(64)
payload BLOB -- up to 64 KB; larger payloads go to blob storage
run_at TIMESTAMP
status VARCHAR(12) -- scheduled | enqueued | running | succeeded | cancelled | dead
attempt INT
lease_until TIMESTAMP NULL -- indexed for running jobs, used by the lease sweep
schedule_id VARCHAR(32) NULL
due -- the timer: which job ids are due when
shard SMALLINT
bucket TIMESTAMP -- run_at rounded down to the minute
run_at TIMESTAMP
job_id VARCHAR(64)
PRIMARY KEY ((shard, bucket), run_at, job_id)
schedules
schedule_id, cron, time_zone, queue, payload, on_overlap, on_missed, next_run_atA job and its due rows hash to the same shard, so creating a job is one local transaction. A retry or new run time only adds a due row, and the dispatcher checks the job's status before enqueuing, so stale rows from cancelled or rescheduled jobs are skipped.
Any store with partitions, sorted keys and conditional single-row writes works, for example a sharded relational database. I would pick that, because claims and leases are simple conditional updates there.
Sketch the boxes: where the jobs live, what finds the due jobs, how they reach the workers, and how two scheduler machines avoid scanning the same shard.
Compare with a model answer
An API writes jobs to the sharded store. Dispatchers take ownership of shards through a coordinator, scan the current bucket every second and put the ids of due jobs on ready queues. Workers pull ids from the queues and claim each job in the store.
High-level design
- status
- scheduled
- attempt
- 0
1At 09:05 a service asks for a reminder email at 10:05:20. The job id hashes to shard 17, and the job and its due row in partition (17, 10:05) are written to three replicas before the API answers.
- status
- scheduled
- attempt
- 0
2Dispatcher D2 holds a coordinator lease on shards 16 to 31 and renews it every few seconds, so normally only D2 scans shard 17.
- status
- enqueued
- attempt
- 0
3Every second D2 reads the current minute's partitions. At 10:05:20 it finds the job, a conditional update moves it from
scheduledtoenqueued, and its id is put on theemailsqueue.- status
- running
- attempt
- 1
- lease until
- 10:05:51
4Worker W3 pulls the id and claims the job with a conditional update: status running, attempt 1, lease until 10:05:51. W3 sends the email and then freezes for 40 seconds in a garbage-collection pause, so it sends no heartbeats.
- status
- enqueued
- attempt
- 1
5At 10:05:51 the lease expires. D2's lease sweep finds the job, sets it back to
enqueuedand puts its id on the queue again.- status
- running
- attempt
- 2
- emails sent
- 2
6Worker W5 claims the job as attempt 2 and sends the email again. The user now has two reminders.
- status
- running
- attempt
- 2
- emails sent
- 2
7W3 wakes up and reports the job done for attempt 1. The store accepts a report only from the current attempt, so it answers 409. The attempt number acts as a fencing token: it stops stale writes to the store, but it cannot undo the email W3 already sent.
- status
- succeeded
- attempt
- 2
8W5 reports the job done. The fix for the double email belongs in the job itself: if the job sends the idempotency key
remind-u42-d15with the email, the email service can drop the repeat.
Deep dives
Finding the jobs that are due
About 70 million jobs are waiting and about 1,200 of them become due every second. The scheduler has to find those jobs cheaply, every second, without reading the rest. There are four ways to do it.
One table with an index on the run time. All jobs sit in one table, and several pollers run a query such as WHERE run_at <= now() ... FOR UPDATE SKIP LOCKED, which lets each poller take different rows. This works at a few hundred jobs a second. At our scale finished rows bloat the index, and 4,800 writes a second land on one primary.
Time-bucketed partitions. The due table is partitioned by shard and by the minute of the run time, so each scan reads one small partition and old buckets are dropped whole. The costs are that dispatchers need shard ownership, and that precision is limited by the one-second scan interval.
An in-memory timer wheel. A dispatcher loads the next few minutes of due rows into memory and fires jobs from there, which gives millisecond precision. A crash loses the memory, so the next owner has to reload the window from the store. It is worth adding only when sub-second precision is needed.
Delayed delivery in a message queue. Many queues can hold a message back until a given time. Delays are usually capped, and it is hard to list, change or cancel waiting messages, so this fits short delays such as retry backoff but not jobs scheduled a week ahead.
| Option | Good at | Bad at | Pick it when |
|---|---|---|---|
| One table, index on run_at | It is simple, and several pollers can work at once. | The index bloats, and one primary takes all 4,800 writes a second. | Use it up to a few hundred jobs a second. |
| Time-bucketed partitions Usual default | Each scan reads one small partition, and shards spread the writes. | Dispatchers need shard ownership, and precision is one scan interval. | Use it for millions of jobs a day when a few seconds of delay is acceptable. This design uses it. |
| In-memory timer wheel | Jobs fire within milliseconds. | A crash loses the memory, and there are more moving parts. | Add it on top of the buckets when sub-second precision is required. |
| Delayed delivery of a queue | There is no scheduler to build. | Delays are capped, and waiting jobs are hard to cancel. | Use it for short delays such as retry backoff. |
I would choose time-bucketed partitions. With 64 shards the 200,000-job burst is about 3,125 rows in each partition, one quick read per shard. A dispatcher that falls behind reads the buckets it missed, so a slow minute delays jobs but never loses them.
Leases and at-least-once execution
When a worker claims a job, it receives a lease: the right to run the job until lease_until, which the worker extends with heartbeats. If the worker dies, its heartbeats stop, the lease expires, and a sweep puts the job back on the queue for another worker. Execution is therefore at least once. No job stays stuck on a dead worker, but a worker that only looked dead may still finish the job, as W3 did in the walkthrough.
The lease length is a trade-off: a 30-second lease recovers quickly from a dead worker but re-runs the job whenever a worker pauses longer, and a long lease does the opposite.
Shard ownership works the same way one level up: dispatchers lease shards from a coordination service that uses consensus (see consensus and leader election). When a stalled dispatcher's lease expires another takes over, and for a short time two may scan the same shard. That is safe because every step is a conditional update: only one can move a job to enqueued, and a duplicate id finds the job already running and is dropped.
The order of operations matters: a worker that marks the job done before running it loses the job if it crashes in between. It must run the job first, report afterwards, and rely on idempotency to make a repeat harmless.
Why exactly-once execution is not possible
A scheduler cannot tell a dead worker from a paused one, so to avoid losing jobs it must re-run jobs from workers that only look dead. When an interviewer asks for exactly-once, the honest answer is that the scheduler guarantees at-least-once execution and the system gets an exactly-once effect from three techniques.
Idempotent handlers. The job passes a key derived from the job, either its id or a key chosen by the caller, to every downstream call. The downstream service remembers the keys it has seen and ignores a repeat (see idempotency and retries). In the walkthrough, this is what stops the second reminder email.
Fencing tokens. Every write carries the attempt number, and the receiving system rejects older attempts. The job store does this for the job status. A fencing token cannot take back an action such as a sent email.
Recurring schedules and time zones
A recurring schedule is stored as a definition with a next_run_at, not as a million future jobs. When a dispatcher claims an occurrence, it creates the next one. The job id is built from the schedule id and the run time, such as s_311@2026-11-15T06:00, so if two dispatchers both create the 07:00 run, insert-if-absent leaves one row. Three policies need an explicit answer.
Overlap is what happens when the 06:00 run is still going at 07:00. The scheduler can skip the new run, queue it or run both, and skipping is the safest default for reports because two concurrent runs often write to the same output.
Missed runs are the occurrences that were due while the scheduler was down. It can run once, run every missed occurrence or skip them, and running once is the usual default.
Time zones matter because the next run time must be computed in the schedule's own zone and stored as a UTC instant. When daylight saving time changes, 02:30 local time may happen twice or not at all, so the design must decide which run to keep and test that case.
The hourly burst is handled by giving schedules that only say "hourly" a stable offset within the hour, chosen by hashing the schedule id. The 200,000 jobs then spread out to about 200,000 ÷ 3,600 ≈ 56 starts a second, which the existing fleet handles.
Bottlenecks and failures
At 10 times the load, about 12,000 runs a second, grow the store from 64 to 512 shards, split dispatcher ownership into smaller ranges and spread the :00 burst across minutes.
| When this fails | What happens | What you do |
|---|---|---|
| A worker | Its leases run out after at most 30 seconds. | The lease sweep puts its jobs back on the queue as the next attempt. |
| A dispatcher | Its shards are not scanned until its lease on them expires. | Another dispatcher takes over the shards and reads the buckets that were missed. Jobs start late but none are lost. |
| The coordinator | No shard lease can be renewed or moved. | Run it on 3 or 5 nodes with consensus. Dispatchers stop scanning when their lease lapses. |
| A job store shard | Jobs on that shard cannot be created, claimed or finished. | A replica is promoted to primary, and the shard's jobs resume from the replica. |
| A ready queue | The job ids that were on it may be lost. | Re-enqueue jobs that have been in enqueued for more than a minute. |
What a strong answer sounds like
| Level | What the answer does |
|---|---|
| Junior | The answer stores jobs in a database and has workers poll for due jobs, and handles a crashed worker only when prompted. |
| Mid-level | The answer uses leases and heartbeats, accepts at-least-once execution, partitions jobs by time and retries with backoff. |
| Senior | The answer sizes the :00 burst and spreads it, leases shards from a consensus service, uses attempt numbers as fencing tokens, and explains that exactly-once is an effect achieved with idempotent jobs. |
Can you guarantee that each job runs exactly once?
I cannot guarantee it for execution. I cannot tell a dead worker from a paused one, so I re-run the job, and sometimes both runs finish. I guarantee at-least-once execution and give job owners the tools for an exactly-once effect, which are attempt numbers as fencing tokens and a stable key per job that they pass downstream.
So who is responsible for duplicates?
The scheduler keeps duplicates rare and visible, and the job owners make their handlers idempotent.
Follow-up questions
How do you cancel a job that is due in a minute?
A conditional update cancels the job only while it is scheduled or enqueued. Workers check the status when they claim a job, so a cancelled job whose id is already on a queue is dropped at that point. A running job can only be asked to stop.
How do retries work?
A failed attempt gets a new run time, which is the current time plus an exponential backoff with some random jitter, and a new due row is written for it. After max_attempts the job moves to a dead status, where it is kept for a person to inspect instead of being retried forever.
One team schedules 10 million jobs for midnight. What protects everyone else?
Each team has its own ready queue and a limit on how fast its jobs are dispatched. The team's jobs start late because of the limit, while other teams' jobs stay on time.
What if a job runs longer than its lease?
The worker sends a heartbeat before the lease runs out, and each heartbeat moves lease_until forward, so a long job keeps its lease for as long as the worker is alive. If heartbeats stop, the lease expires and the job is retried.
After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".