"Design a distributed job scheduler" usually turns into a question about leader election. The candidate starts with cron on one machine, notices that the machine can die, adds a second scheduler, and spends ten minutes making sure only one of them fires. That handles one way a job runs twice. There are at least three more.
- A worker dies halfway through a run, and the run is started again on another worker.
- A worker pauses past its lease, and wakes up while a second worker is running the same thing.
- A region fails over, and the new region fires runs that the old one fired a second before it died.
A perfect election prevents none of these.
Google's Site Reliability Engineering (SRE) book describes how its cron service can handle the first case, a new leader taking over, with a name. Before a launch, the cron leader works out a name for it that includes the scheduled launch time. A new leader looks up which of those names already exist and launches only the missing ones. The book calls this a reasonable solution, and says the real system's lookup is more complicated. Temporal, a workflow engine, does the same for its schedules. It appends the scheduled time to each run's workflow ID, and it never runs two open workflows with the same ID.
The same name settles the other three cases too.
Name every run before it fires, by its job and its scheduled time. Then every way a run can happen twice becomes the same event: a second attempt at a name the system already knows. One set of rules handles all of them.
Understanding the problem
The general method for this part of the interview is in The First Five Minutes: Requirements.
A job scheduler runs work at a time. A team registers a job with a schedule, such as "every day at 02:00 London time" or "once, 30 minutes from now". When that time comes, the scheduler starts it on a fleet of workers.
Five kinds of system go by this name, and each is designed differently.
- Cron on one machine. A daemon wakes every minute and checks a file of schedules. When the machine dies, nothing runs.
- A timer inside one service, such as a request timeout or a retry delay. It lives in the process's memory and dies with it, which is fine for a timeout.
- A task queue, such as Celery or Sidekiq, which runs work as soon as it's enqueued. Message queues vs event streams covers those, and this design uses one for runs that are already due. A message that has to be delivered later is a one-off job here, whose handler publishes it.
- A workflow engine, such as Airflow or Temporal. It runs graphs of steps that wait on each other, and keeps the state of long workflows. Deep dive 5 touches on dependencies.
- A distributed job scheduler for a whole company, such as AWS EventBridge Scheduler: millions of schedules, code from any team, one shared fleet. This is the one we're designing.
Functional requirements
Core:
- Define a job. Create, change, pause and delete a job with a schedule: a cron expression in a named time zone, a fixed rate, or a single time. A job names a handler in a worker pool, and a payload for it.
- Fire each run on time. When a run is due, hand it to a worker.
- Run it, and survive a worker dying. At most one attempt of a run is active at any moment, and a run whose worker dies is started again.
- Retry, time out and record. A failed attempt is retried with backoff up to a limit, and then the run goes to a dead-letter table. Every run's outcome is kept for 30 days.
Out of scope, deliberately:
- Dependencies between jobs, beyond deep dive 5. A graph of steps is a workflow engine.
- Building and deploying the job's code. Each team already runs its handlers in its own worker pool.
- Runs triggered by events, such as a file arriving. A queue consumer does that.
- Timers that may be lost, or that are shorter than a second, such as a request timeout. Those belong inside the service that needs them.
- How the broker behind the ready queues stores and copies messages. Distributed message queue designs that.
Non-functional requirements
- Scale. 10 million recurring schedules, which fire about once an hour on average, and 200 million one-off jobs created a day. That's 440 million runs a day, about 5,100 a second. These are assumptions. EventBridge Scheduler allows 10 million schedules per Region by default, and AWS says the limit can be raised to billions, so the size is ordinary for a shared service.
- On time. 99 percent of runs start within 5 seconds of when they're due. A job may allow a window, such as "any time in the 30 minutes after 02:00". It's then due at the point in that window the scheduler picks for it (deep dive 2). Dropbox set its task framework a similar bar: 95 percent of tasks start within five seconds of their scheduled time.
- No run disappears. Every run the schedule calls for either starts or is recorded as skipped, with the reason. A scheduler outage makes runs late, never lost.
- One name per run, one attempt at a time. A run may be attempted more than once, but never by two workers at the same moment. Every attempt carries the run's name, so the job's code can tell a repeat from new work.
- Availability. Losing a machine or a zone delays runs by seconds. A job, once created, survives losing any one machine or zone.
Requirement 4 carries the design, so write it in those words. "Each job runs exactly once" can't be built. A worker that dies after its side effect and before it reports leaves nobody able to tell whether the work happened. Idempotency and exactly-once delivery shows why no protocol closes that gap. A scheduler can promise the run's name and one attempt at a time. The job's code turns that into one effect.
How often does a run get a second attempt?
The question is whether second attempts are rare enough to ignore. Assume 1 attempt in 1,000 loses its worker or its lease: a crash, a host taken back, an out-of-memory kill, a pause longer than the lease. The idempotency page calls a 0.1% redelivery rate unremarkable. runs a day 440M attempts lost 440M × 0.001 = 440,000 per second 440,000 / 86,400 ≈ 5 ───────────────────────────────────────────────────── About 440,000 runs a day get a second attempt while the first may have done part of its work, about 5 a second all day. The design has to treat a second attempt as normal.
The set up
Core entities
- Job. A schedule, a target, and the rules for retries, overlap and catch-up. A one-off job is stored only as its single run.
- Run. One firing of a job, named by the job and the time the schedule called for, such as
job_8f2@2026-11-10T02:00:00Z. The run is the only interesting entity. It's what gets fired, retried, deduplicated, measured for lateness and kept in history. - Attempt. One try at a run on one worker. Attempts are numbered 1, 2, 3, and the number goes with every call the worker makes.
- Pool. The workers that run one team's handlers, with their own queue of runs that are due.
- Partition. One of 1,024 fixed slices of the jobs, by a hash of the job ID. A run lives in its job's partition.
System interface
POST /v1/jobs
Idempotency-Key: 3b9e2c71-0f4d-4a8e-b6c2-91d7e5a04f18
{
"name": "invoice-export",
"schedule": { "cron": "0 2 * * *", "time_zone": "Europe/London" },
"window_minutes": 30,
"target": { "pool": "billing", "handler": "export_invoices",
"payload": { "country": "GB" } },
"timeout_seconds": 900,
"retry": { "max_failures": 5, "first_delay_seconds": 30 },
"overlap": "skip",
"catch_up": "latest",
"on_lost": "rerun"
}
→ 201 { "job_id": "job_8f2", "next_run": "job_8f2@2026-11-10T02:00:00Z" }
POST /v1/jobs
{ "run_at": "2026-11-09T18:30:00Z", "target": { ... } }
GET /v1/jobs/job_8f2/runs?limit=20
→ 200 [{ "run": "job_8f2@2026-11-09T02:00:00Z", "state": "SUCCEEDED",
"due_at": "2026-11-09T02:17:41Z", "started_at": "2026-11-09T02:17:42Z",
"attempts": 1 }]
-- the worker side
POST /v1/runs/job_8f2@2026-11-10T02:00:00Z/start
→ 200 { "attempt": 2, "epoch": 7, "lease_seconds": 60, "payload": { ... } }
→ 409 -- already started or finished: drop the message
POST /v1/runs/job_8f2@2026-11-10T02:00:00Z/heartbeat { "attempt": 2, "epoch": 7 }
POST /v1/runs/job_8f2@2026-11-10T02:00:00Z/finish
{ "attempt": 2, "epoch": 7, "outcome": "retriable_failure" }
→ 409 -- a newer attempt owns this run: stop
Four things to note.
The run's name is computed, not issued. It's the job ID and the scheduled time in Coordinated Universal Time (UTC). Anything that knows the schedule can work it out, so a second scheduler, a new region or a retry arrives at the same name, not a new one. The handler receives the name and builds each effect's idempotency key from it: the name plus that effect's own identity, such as job_8f2@2026-11-10T02:00:00Z/charge/inv_42.
window_minutes says how late a run may start. Most jobs written for 02:00 mean "once a night", and this field lets the scheduler spread them out (deep dive 2). A job that must start at 02:00 sends 0.
Every worker call carries the attempt number and the region's epoch. A worker whose attempt has been replaced gets 409 on its next heartbeat or finish, and stops. Section 3 uses the number to refuse a worker that woke up late, and deep dive 6 explains the epoch.
on_lost decides what happens when a worker vanishes mid-run. rerun starts another attempt, which is safe only if the handler keys each effect on the run's name. hold starts nothing and marks the run unknown for a person to check.
All of that is the data plane. The control plane creates pools, sets each tenant's limits, and decides which dispatcher, the process that finds due runs, polls which partitions. The job API and the dispatchers share one thing, the database that holds jobs and runs. If the API is down, runs still fire. If the dispatchers are down, job changes still save, and runs are late.
High-level design
1. Define a job: how does a schedule become runs?
A recurring job describes an endless series of runs. Something has to decide how many of them exist as rows.
The tempting answer is to expand each schedule ahead of time, say a year of runs per job, so finding due runs is one index scan. At 10 million schedules firing hourly, a year is 10 million × 8,760 = 87.6 billion rows, and changing one job's cron rewrites 8,760 of them.
So only the next run of each recurring job exists. When it fires, the same transaction inserts the one after it, computed from the schedule. A one-off job is stored as its run row alone, which carries its own target and payload, and it never gets a row in jobs. At any moment that's 10 million pending recurring runs, plus the one-off runs. If the average one-off job waits 6 hours, those are 200 million × 6 / 24 = 50 million.
The next run is computed from the previous run's scheduled time, not from the clock, and that decides what happens after an outage. Say the dispatcher for a partition was down from 01:40 to 04:30, and an hourly job's 02:00 run was waiting. When it comes back, 02:00 is due, and so are 03:00 and 04:00. A run counts as missed when the dispatcher first reaches it more than 10 minutes past its due_at, longer than any normal delay. A run that is only a poll late is just late. The job's catch_up setting decides what happens to missed runs.
- all fires all three, each one when the run before it finishes, so the overlap rule in section 4 doesn't skip them.
- latest fires 04:00, and records 02:00 and 03:00 as skipped.
- none records all three as skipped, and waits for 05:00.
Every missed time still gets its name, whatever the policy. A skipped run is a row in history with a reason, and that's how requirement 3 holds: nothing that was due goes unaccounted for.
An edit replaces the pending run. It locks the job row with FOR UPDATE, deletes the job's SCHEDULED run and inserts the new next one, all in one transaction. A firing reads the job row FOR SHARE first (query 2). So an edit and a firing of the same job run one after the other, and the edit always sees the successor the firing inserted. That needs read committed, Postgres's default, where each statement sees what committed before it. It also needs every path that replaces a pending run to take the job row's lock first: edits, deletes, resumes, and the time zone update in deep dive 4. A run that has already started finishes under the old definition, and records the job version it was fired with. A paused job's run is recorded as skipped when it comes due, and the next one is computed as usual. Computing the next time in a named time zone has two awkward days a year, and deep dive 4 handles them.
2. Fire each run on time: where do future runs wait?
About 60 million runs are waiting for their time, and about 5,100 come due each second. Something has to keep the waiting ones, and something has to notice each one when it comes due and hand it to a worker.
A timer that wakes the run, in memory or on a broker
The scheduler can hold the timers itself. Inside one process, a timing wheel keeps millions of timers cheaply. It's a ring of buckets, one per tick, and adding or cancelling a timer costs the same however many there are. Kafka keeps its request timeouts in timing wheels for that reason. Or a broker can hold them: put each run on a queue with a delay, and the broker hides the message until it's due.
Both are tempting because nothing has to poll. Both fail here.
A timer in memory dies with the process. Reloading 60 million runs from wherever else they're kept, at an assumed 200,000 rows a second, takes 5 minutes, and nothing that process owns fires meanwhile. Google's cron chapter treats one minute as the most a failover should take.
A broker's delay has a ceiling. Amazon Simple Queue Service (SQS) hides a message for at most 15 minutes, so a run due tomorrow has to be sent again every 15 minutes until then. With 50 million one-off runs waiting, that's 50,000,000 / 900 s ≈ 55,600 sends a second, 11 times the 5,100 runs a second that are due.
And nothing can find a message on a queue and change it. When a team pauses a job or moves it to 03:00, the old message still fires at 02:00. So every run needs a check against the job when it fires, and the queue becomes a second copy of the schedule that has to agree with the first.
A table of upcoming runs, polled with SKIP LOCKED
Keep each upcoming run as a row with its due time, indexed by that time. Workers poll the table: each one selects the earliest due rows, locks them and runs them. In Postgres, FOR UPDATE SKIP LOCKED makes this safe with many pollers. A row that another transaction has locked is skipped, not waited for, and the documentation names this exact use: several consumers sharing a queue-like table.
Airflow works this way. It runs several schedulers against its metadata database using row locks, and its documentation says it chose that over a consensus protocol for operational simplicity. A row survives any process, a pause is an update, and the claim is a transaction.
The cost is who polls. Here the pollers are the workers, and deep dive 3 sizes the fleet at about 4,000 hosts. Each host holds connections to the database, and Postgres starts a process for every connection and ships with a limit of 100. Each host also scans the head of the same index every second, stepping over rows the others have locked. So the database's load grows with the number of workers, not the number of runs. Adding workers for one busy pool slows every pool.
Split finding a run from running it
Question the premise that the machine that runs a job has to be the one that finds it. Finding is cheap and needs a few machines. Running is expensive and needs thousands.
So a small tier of dispatchers does the finding. Each dispatcher polls its own share of the 1,024 partitions once a second, claims what's due, and sends each run's name to its pool's ready queue. Workers take names from that queue and talk to the scheduler's API, never to the database. The database sees 1,024 indexed reads a second, however many workers there are. And since one dispatcher polls each partition, there are no locked rows to step over.
Dropbox's async task framework (ATF) is built this way. A process Dropbox calls the Store Consumer polls its database every two seconds for tasks that are ready, and pushes them to SQS. A controller on each worker host pulls from SQS and hands tasks to executors. Dropbox reported about 9,000 tasks a second through it.
What you give up. A run is now in two places, its row and a queue message, and they can disagree. The row is the truth and the message is a pointer. A worker that receives a name asks the API to start it, and a message for a run that has already started gets 409 and is dropped. A claimed run whose message never arrives has to be sent again, and the notes under the queries say how. And partitions need owners, which deep dive 1 works out.
Which data store, and what actually forces it
Start where the interviewer expects: one Postgres database for jobs, upcoming runs and history. Then price it.
The question is what forces more than one database. A recurring job's row is about 1 KB and its run's row about 300 B. A one-off run carries its own target and payload, about 1 KB. All three are assumed. Data jobs 10M recurring × 1 KB = 10 GB pending runs 10M × 300 B + 50M one-off × 1 KB = 53 GB history 440M a day × 300 B = 132 GB a day 30 days of it 132 GB × 30 ≈ 4 TB Writes to a run's row, over its life inserted, fired, started, one heartbeat on average, finished, removed = 6 per second 5,100 × 6 ≈ 30,600 the firing's FOR SHARE lock marks the job row's header, a light write left out here One primary commits 5,000 to 20,000 point writes a second. Plan at the low end, under 40% busy at the average: shards 30,600 / (5,000 × 0.4) ≈ 15.3 → 16 ───────────────────────────────────────────────────── The jobs and pending runs are 63 GB, which one machine holds easily. The writes need 16. History is about 60 times the pending data, and it goes somewhere else.
This is the reverse of the usual case. Choosing a database finds that storage forces a split long before writes do. A scheduler's runs table behaves like a queue. Rows arrive, change state a few times and leave, so the table stays small and every row is rewritten several times. That churn is also why the plan uses the low end of the range: every update leaves a dead row for vacuum, the Postgres cleanup process, to clear.
So the partitions map onto 16 Postgres shards, 64 partitions each, and a job's rows live on its partition's shard. Moving a partition to a new shard copies its rows, without rehashing any job.
Why not a wide-column database such as Cassandra? A run has states, and every change is conditional: fire it only if it's still scheduled, finish it only if this attempt still owns it. Postgres does each in one statement, and does a firing and its successor's insert in one transaction. Cassandra runs a Paxos round for each conditional write, as the key-value store notes.
History is different. It's written once, read by job with the newest first, and deleted after 30 days. That's a wide-column table with an expiry, so it goes to Cassandra, partitioned by job and month.
| data store | what goes in it | what forces it |
|---|---|---|
| Postgres, 16 shards by partition | jobs, upcoming and running runs, dead letters | conditional state changes, 30,600 writes a second |
| Cassandra, keyed by job and month | finished runs, kept 30 days | 132 GB a day, written once, read by job |
| a queue broker such as SQS, one queue per pool | names of runs that are due now | a buffer between 16 dispatchers and 4,000 worker hosts |
| Redis, shared by the dispatchers | a token bucket per tenant | each tenant's limit, checked by 16 dispatchers on every firing (deep dive 2) |
The tables
-- On each Postgres shard: 64 of the 1,024 partitions
jobs ( -- recurring jobs only
job_id text primary key,
partition int not null, -- hash(job_id) % 1024
tenant_id text not null,
schedule jsonb not null, -- cron and time zone, or a rate
window_s int not null, -- 0 means start on time
policy jsonb not null, -- timeout, retries, overlap, catch_up, on_lost
target jsonb not null, -- pool, handler, payload
paused boolean not null,
version bigint not null -- raised by every edit
)
runs ( -- upcoming, running and just finished
job_id text,
scheduled_for timestamptz, -- the schedule's time, in UTC
partition int not null,
due_at timestamptz not null, -- scheduled_for plus the job's offset
state text not null, -- SCHEDULED, QUEUED, RUNNING, RETRY_WAIT,
-- then SUCCEEDED, DEAD, SKIPPED, UNKNOWN
attempt int not null, -- 0 until a worker starts it
failures int not null, -- failed attempts; the retry limit counts these
epoch int not null, -- region lease epoch at the start (deep dive 6)
definition jsonb, -- one-off runs only: target, payload, policy
wake_at timestamptz not null, -- when a dispatcher must look at it next
deadline_at timestamptz, -- the running attempt's timeout
job_version bigint not null,
primary key (job_id, scheduled_for)
)
create index runs_wake on runs (partition, wake_at);
dead_letters (
job_id, scheduled_for, attempts, last_error, died_at,
primary key (job_id, scheduled_for)
)
-- In Cassandra
run_history (
job_id, month, scheduled_for, attempt, state,
due_at, started_at, finished_at, error,
primary key ((job_id, month), scheduled_for, attempt)
) with clustering order by (scheduled_for desc)
and default_time_to_live = 2592000; -- 30 days
Four things to note.
The primary key is the run's name. (job_id, scheduled_for) can't be inserted twice. A finished run leaves this table, so the key alone can't refuse a very late duplicate. The chain does. A recurring run's successor is inserted by its firing, which succeeds once, or by an edit, which holds the job row's lock and replaces the pending run.
One time column drives every state, wake_at. For SCHEDULED it's the due time. For QUEUED it's 5 minutes after the claim, a check for a lost message. For RUNNING it's the end of the lease or the deadline, whichever comes first, and for RETRY_WAIT it's the end of the backoff. A finished run's wake_at is now, so the next poll moves it to history. The dispatcher polls one index and acts by state.
scheduled_for and due_at are different times. The first is what the schedule said, and it's part of the name. The second is when the dispatcher fires the run, after the job's offset inside its window. Lateness is measured from due_at.
attempt and epoch together are the fence. Each start adds one to attempt and writes the region's current epoch, and every heartbeat and finish has to match both.
The queries that carry the product
-- 1. A dispatcher polls one partition, every second
select job_id, scheduled_for, due_at, state, attempt, definition
from runs
where partition = $1 and wake_at <= now()
order by wake_at
limit 500;
-- 2. Fire a batch of due runs and insert their successors, in one commit
begin;
select job_id, version, schedule, window_s, -- the batch's recurring jobs
policy, target, paused from jobs
where job_id = any($1) for share; -- an edit waits, or this waits
update runs set state = 'QUEUED', wake_at = now() + interval '5 minutes'
where (job_id, scheduled_for) in (select * from unnest($1, $2))
and state = 'SCHEDULED'
returning job_id, scheduled_for; -- only these were fired
-- insert one successor per returned recurring run: the next
-- time from its schedule, due at that time plus its offset
commit;
-- then send each returned name to its pool's ready queue
-- 3. A worker starts an attempt; $3 is the timeout, $4 the region's epoch
update runs
set state = 'RUNNING', attempt = attempt + 1, epoch = $4,
deadline_at = now() + make_interval(secs => $3),
wake_at = least(now() + interval '60 seconds',
now() + make_interval(secs => $3))
where job_id = $1 and scheduled_for = $2 and state = 'QUEUED'
returning attempt;
-- 4. A heartbeat, fenced by the attempt and the epoch
update runs set wake_at = least(now() + interval '60 seconds', deadline_at)
where job_id = $1 and scheduled_for = $2
and state = 'RUNNING' and attempt = $3 and epoch = $4;
-- 0 rows: a newer attempt owns the run. Stop.
Query 1 runs on a fixed clock, 1,024 times a second however busy the system is. Queries 2, 3 and 4 each handle about 5,100 runs a second, query 2 in batches and query 4 at one heartbeat per run on average.
Query 2 is the one an interviewer pushes on, usually by asking what happens if the dispatcher dies between the commit and the send. Its runs then sit in QUEUED with no message. Whichever dispatcher takes the partition next, including the same one restarting, sends every QUEUED run in it again straight away. A duplicate message gets 0 rows from query 3, which is a 409 to the worker.
The 5 minute wake_at catches a message the broker loses later, and it doesn't resend blindly, because a queue with a backlog can hold a message for longer than that. The dispatcher compares the age of the oldest message waiting in the pool's queue with the time since this run's message was sent. If the oldest is younger, everything sent before it has been delivered, so this message was lost, and it goes out again. This is an outbox, with the run's row as the record of what still has to be sent.
3. Run it on a worker: what happens when one dies mid-run?
A worker takes a run's name from its pool's ready queue, starts an attempt with a conditional update on the run's row (query 3), and then acknowledges the message. From that point the run's row decides who owns the run, not the broker.
The worker can crash, freeze or lose its network at any moment while the handler runs. Runs average 20 seconds, but the same pools also carry jobs that take hours. So how is a run started again after its worker dies, whatever its length? And how is the first attempt stopped from finishing on top of the second?
Hold the message until the job is done
Leave the message unacknowledged while the job runs, and let the broker's visibility timeout bring it back if the worker dies. SQS lets a worker set that timeout for one message and extend it with ChangeMessageVisibility while the job runs. So it can work as a lease, with no sweeper of your own.
It's a lease the broker holds, and that has costs. SQS caps it at 12 hours from the message's first receipt, and extending it doesn't reset that cap. The run's row and the target can't see it. And it carries no number they could check, so a worker that stalls past it and wakes up has nothing to refuse its writes. A worker that forgets to extend in time hands the job to a second worker while it's still running, as message queues vs event streams walks through.
A lease, renewed by heartbeats
Each attempt gets a short lease, and the worker renews it. Here the lease is 60 seconds, a heartbeat every 20 seconds renews it, and the dispatcher re-queues any run whose lease has passed. A dead worker's run is back in the queue within about a minute, whether the job takes 20 seconds or 6 hours. ATF does this. Its heartbeat timeout covers three missed heartbeats, and an executor stops itself after three heartbeats fail.
The cost is that it depends on the old worker noticing it has lost the lease. A worker frozen by a garbage collection pause, or by its virtual machine being moved, runs no checks while frozen. It wakes after attempt 2 has started, still sure it owns the run, and carries on. Its result lands on top of attempt 2's, and its handler repeats whatever it was doing.
Fence the attempt, and key each effect on the run's name
Question the premise that the scheduler can stop the first attempt. It can't: the attempt runs on another machine, and that machine may not be running at all. The scheduler controls two things, its own rows and what it tells the handler.
So it fences its rows. Every heartbeat and finish carries the attempt number and epoch, and query 4 changes nothing unless they match. Attempt 1's late result gets 409 and is thrown away. That 409 is how attempt 1 learns it no longer owns the run.
The handler's side effects live outside the scheduler, in a payments API or an email provider, and nothing there knows attempt numbers. They're protected the other way. Each effect gets an idempotency key made of the run's name plus the effect's own identity, such as job_8f2@2026-11-10T02:00:00Z/charge/inv_42 for the charge on invoice 42. Attempt 2's charge for invoice 42 gets back attempt 1's result instead of charging again, and its charge for invoice 43 is new work. One key for the whole run would hand invoice 43 the result of invoice 42, or a 422 from a target that checks the request body.
If attempt 2 arrives while the target is still working on attempt 1's call, the target answers 409, which means retry later. The scheduler's own 409 means stop. The web crawler meets the same limit with websites, which can't check a fence either.
What you give up. Every target has to keep the keys it has seen for as long as a run can still be attempted. That's the 24 hour retry limit in section 4 plus the job's timeout, because a last retry can start near hour 24 and run for its whole timeout. A dead run sent through again by hand after that has to check the target first, or go out under a new name. And some jobs can't be made safe to repeat, such as a call to a partner API that accepts no key. Those set on_lost: hold. When their lease or deadline passes, the run is marked UNKNOWN, not started again, and its owner is paged to find out what happened.
4. Retry, time out and record: what happens to a run that keeps failing?
An attempt ends in one of four ways. The handler returns success, returns a failure it calls retriable, returns a failure it calls fatal, or runs past its deadline. Success ends the run as SUCCEEDED, and a fatal failure ends it as DEAD. A retriable failure or a passed deadline starts a wait, and then another attempt.
The wait grows: 30 seconds, then 60, 120 and 240, doubling up to a cap of an hour. Each wait also gets full jitter, which means the actual wait is a random time between zero and that value, so runs that failed together don't come back together. Circuit breakers, bulkheads and backpressure shows the waves that form without it. The run waits in RETRY_WAIT with wake_at at the end of the wait, so the same poll picks it up.
Retries stop at a count or an age, whichever comes first: 5 failed attempts, counted in failures, or 24 hours by default. EventBridge Scheduler has the same two limits, up to 185 retries and up to 24 hours. Then the run moves to DEAD, its last error goes into dead_letters, and the job's owner is told. A person can send a dead run through again as a new attempt under the same name, as long as its targets still hold its keys (section 3).
A lease catches a dead worker, and only a deadline catches a stuck one. A worker stuck in a loop keeps heartbeating, because the process is alive. So every attempt also has a deadline, the job's timeout_seconds, and a running attempt's wake_at is the lease end or the deadline, whichever comes first. Past the deadline, the dispatcher moves the run to RETRY_WAIT with the next attempt's wait, or to UNKNOWN if the job says hold, and the stuck worker's next heartbeat gets 409.
Long jobs need one more thing. A 6 hour job that crashes at hour 5 and starts again repeats 5 hours of work. Its handler should save progress under the run's name, such as the last file it finished, and a new attempt should start from there.
A recurring job can also fall due while its previous run is still running or retrying. The overlap setting decides. skip records the new run as skipped, queue_one holds one run until the previous one finishes, and allow runs both. Skip is the default, as it is in Temporal's schedules, because most handlers were never written to run twice at once. The dispatcher checks this before it fires: if the job's previous run is still in runs and not finished, the new one goes to SKIPPED in the same commit. Catch-up runs under all are the exception, and wait for the run before them.
A finished run stays in runs until the next poll of its partition. The dispatcher writes it to Cassandra, keyed by job, month, scheduled time and attempt, and then deletes the row. If the dispatcher dies in between, the next one writes the same history row again, which changes nothing, and then deletes.
Deep dives
Deep dives 1, 2 and 3 come up in most versions of this interview.
1. Many dispatchers: what stops two of them firing one run?
The runs table holds every upcoming run, and dispatchers fire them. One dispatcher is a single machine that can die, and several can collide. The usual instinct is to run one at a time and elect it.
One dispatcher, holding a lock in Redis
Each dispatcher tries to set a key in Redis with a 10 second TTL, a time to live after which Redis deletes the key, and the holder keeps refreshing it. Whoever holds the key reads the due runs, sends them, and moves each job to its next time. It takes an afternoon to build, and it works in testing.
It fails the way replication and leader election describes. The holder pauses, the key expires, a second dispatcher takes it, and the first wakes up still sure it leads. Both read the same due runs, and nothing in the database refuses the second send, so every run due in that window fires twice.
Every dispatcher competes, and the row lock decides
Skip the election. Run several dispatchers against the table, each claiming due rows with FOR UPDATE SKIP LOCKED. A row one dispatcher has locked is invisible to the others, so each run is claimed once. Airflow lets you run as many schedulers as you like this way on Postgres or MySQL.
The cost is that every dispatcher scans every partition. Adding a dispatcher adds another poller at the head of the same index, not capacity. Clustered Quartz shows where the other common design ends up: its nodes take triggers under one cluster-wide lock, and its documentation says that degrades performance beyond about three nodes.
Owners for speed, the row for safety
Question the premise that exclusive ownership is what stops a double firing. In this design it isn't. Query 2 moves a run from SCHEDULED to QUEUED, and only one transaction can do that. A second dispatcher's update of the same run changes nothing and doesn't return it, so it inserts no successor and sends no message.
Ownership can be wrong, and the database still fires each name once. Every poll and claim also uses the shard's own now(), so one clock decides what's due in each partition.
That frees ownership to be about efficiency. Each live dispatcher holds a session lease in etcd, renewed every 3 seconds, with a 10 second TTL. Partitions go to live dispatchers by rendezvous hashing, which ranks every dispatcher for each partition so that all of them agree on the top one. Each of 16 dispatchers then polls its own 64 partitions, with no locks to step over.
Splitting the work by job removes the election, as replication and leader election says. It doesn't remove the moment a partition changes hands. When a dispatcher pauses and its lease runs out, the new owner starts polling, and the old one may still be in the middle of a poll. For those seconds two dispatchers poll one partition, and the row lets only one of them fire each run.
Sized: with 16 dispatchers, a dead one leaves 64 partitions, a sixteenth of all runs, unpolled until its lease runs out. Those runs start up to about 11 seconds late, the 10 second TTL plus a poll, once per dispatcher failure. That spends part of the 5 second target on a rare event, and it's why the TTL is 10 seconds and not 60. A batch the dead dispatcher claimed and never sent is late by the same amount, because the new owner sends every QUEUED run again when it takes the partition.
What you give up. etcd is one more system to run, although it holds only 16 leases. And every write a dispatcher makes must be a conditional state change, never a blind one. A dispatcher that sets state = 'QUEUED' without checking the old state turns the overlap back into a double firing.
2. Everything at 00:00
A cron expression names a minute, and people pick the same minutes. Every hour starts with a spike at :00. Midnight UTC is the largest, when hourly, daily, weekly and monthly jobs fall due together. Google's chapter says its cron load stayed "very spiky" even after it let teams leave the exact time to the system.
The question is which part of the system the spike at
00:00 breaks. Assume 2M runs are due at 00:00:00 UTC, a
fifth of the recurring schedules.
Normal load, each run taking 20 s on average, assumed
runs a second 5,100
in flight 5,100 × 20 s = 102,000
worker slots, twice the average = 204,000
spare slots = 102,000
spare runs a second 102,000 / 20 s = 5,100
The spike, on the workers
due in one second = 2,000,000
drained by spare 2,000,000 / 5,100 ≈ 392 s
slots to start all of them at once = 2,000,000
hosts at 50 slots each = 40,000
against the fleet 204,000 / 50 = 4,080
The spike, on the database
fire and insert the successor, 2 writes each
spare on each shard 5,000 − 30,600 / 16 ≈ 3,100/s
2M × 2 / 16 shards / 3,100 a second ≈ 81 s
─────────────────────────────────────────────────────
The last run starts six and a half minutes late. The
database could fire every run in a minute and a half.
Workers are what's short, and the targets behind them
would get 2 million calls at once.So midnight is a worker problem and a target problem, and a faster scheduler doesn't help. The question is how to spread 2 million runs so they fit in the spare capacity, without breaking the jobs that need midnight.
Add capacity for midnight
The spike is predictable, so scale the worker fleet up before it, on a schedule. That at least avoids autoscaling's lag, which is minutes against a spike that arrives in one second (capacity planning).
Starting all 2 million at once needs 40,000 hosts, ten times the fleet, for a few minutes each midnight. And the services behind the workers, a billing service or a partner's API, get 2 million calls in a second. Nobody sized them for that either.
Random jitter, and a limit per tenant
Add a random delay to each run when it fires. Cap how fast each tenant's runs enter the ready queues with a token bucket per tenant, so one tenant's million midnight jobs can't take every slot. The buckets live in Redis, shared by all 16 dispatchers, as the rate limiter builds them. A run over its tenant's limit isn't refused: the dispatcher leaves it SCHEDULED and moves its wake_at to when the bucket will have a token.
The jitter has to be wide to do anything. The backlog drains at the spare 5,100 runs a second however the runs arrive, so a 60 second jitter still leaves the last run 392 seconds late. Jitter wide enough to fit the spare capacity, about 400 seconds, moves runs that needed 00:00 by minutes. And a random delay lands somewhere different each night, so a job's start time wanders. The tenant limit keeps tenants apart, but it promises nobody a time.
Ask each job how late it may start
Question the premise that 0 0 * * * means 00:00:00. Most jobs written that way mean "once a night, around midnight", and the scheduler can't tell them from the few that mean it exactly. So the API asks. window_minutes says how late a run may start, and a job that needs 00:00 says 0.
Each job then gets a fixed offset inside its window, hash(job_id) mod window, and that offset sets its due_at. The same job starts at the same moment every night, so its owners can plan around it. The run's name doesn't change: it's still @00:00, so catch-up, retries and deduplication work as before. Lateness is measured from due_at, so a job that starts at 00:17:41 by design isn't counted as late.
Google's cron did this with a ? in a crontab field, which means any value is acceptable, and filled it by hashing the job's configuration over the allowed range. EventBridge Scheduler calls it a flexible time window, and makes every schedule say whether it has one.
Sized: say 95 percent of the 2 million accept a 30 minute window. 1.9 million spread over 1,800 seconds add 1,056 runs a second, about a fifth of the spare 5,100. The 100,000 strict runs fit in the 102,000 spare slots and start at once.
What you give up. The product has to ask, and the field has to be required, or most jobs keep whatever the default is. Strict runs still need the spare slots free at :00, so they go to a higher-priority queue in each pool. And the per-tenant limit stays, because one tenant can still put 100,000 strict jobs on midnight.
3. How many servers, and what actually needs scaling?
The question is which tier grows with the load. 5,100 runs a second on average, 20 s each. Database 16 Postgres shards 30,600 / 16 ≈ 1,900 writes/s data on each 63 GB / 16 ≈ 3.9 GB each with a standby in another zone = 32 servers Dispatchers one batch of 500 firings in one commit, ~50 ms, assumed per dispatcher 500 / 0.05 s = 10,000 runs/s one could fire every run; run 16, so a failure delays a sixteenth of the runs, not all of them Workers in flight 5,100 × 20 s = 102,000 slots, twice that = 204,000 hosts at 50 slots each = 4,080 History, in Cassandra 132 GB a day × 30 days × 3 copies ≈ 12 TB ───────────────────────────────────────────────────── The scheduler itself is a few dozen machines. The workers are about 4,000, and they grow with how long jobs take, not with how many jobs there are.
The same 5,100 runs a second at 60 seconds each would need three times the worker hosts. The database would feel it too: three heartbeats a run instead of one makes 8 writes a run, 40,800 a second, and about 21 shards. Each pool autoscales on its backlog per worker, the signal capacity planning uses for workers behind a queue, up to a ceiling set by what its targets can take. Each team's pool is sized for its own handlers. One team's slow handler then fills its own pool's queue, and no one else's.
The other tiers change rarely. Adding a 17th dispatcher moves about a seventeenth of the partitions under rendezvous hashing, and the overlap from deep dive 1 makes the move safe. Adding a shard moves whole partitions, each one's firing stopped while its rows copy. That's the stop-and-copy partitioning and sharding warns against, because nobody gets the maintenance window it needs. Here the window is a few seconds a partition, since a partition is about 62 MB, so it's chosen on purpose, and its runs are late by that much.
4. Time zones and daylight saving
A team that writes "01:30 London" means 01:30 on the clock in London, in winter and in summer. So the job stores the cron expression and a zone name from the time zone database the Internet Assigned Numbers Authority (IANA) maintains, such as Europe/London. It never stores a fixed offset from UTC. When a run fires, the next time is computed in that zone, converted to UTC, and written into the next run's name.
On two days a year, the local clock doesn't map one to one onto UTC. EventBridge Scheduler documents what it does on each.
When the clocks go forward, an hour of local time doesn't exist. On 29 March 2026, London's clocks jump from 01:00 to 02:00, so a job set for 01:30 has no moment that day. EventBridge skips the run. This design runs it at 02:00 local, the first minute after the gap, because a team that wrote "daily" usually expects a run that day. EventBridge's skip also meets requirement 3, as long as the skip is recorded, so either answer works if it's chosen and written down. For an hourly job, the moved 01:00 run lands on the same instant as the 02:00 run, so the two share one name and run once.
When the clocks go back, an hour happens twice. On 25 October 2026, 01:30 in London is 00:30 UTC, and an hour later it's 01:30 again. A scheduler that asks for "the next 01:30" after firing at 00:30 UTC finds the second one and fires twice. Here, like EventBridge, the job runs once, at the first. The next time is computed from the next local date, 26 October, and never from the next instant that reads 01:30.
Two more rules. A rate is not a time of day: "every 24 hours" moves an hour against the local clock at each change, and EventBridge treats rate(1 days) as exactly 24 hours for that reason. And the rules themselves change. The IANA database is updated when a country changes its rules, and the pending runs in that zone were computed with the old ones. Applying an update means recomputing the next run of every job in the zones it changed.
5. Jobs that depend on other jobs
Some jobs wait for others, such as a report that needs the night's export. The dependency is between runs, not jobs. Tuesday's report waits for Tuesday's export, not for whichever export ran last.
In this design that's one more use of the name. A graph of jobs gets one name per scheduled time, and each step's run is that name plus the step, such as nightly@2026-11-10T02:00:00Z/report. A step's run is created when the runs of the steps before it succeed, not by a timer. A step that fails is retried under its own name, without running the steps before it again. Airflow's scheduler works the same way: it creates a run of the whole graph, then queues each task in it once the tasks before it are done.
Anything beyond that, such as branches, waiting for a signal from outside, or state carried from one step to the next, is a workflow engine. The scheduler can start a Temporal workflow or an Airflow graph like any other target.
6. Multi-region
Every multi-region design starts with where a write lands, as multi-region and disaster recovery says. Here the writes are a run's state changes, and two regions changing one run's state is the double firing this design exists to prevent. So each tenant gets a home region. Its jobs, runs, dispatchers and worker pools live there. A second region keeps an asynchronous replica of that tenant's shards and stands by.
That's partitioning by tenant across regions, plus replication of each home to one standby. With two regions, each homes half the tenants and stands by for the other half. The cost is spare worker capacity in each region for the other's load, since workers are almost all of the machines.
The old region has to stop accepting writes before the new one starts. The region lease from that page does it. A region accepts any write, firings and worker calls alike, only while it holds a lease it renews through a consensus group spread over three regions. A region that is cut off can't renew, so it stops firing and refuses its own workers' starts and heartbeats. The standby takes over only after that lease has run out, plus a margin for clock drift. The page puts the lease at 30 seconds, so runs in the moved tenants start about 30 to 40 seconds late during a failover.
A failover then repeats some runs under the same names, and how many depends on how region A failed.
- A crashes. It fires nothing more. Its replica in B is behind by the replication lag, say 2 seconds, so runs A fired in those 2 seconds still look
SCHEDULEDthere, and B fires them again. At 2,550 runs a second, half the load, that's about 5,100 runs. - A is cut off but alive. It keeps firing until its lease runs out, 30 seconds later, and none of that reaches B. B fires all of it again, plus the lag: (30 + 2) seconds × 2,550 ≈ 82,000 runs.
Either way, every run that was running in A, about 51,000, looks RUNNING in B with a lease nobody will renew, and gets a second attempt when the lease passes. The targets see keys they already hold and return the stored results.
The fence needs one more part here. B's replica doesn't know which attempt numbers A handed out during the lag, so B could start attempt 1 of a run that A also started as attempt 1. If A's workers can still reach B's API, two workers would hold the same number. So every start also writes the region lease's epoch, and query 4 checks it. B's attempts carry epoch 8 and A's carry epoch 7, so the pair never repeats.
hold jobs have no keys to fall back on, so B doesn't fire them blind. On takeover, before its dispatchers resend anything, it marks as UNKNOWN every hold run that is QUEUED or whose wake_at has passed. For each one that was still SCHEDULED, it inserts the successor as a firing would, and marks that one too if it's already due, so the job's schedule carries on. Then it pages the owner.
7. How do you know it is working?
The service level indicator (SLI) is the share of runs that start within 5 seconds of their due_at, and the service level objective (SLO) from requirement 2 is 99 percent. Lateness, started_at minus due_at, goes into a histogram per pool with a bucket boundary at exactly 5 seconds, so the share is a count, not an estimate. Observability covers turning that into an error budget and paging on how fast it's spent.
During an incident, four questions need answers quickly.
- Are runs starting late, and where? The share on time per pool, and the oldest overdue run per partition.
- Are runs failing? Attempts per run and dead letters per pool. More second attempts with no more failures means workers are dying or pausing.
- Is one tenant crowding the others? The age of each pool's ready queue, and each tenant's use of its limit.
- Is the database keeping up? Writes per shard against the 5,000 planned, and dead rows in
runs.
Don't label any metric by job ID. 60 million jobs would make 60 million time series. "Did my job run last night?" is a read of run_history, not a dashboard.
Final design
One run, end to end:
- A team creates a job. The API writes the job row and its first run, named by the job and its scheduled time in UTC, in one transaction on the shard that holds the job's partition. A one-off job is written as its run row alone.
- The dispatcher that owns the partition, through its lease in etcd, polls the partition's
wake_atindex every second. - When the run's
due_atpasses, the dispatcher reads the job rowFOR SHARE, moves the run fromSCHEDULEDtoQUEUEDand inserts the next run, in one commit. Then it sends the run's name to the pool's ready queue, within the tenant's limit, with strict runs on the higher-priority queue. - A worker takes the name, starts attempt 1 with a conditional update that also writes the region's epoch, and acknowledges the message.
- The handler runs, and builds each effect's idempotency key from the run's name and the effect. The worker sends a heartbeat every 20 seconds, fenced by the attempt number and epoch.
- The worker reports the outcome, fenced the same way. A retriable failure waits with backoff and jitter, then starts a new attempt. A fatal failure, or the last attempt failing, moves the run to
dead_letters. - If the lease or the deadline passes first, the dispatcher re-queues the run for its next attempt, or marks it
UNKNOWNif the job sayson_lost: hold. - On its next poll, the dispatcher writes the finished run to Cassandra, keyed by job and month, deletes the row, and reports the oldest overdue run in each partition.
The numbers behind the shape: 440 million runs a day is 5,100 a second, and each run's row is written six times. 30,600 writes a second need 16 Postgres shards, for only 63 GB of data. 102,000 runs in flight need about 4,000 worker hosts, almost all of the machines. And the 2 million runs due at midnight fit in the spare capacity only because 95 percent of them accept a window.
What is expected at each level
How interviewers turn what they see into these levels is in How a System Design Interview Is Scored.
Mid-level
Breadth matters more than depth at this level, and it's fine to be led.
You should store jobs in a database, find due ones with an index on the next run time, and hand them to workers through a queue. You should say what happens when a worker crashes: something notices and starts the run again. You should know what retrying with backoff means, and why every job needs a timeout.
You aren't expected to raise fencing, partition ownership or daylight saving without being asked. You are expected to answer "what if this job runs twice?" with something better than "it won't". A good answer says which jobs can run twice, and what the others need.
Senior
You drive the structure, and three things should come up without prompting.
A name for each run. Say how a run is identified, and use that to stop a second firing and to build the job's idempotency keys, one per effect. Without it, nothing downstream can tell a retry from a new run.
A worker that dies or pauses. A lease with heartbeats, a deadline separate from the lease, and what the first worker does when it wakes up.
The midnight spike. Say it exists, size it, and say what spreads it.
Two things are disqualifying: promising exactly-once execution, and a design whose only protection against a double run is a leader election.
Staff+
A correct design is still the bar. A staff+ answer also decides what not to build.
Put the guarantee in the row, not the lease. A run fires through a state change that only one transaction can make, so dispatcher ownership can be wrong for a few seconds without harm.
Fence the attempt and name the effect. The attempt number and epoch refuse a stale worker's writes, keys built from the run's name and each effect let targets drop repeats, and on_lost: hold covers the jobs that can't repeat at all.
Find that midnight is a worker problem. 2 million runs at 00:00 need ten times the fleet, while the database could fire them in a minute and a half. Then change the API, so each job says how late it may start.
Size the database by its writes. 63 GB fits on one machine, and six writes per run don't.
Be able to say what you would not build. No leader election of your own, when a conditional update already refuses a second firing. No exactly-once promise in the API. No delay queues on the broker for runs more than minutes away. No year of future runs stored per job. No worker fleet sized for midnight. No time zone arithmetic of your own, when the IANA database and a library already exist. A team could spend a quarter on any one of these.
Sources
Each figure about a real system above comes from one of these, read for this page. The fleet sizes, rates and timings are assumptions, worked through in the worksheets where they're used.
- Štěpán Davidovič, edited by Kavita Guliani, Distributed Periodic Scheduling with Cron, chapter 24 of Google's Site Reliability Engineering book, published in part in ACM Queue in March 2015 as "Reliable Cron across the Planet". Launch names that include the scheduled time, which the book calls a reasonable solution, and a new leader launching only the missing names. Skipping over double launching, the garbage collection, newsletter and payroll examples, the
?field, and the one-minute failover. - Dropbox, How we designed Dropbox ATF: an async task framework, 2020. The Store Consumer polling every two seconds and pushing to SQS, and controllers on the worker hosts. Heartbeats covering three missed beats, 95 percent of tasks starting within five seconds, and 9,000 tasks a second.
- Amazon EventBridge Scheduler documentation: schedule types for time zones, daylight saving and
rate(1 days); FlexibleTimeWindow for windows every schedule must declare; RetryPolicy for 185 retries and 24 hours; and quotas for 10 million schedules per Region. Also SQS delay queues, for the 15 minute ceiling, and the SQS visibility timeout, for per-message timeouts and the 12 hour cap from first receipt. - Temporal documentation, Schedules and Workflow Id and Run Id. The scheduled time appended to each run's workflow ID, one open execution per ID, and skip as the default overlap policy.
- PostgreSQL documentation: SELECT for
SKIP LOCKEDand queue-like tables, the architecture overview for a process per connection, and connection settings for the default limit of 100. - Quartz's clustering configuration and Airflow's scheduler documentation. Quartz's cluster-wide lock, which degrades performance beyond about three nodes, and Airflow's row locks, chosen over consensus for operational simplicity.
- Yasuhiro Matsuda, Apache Kafka, Purgatory, and Hierarchical Timing Wheels, Confluent, 2015. Timing wheels, with constant-cost insert and delete.