Skip to content

How to design a job scheduler

The first sections are free. The deep dives, level expectations and quiz are part of Pro.

On this page
Practice this question

The problem

A job scheduler takes the background work other teams hand it, runs each job now, at a set time or on a repeating schedule, and shows what happened to each run. At 10,000 job runs a second, each starting within 2 seconds of its time, the answer turns on keeping two problems apart: finding what's due without reading the whole table at the moment it's due, and keeping a run alive when the scheduler or a worker dies. The design that does both reads soon-due runs ahead of time into a queue that releases each one on schedule, leases each run to a worker, and accepts that a run may happen twice because the task is written to tolerate a repeat.

Clarifying questions

AskWhy it mattersA typical answer

How many runs a second, and how close to the scheduled time must each one start?

The pair decides the shape of the scheduler. A few runs a minute can be found by polling the table when they're due; a steady 10,000 a second with a tight start window means the due runs must already be staged somewhere before their time arrives.

The interviewer's figures: 10,000 a second, with a start window of 2 seconds.

May a run happen twice, or must it happen exactly once?

It sets the contract with the task code. If a repeat is acceptable, a lease and a retry cover worker crashes; if not, the execution path needs a transactional handshake with whatever the task touches, which is far costlier.

At least once. A task is expected to tolerate a repeat, and the scheduler promises no run is lost.

Can a job be canceled or changed after it's created?

Cancel means reaching a run that may already be staged in a queue or running on a worker, which adds a signal path and a state check to the design.

Out of scope for the base question. It comes back if the interviewer switches to the GPU variant, where cancel frees a GPU.

Do several teams share this, with priorities, and can one of them flood it?

One shared line ordered by priority and a line per tenant behave very differently when a single team drops a huge batch.

Yes. Many teams submit jobs, each job carries a priority, and one team's flood may not starve the rest.

What should happen to runs that were due while the scheduler was down?

There is no single right answer: a daily report wants one catch-up run, a metrics tick wants each missed one, a reminder wants to be skipped once it's stale. The choice has to be explicit.

A policy per job. We'd propose one catch-up run as the default and say so; the interviewer may prefer another.

How long do tasks run, and do we own their code?

Run length sets the lease length and heartbeat interval for workers, and whether we own the code decides whether idempotency is something we build or something we require.

Assume a wide range and size the lease per task. The task code and its runtime are out of scope; the scheduler requires it to tolerate a rerun and keys each run by its execution id.

The requirements menu

RequirementScopeWhy

Schedule a job to run now, at a future time, or on a recurring schedule such as every day at 10:00

Core

The whole product. The three schedule shapes collapse into one mechanism: each occurrence becomes an execution row with a scheduled time, and a recurring job creates its next row when the current one is handed out.

See the status of each job and its runs

Core

Other teams need to know whether their work ran. It forces workers to write status back to the store at each transition, which one mock interviewer called out as the main gap in a candidate's design.

Retry failed runs

Core

Both automatic retries with backoff and a manual retry through the API. It forces an attempt counter on each execution and a limit after which a person is told.

Priorities, and jobs that depend on other jobs

Core

Priorities decide order inside a tenant's queue. Dependencies change when a run becomes eligible: it waits for its parents to finish instead of a clock, which is the curveball at the end of the round.

Pause and resume a job

Optional

Cheap to add once executions are rows: a paused job stops creating new rows and its staged ones are skipped on release. Take it if asked; it shows the execution row is the unit of control.

Per-job overlap control: skip or queue a run while the previous one is still going

Optional

Real schedulers expose this because a slow daily job can overlap itself. Worth naming; leave the mechanism unless the interviewer pulls on it.

Time zones and daylight saving for recurring schedules

Optional

Worth settling early: store schedules with an explicit zone and compute the next occurrence in it, so a daily job at a local hour means the same thing to the job owner and the scheduler across a clock change. Say so in one sentence and move on.

Alert when a run fails past its retry limit

Optional

The natural end of the retry path: a run marked failed needs a person to see it. One line about a dead-letter view or a notification is enough.

Capture task logs and output

Optional

Useful for the teams who own the tasks, but it is storage and a viewer, not scheduling. Point at object storage keyed by execution id and park it.

Exactly-once execution for each run

Out of scope

Tempting because it sounds safer, but it needs a transactional handshake with each system a task touches. The round's contract is at least once with tasks that tolerate a repeat.

