"Design a job scheduler" means a distributed cron: users register jobs ("run this every day at 02:00", "run this once at 3 p.m. Friday"), and the system runs them on time, even when machines die. Interviewers like it because the happy path is trivial and the failure modes are the whole question.
Three things decide the answer. How do you find the jobs that are due among tens of millions, every second, without scanning them all? How do you make sure a due job is started by one scheduler and not two, without a global lock that becomes a bottleneck? And what does the system promise when a worker or a scheduler dies halfway through: that a job runs exactly once, at least once, or at most once?
The coordination basics are in distributed coordination, including leader election and fencing, and we will use them rather than re-derive them. The page you are reading is about putting them into a scheduler.
Clarify the requirements
Functional requirements:
- Create a job with a schedule (a one-time timestamp or a cron expression), a payload and a target to run.
- Update, pause, resume and delete jobs.
- Run each job at its scheduled time, then record the outcome (success, failure, duration).
- Retry failed runs with backoff, up to a limit.
- Show a job's run history.
Out of scope, said aloud: multi-step workflows with dependencies between jobs (that is a workflow engine), a UI, running arbitrary user code in a sandbox.
Non-functional requirements:
- Timely: a job starts within 30 seconds of its due time under normal load.
- No lost jobs: a registered job is never silently skipped because a machine failed.
- Duplicates are controlled: a job may be started more than once only in rare failure cases, and workers must be able to detect it.
- Scalable: tens of millions of jobs, with millions firing at the same minute boundary.
- Fair: one tenant with a million jobs must not delay everyone else's.
Estimate the scale
Assume 50 million active job definitions producing 200 million executions a day, with an average run time of 2 seconds. Half the executions are scheduled on whole minutes (cron's */5, 0 * * * * and similar).
Average rate: 200,000,000 ÷ 86,400 s ≈ 2,300 executions per second.
The minute-boundary wave: 100 million executions on whole minutes ÷ 1,440 minutes = about 69,400 jobs due at each minute boundary. If they must all start within 5 seconds, that is 69,400 ÷ 5 ≈ 14,000 starts per second, six times the average.
Job storage: 50M definitions × 500 B = 25 GB. It fits on one database with room to spare, and the due-time index is the hot structure.
Run history: 200M executions × 200 B = 40 GB per day, and 30 days of history is about 1.2 TB. History is append-only and queried by job, so keep it out of the hot job table.
Worker capacity: average concurrent jobs = 2,300 × 2 s ≈ 4,600. A fleet of 200 workers with 50 slots each gives 10,000 slots. Draining a minute-boundary wave of 69,400 jobs of 2 seconds each takes 69,400 × 2 ÷ 10,000 ≈ 14 seconds, inside the 30-second requirement without sizing for the spike.
"The average is 2,300 per second, but the number that sizes the system is the minute boundary, six times higher. Buffering the spike in a queue and letting workers drain it in 14 seconds is far cheaper than provisioning for 14,000 instantaneous starts. And 25 GB of job definitions means the database is not the scaling problem. The due-time lookup and the claim are."
The capacity estimator reproduces the 2,300 executions per second and about 1.2 TB for 30 days of history.
API and data model
POST /v1/jobs { schedule, payload, target, retries, misfirePolicy } -> { jobId }
PATCH /v1/jobs/{jobId} { schedule?, paused? }
DELETE /v1/jobs/{jobId}
GET /v1/jobs/{jobId}/runs -> run historyjobs (job_id PK, tenant_id, schedule, next_run_at, shard, state, lease_until, attempts, payload)
index on (shard, next_run_at) where state = 'scheduled'
runs (job_id, scheduled_for, started_at, finished_at, outcome, worker) append-onlynext_run_at is a single column holding the next time this job is due. A recurring job is never expanded into millions of future rows. When it fires, the next time is computed from the cron expression and written back. That keeps the table at one row per job, and the index small.
High-level design
The slice to simulate is the dispatch path: a scheduler stores jobs durably, claims due work, enqueues it with a visibility timeout, and a worker pool runs it with bounded retries.
- Submitters create jobs through the scheduler, which stores them in the job table.
- The scheduler claims due jobs and puts them on a dispatch queue.
- Workers take jobs from the queue and run them, and an unfinished job reappears after its visibility timeout.
Describe this diagram
Components
- submitters (Client)
- scheduler (Service)
- job table (PostgreSQL)
- dispatch queue (SQS queue)
- workers (Service)
Connections
- submitters sends to scheduler
- scheduler sends to job table
- scheduler sends to dispatch queue
- dispatch queue sends to workers
Run it, then try shrinking the number of consumers, or cutting the visibility timeout below the run time, and watch the backlog and the repeated deliveries.
The schedule path: a request writes one row with next_run_at set to the first due time and state = scheduled.
The dispatch path: scheduler nodes repeatedly claim a batch of due jobs, advance each job's next_run_at, and publish a run message (job_id, scheduled_for) to the queue. A worker takes the message, runs the job, writes a row to runs, and acknowledges. If the worker dies, the message becomes visible again and another worker runs it. Inside a scheduler node, the next few seconds of due jobs can wait in an in-memory timing wheel, so firing them is a cheap lookup rather than a database query.
The interesting problem: finding due jobs and claiming each once
Fifty million jobs, and a few thousand become due every second. The design has to answer "which ones, and who starts them?"
Approach A: every scheduler polls and takes a lock
Each scheduler node runs SELECT ... WHERE next_run_at <= now(), then locks the rows it wants.
Good: no extra infrastructure beyond the database.
Bad: every node scans the same hot end of the index and fights over the same rows. SKIP LOCKED helps, but throughput is limited by contention on one table, and a node that crashes holding locks needs cleanup logic.
Approach B: one elected leader scans and dispatches
Elect a single leader with leader election. Only it reads the due jobs and enqueues them.
Good: no contention and simple reasoning.
Bad: one machine's throughput is the system's ceiling, and a leader failure means a gap in scheduling until the election completes. A paused leader that comes back thinking it is still the leader can double-dispatch, unless you add fencing tokens.
Approach C: partition the jobs, one owner per partition
Assign each job to one of, say, 64 shards by hash(job_id) mod 64. Each shard is owned by exactly one scheduler node at a time through a lease (a coordination service or a leases table). The owner scans only its shards' due-time index in batches.
To claim a job, the owner runs one conditional update that advances the schedule and sets a lease in the same statement:
UPDATE jobs
SET next_run_at = <next cron time>, lease_until = now() + 60s, attempts = attempts + 1
WHERE job_id = ? AND next_run_at = <the value I read>If the update changed one row, this node owns that run and publishes it. If it changed zero rows, someone else claimed it, and the node moves on.
Good: work divides across nodes with no contention, because shards are disjoint. A node that dies loses its lease, and another takes its shards within seconds. The conditional update makes the claim atomic, so a stale or duplicate owner cannot dispatch the same run twice.
Bad: it needs a way to assign shards and detect dead nodes, and a skewed shard (one tenant with a million jobs) loads one node unevenly.
Diagram, as text
- Scheduler: owns shards 0-15 leads to Claim due jobs in batches
- Claim due jobs in batches leads to Conditional update: advance next_run_at
- Conditional update: advance next_run_at leads to Publish run to queue
- Publish run to queue leads to Worker runs it
The recommended answer is C. Mention that A's SKIP LOCKED is a fine start for a small system, and that B is acceptable at modest scale with fencing. For the order of the steps, claim in the database first, then publish. If the scheduler crashes between the two, the lease expires and the job is reclaimed, so the job is never lost. The cost is a possible duplicate, which the next section handles.
The second decision: what "runs" means
A job can be lost, run once or run more than once, and you can only pick two of the three at the edges.
- At-most-once: mark the job done before running it. A crash loses the run. Acceptable only for jobs where a skipped run is harmless.
- At-least-once: the run message is redelivered until a worker acknowledges completion. A crash causes a rerun, so a job may execute twice. This is the default for a scheduler.
- Effectively-once: at-least-once delivery plus idempotent execution: each run carries a unique key
(job_id, scheduled_for), and the job (or the worker's wrapper) checks whether that key has been completed before doing the work. See idempotency.
Choose at-least-once with idempotency keys, and push the responsibility honestly: the scheduler guarantees a run is started, the job's author guarantees running it twice is safe.
Two timing rules follow:
- The visibility timeout must exceed the longest normal run, or a healthy worker's job is handed to a second worker. For jobs that run for minutes, have the worker send heartbeats that extend the lease, and let a missing heartbeat, not a fixed timeout, signal death.
- Retries need backoff and a limit. Retry after 10 s, 1 min, 10 min, then mark the job
failedand alert. An endless retry of a broken job occupies worker slots forever.
Bottlenecks and failures
The minute-boundary spike. 69,400 jobs due at :00 arrive almost together. Do not size workers for it. The queue buffers the wave and workers drain it in about 14 seconds. For jobs that do not need exact timing, add deterministic jitter (a hash of the job id spreading starts across a few seconds) and set per-tenant concurrency limits so one tenant's wave cannot starve others.
A scheduler dies. Its shard leases expire in seconds and another node takes over. Jobs it claimed but had not published are reclaimed when their lease_until passes. Jobs it had published are already on the queue.
A worker dies mid-job. The queue redelivers after the visibility timeout or a missed heartbeat. This is why jobs must be idempotent. Record started_at and the worker id so you can see the retry in the run history.
Missed runs after an outage. If every scheduler is down for 45 minutes, thousands of jobs are overdue when it returns. Each job has a misfire policy: skip (run only the next one), run once now (catch up), or run all missed. Default to run once, and ramp the catch-up so the backlog does not stampede.
Time zones and daylight saving. A cron of 0 2 * * * in a local zone does not exist on the night the clocks jump forward, and happens twice when they fall back. Store the zone with the schedule, compute the next time with a tested library, and document the rule.
A poison job. One job that crashes its worker every time can drain capacity. Cap attempts, move the job to a failed state and alert the owner.
Trade-offs to name aloud
- At-least-once over exactly-once: simple and safe, in exchange for pushing idempotency to the job.
- Sharded owners over one leader: more moving parts (leases), in exchange for scale and no single point of failure.
- One row per recurring job: a small index, in exchange for computing the next time on every run.
- Queue buffering over provisioning for the peak: a few seconds of start delay, in exchange for a fleet a sixth of the size.
- Claim then publish: a possible duplicate, in exchange for never losing a run.
What interviewers listen for
- A working answer: a jobs table with a next-run time, a scheduler that polls for due jobs, workers that run them and retries.
- A strong answer: shards the scan, claims jobs with an atomic conditional update, chooses at-least-once and explains idempotency, and uses a queue to absorb the minute-boundary spike.
- A standout answer: also covers leases and heartbeats for long jobs, misfire policies after an outage, daylight-saving traps, fencing for a zombie scheduler and fairness between tenants.
Check your understanding
Common mistakes
One cron process on one machine. It is the first design and the interview's starting point, not its answer. Say what happens when that machine dies.
Scanning all jobs. Without an index on due time and a per-shard scan, finding due jobs is a full table scan every second.
Claiming and publishing in the wrong order. Publishing first can run a job with no record of it, and failing between two unordered steps can lose runs. Order them and use leases.
Promising exactly-once. It is not achievable across a crash. Offer at-least-once with idempotency keys and say so.
Forgetting long jobs. A fixed timeout shorter than the job causes duplicate concurrent runs. Use heartbeats.
Ignoring time. Daylight saving, time zones and clock skew each produce real bugs, and interviewers who have run a scheduler know it.
Practice
All schedulers were down for 45 minutes. When they return, 3 million jobs are overdue. What should the system do?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Not every job wants the same catch-up behavior, and starting millions at once would be a second outage.
Show a strong answer
Let each job choose its misfire policy. A job that refreshes a cache every minute needs one run now, not 45. A report for each hour may need all 45 catch-up runs. A reminder that is 45 minutes late may be pointless. Default to run once now.
Do not release it all at once. 3 million overdue jobs at 14,000 starts per second takes about 215 seconds of full-rate dispatch, which would also crowd out jobs that are on time. Dispatch catch-up work from a lower-priority lane, ordered by the oldest due time, and cap its share of capacity, for example 30%.
Protect the downstreams. Many of these jobs call other services. Per-tenant and per-target concurrency limits keep the backlog from becoming a thundering herd.
Tell owners. Record each skipped or late run in the history with the reason, so owners can see exactly what did not run on time.
The pattern worth keeping: recovery from an outage is a controlled ramp with explicit policy per workload, not a flood.
A billing job must never charge a customer twice, but your scheduler is at-least-once. How do you make that safe?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Give each run an identity and make the side effect check it.
Show a strong answer
Name each run. The unique identity of one execution is (job_id, scheduled_for), for example invoice-run:2026-12-01. A retry has the same identity as the original.
Make the side effect idempotent. Pass that identity to the payment provider as an idempotency key, or insert it into a table with a unique constraint before charging. A second attempt hits the constraint or the provider's cache and returns the first result instead of charging again.
Order the steps. Record the intent, perform the charge with the key, then record completion. A crash after the charge and before the completion record just repeats the call, which returns the cached result.
Add a fencing check for zombies. If a paused worker wakes up after its lease was given to another, a monotonically increasing token lets the downstream reject the stale caller, as in distributed coordination.
The pattern worth keeping: exactly-once effects come from at-least-once delivery plus an identity that makes repeats harmless.
Key takeaways
- Store one
next_run_atper job, index it and never expand recurring jobs into future rows. - Shard the scan so each scheduler owns disjoint jobs through a lease.
- Claim with an atomic conditional update, then publish, so a crash loses nothing.
- At-least-once plus idempotent runs is the honest delivery guarantee.
- Buffer the minute-boundary spike in a queue rather than sizing for it.
- Plan for misfires, long jobs and time zones. They are where real schedulers fail.
Further reading
- Google, "Site Reliability Engineering" (O'Reilly, 2016), the chapter "Distributed Periodic Scheduling with Cron": a production distributed cron and its failure modes.
- M. Burrows, "The Chubby Lock Service for Loosely-Coupled Distributed Systems", OSDI (2006): leases and coarse-grained locks for coordination.
- G. Varghese and T. Lauck, "Hashed and Hierarchical Timing Wheels", SOSP (1987): an efficient in-memory structure for timers.