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
- The problem
- Clarifying questions
- The requirements menu
- Non-functional requirements
- Estimates
- Core entities
- The API
- The high-level design
- What breaks first
- The deep dives
- Entity fields
- When the scheduler dies
- Every job runs at least once
- Scale and fairness
- Variants
- What each level is expected to show
- The 30-second answer
- Quiz
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
| Ask | Why it matters | A 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. |
Non-functional requirements
| Requirement | What 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
| Quantity | Working | Result | What 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
| Entity | What 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
| Endpoint | Notes |
|---|---|
| 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. |
| The next run time is read from the earliest execution row still in |
| 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. |
| Allowed on a run in |
The high-level design
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.
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?
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?
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?
Concepts this guide uses
Sources
- Amazon SQS documentation: visibility timeout
- Amazon SQS documentation: delay queues
- Amazon SQS API reference: SendMessage
- tecRacer: The beating heart of SQS, of heartbeats and watchdogs
- Kubernetes API reference: Lease
- Kubernetes documentation: Coordinated Leader Election
- Encore: Postgres as a job queue with SELECT FOR UPDATE SKIP LOCKED
- Amazon DynamoDB documentation: optimistic locking with version number
- Stripe API reference: idempotent requests
- Lumigo: Amazon Builders' Library in focus, timeouts, retries and backoff with jitter
- Marc Brooker: Jitter, making things better with randomness
- Apache Airflow documentation: Dag Runs (catchup)
- Apache Airflow documentation: Backfill
- Kubernetes documentation (mirrored copy): Schedule GPUs
- Wikipedia: Weighted fair queuing
- interviewing.io: Job scheduler mock interview with a FAANG engineer (replay two)
- interviewing.io: Job scheduler mock interview with a FAANG engineer (replay one)
- Pulsetic: Kubernetes CronJob, a practical guide