Cancelling or rescheduling jobs (Hello Interview), unless the GPU variant is chosen

Out of scope

Reaching a staged or running run is its own mechanism. It returns in the GPU variant, where a canceled task must free its GPU.

The job code and its runtime

Out of scope

The scheduler hands a task id and parameters to a worker; what the worker runs, in which language or container, is the task owner's problem. Keep the idempotency requirement as the one thing you impose on it.

A visual editor for job graphs

Out of scope

A front end on top of the dependency model. Name it as a later product and spend the time on the scheduler.

Non-functional requirements

RequirementWhat it forces

Runs start within 2 seconds of their scheduled time

Finding a run when its time arrives is too late. Due runs must already be staged, minutes ahead, in something that releases each at its second; and a scheduler failover must finish inside the window that staging bought, so the lease on the scheduler role is measured in seconds.

10,000 job runs a second

The executions table grows by about 864 million rows a day, so it is partitioned by time, indexed by scheduled time, and old partitions are dropped rather than deleted row by row. The scheduler reads by time range, not the whole table, and the queue and the worker pool scale by adding instances.

Every run happens at least once

A run exists as a durable row before anything is queued, a worker holds a run under a lease rather than owning it outright, and when the lease lapses the run goes back for redelivery. The price is that a run can happen twice, so the task contract says a repeat must be harmless.

One tenant’s flood of jobs cannot starve the others

No single shared line. Released runs sit in a queue per tenant, a dispatcher takes weighted turns between tenants, and priority orders runs inside a tenant's queue, not across tenants.

Estimates

QuantityWorkingResultWhat it sizes

Runs per day

10,000 job runs a second × 86,400 seconds a day = 864 million

About 864 million execution rows a day

The executions table: it must be partitioned by time with old partitions dropped, because deleting that many rows one by one would compete with the writes.

Executions table growth in bytes

Assume an execution row of about 200 bytes (ids, two timestamps, status, attempt, worker). 864 million × 200 bytes ≈ 173 GB a day; about 1.2 TB a week

Roughly 173 GB a day of new rows

The retention policy: keep a week or two of run history in the hot store and move older rows to cheap storage.

Runs in one one-minute time bucket

10,000 job runs a second × 60 seconds = 600,000 rows per bucket

About 600,000 rows a bucket

What a scheduler reads when it picks up a bucket: a range read of that many rows by the scheduled-time index, not a scan of the whole table.

Messages staged in the delay queue

With a five-minute lookahead: 10,000 job runs a second × 300 seconds = 3 million messages waiting at any moment

About 3 million delayed messages waiting in the queue at any moment, not yet visible to workers

The queue's holding capacity and why the lookahead stays at minutes: a longer window multiplies what sits in the queue and what a cancel would have to chase.

Scheduler failover against the lookahead

Scheduler lease of 10 seconds, renewed at 5-second intervals, half the lease. A standby sees the lapse within 10 seconds of a crash. In that gap the dead leader would have staged 10,000 × 10 = 100,000 runs, all of them due about 300 seconds out. A run due at 10:00 is staged 300 seconds earlier, at 9:55, so a crash at 9:59 finds it already in the queue

Takeover in about 10 seconds, leaving about 100,000 runs for the new leader to stage, each due minutes later. Whether any runs late depends on its catch-up rate, not on the lease

The failover budget: the lease must be far shorter than the lookahead, so a crash at 9:59 doesn't touch a run due at 10:00 that was staged near 9:55.

Time to notice a dead worker

Worker lease of 30 seconds (the queue's default visibility timeout), a heartbeat at 10-second intervals. A worker that dies is noticed when its lease lapses, at most 30 seconds later

A redelivered run starts up to about 30 seconds late

What the two-second promise covers: the first start of a run. A retry after a worker crash is late by the lease length, so say that out loud.

Load per scheduler when the work is split

10,000 job runs a second ÷ 4 schedulers = 2,500 enqueue calls a second each

About 2,500 a second per scheduler with four slices

Whether one leader does all the staging or several schedulers split the time range between them.

Retry schedule with capped backoff

An example policy: base 1 second, delay before retry n of 2^n seconds, capped at 300 seconds, with random jitter. Retries one through five wait about 2, 4, 8, 16 and 32 seconds; about a minute in total before the sixth attempt

A failing run is marked failed within a few minutes under this example policy

How long a broken run lingers before a person is told, and how many attempts a dead-letter limit should allow.

Core entities

EntityWhat it holds

Task

The reusable unit of work a team registers once, such as send an email or rebuild a report.

Job

A task bound to a schedule, parameters, an owner and a priority. Nothing here changes when the job runs.

Execution

One scheduled occurrence of a job: the row the scheduler stages, a worker leases, and the status page reads.

Worker

A process in the pool that leases runs, heartbeats while working and writes the result.

The API

EndpointNotes

POST /jobs { task_id, schedule, parameters, priority } → { job_id }

Validates the schedule, stores the job and inserts its first execution row in the same transaction, so a job is not created without a run to find. Accept an idempotency key from the caller so a retried create doesn't make two jobs. The tenant comes from the caller's credentials, not the body.

GET /jobs/{id} → job and its next run time

The next run time is read from the earliest execution row still in scheduled or staged, not computed again from the schedule, so the API and the scheduler agree.

GET /jobs/{id}/executions?status= → runs with their status

Reads the executions table by job id, newest first, with a cursor. The status filter is an index on (job_id, status). This is the page that proves workers wrote their status back.

POST /executions/{id}/retry

Allowed on a run in failed. Creates a new execution row that points at the original (same job, same parameters, new id) and stages it for now, rather than reopening the old row, so history is kept and the task's idempotency key is fresh.

The high-level design

writesduestatusdispatchJob serviceJobs, executionsSchedulerWorkers

Step 1 of 4

A job service, one store, and a scheduler that polls

Start with the smallest shape that works. A job service takes POST /jobs, writes the job and its first execution row into one store, and answers status reads from the same rows. A scheduler loop asks the store for executions whose time has come and hands each one to a worker; workers run the task and write status back on each transition, so the status page reads from the store and nowhere else. This already handles run now, run later and recurring jobs, because each occurrence is a row and the handoff of one row creates the next. What it lacks shows up under load and under failure.

writesholdslapseduestageresumereleaseturnsstatusJob serviceJobs, executionsLease recordSchedulerStandbyDelay queueFairdispatcherWorkers
The whole design

What breaks first

The deep dives

When the scheduler dies. The scheduler process crashes at 9:59 and a job is due at 10:00. How does that run still start within 2 seconds of its time, who takes over, and how does the newcomer avoid staging the same runs again?

A concept that helps here: Leader election and failoverA concept that helps here: Job scheduling and delayed workA concept that helps here: Distributed locks and leases

Every job runs at least once. A worker takes a run and dies halfway through. How does the system notice, how does the run reach another worker, and what happens if the first worker was just slow and finishes later?

A concept that helps here: Delivery semantics: at most, at least, exactly onceA concept that helps here: Idempotency keysA concept that helps here: Retries and dead-letter queues

Scale and fairness. The scheduler now runs GPU jobs, one GPU per task, and one customer submits an enormous batch at once. How does each other customer still get a turn, how does a cancel reach a task already on a GPU, and what happens when a GPU worker dies mid-task?

A concept that helps here: Fair queuing across tenantsA concept that helps here: GPU batching and schedulingA concept that helps here: Heartbeats and presence

Concepts this guide uses

Sources

  1. Amazon SQS documentation: visibility timeout
  2. Amazon SQS documentation: delay queues
  3. Amazon SQS API reference: SendMessage
  4. tecRacer: The beating heart of SQS, of heartbeats and watchdogs
  5. Kubernetes API reference: Lease
  6. Kubernetes documentation: Coordinated Leader Election
  7. Encore: Postgres as a job queue with SELECT FOR UPDATE SKIP LOCKED
  8. Amazon DynamoDB documentation: optimistic locking with version number
  9. Stripe API reference: idempotent requests
  10. Lumigo: Amazon Builders' Library in focus, timeouts, retries and backoff with jitter
  11. Marc Brooker: Jitter, making things better with randomness
  12. Apache Airflow documentation: Dag Runs (catchup)
  13. Apache Airflow documentation: Backfill
  14. Kubernetes documentation (mirrored copy): Schedule GPUs
  15. Wikipedia: Weighted fair queuing
  16. interviewing.io: Job scheduler mock interview with a FAANG engineer (replay two)
  17. interviewing.io: Job scheduler mock interview with a FAANG engineer (replay one)
  18. Pulsetic: Kubernetes CronJob, a practical guide
Sign in to report a mistake