GOAT EngineerPreparing your learning space…

System Design · Interview breakdown · Free article

Design a Distributed Job Scheduler (Cron)

Find the runs due this second among ten million jobs, give each run to one worker at a time, and keep a retry from doing the work twice. Built one step at a time, with experiments you can run.

A job scheduler runs work at a time someone chose: once, or on a repeating schedule such as every weekday at 09:00. Store each job with its next run time in a database. Load the runs due in the next few minutes into a set ordered by time, and hand each one to a queue at its second. A worker takes a run under a short lease with an attempt number, and records the result only if its attempt still owns the run. A run can be delivered twice, so the work uses the run ID to make a repeat harmless.

Difficulty: Medium. Reported in interviews at Robinhood, LinkedIn, DoorDash, Airbnb, Meta. Also asked as Design a distributed cron, Design a task scheduler, Design Airflow, Design a delayed job queue.

Practise one part of it on a canvas that tests your design: Run 3,000 Jobs That Come Due at Once.

How do you design a distributed job scheduler?

A job scheduler runs a piece of work at a time someone chose. The work can run once, like “email this customer again in three days”. It can also repeat, like “every weekday at 09:00”. The hard part is starting millions of these on time, when any machine can stop at any moment.

  1. Schedule: 09:00 weekdays, Lisbon. Ten million jobs are stored, and only a few are due each second. Finding those few must be cheap.
  2. Due: 09:00:00 · 100k due. People pick round times, so a hundred thousand runs can come due in the same second.
  3. Run: worker 17 · attempt 1. A worker can freeze halfway. Another must finish the run. The work must not happen twice.
  4. Retry: attempt 2 in 20 s. When the email service is down, thousands of retries must not hit it in the same second.
  5. History: 09:00 ✓ · 2 attempts. Did it run, when, and how many times? The answer must be exact for thirty days.
Ana sees five screens. Behind them, one platform runs ten million jobs like hers.

Picture Ana, who runs billing at a small software company in Lisbon. She creates a job called invoice reminders. It runs every weekday at 09:00, Lisbon time. Each run finds the customers whose invoices are overdue, about 120 of them, and emails each one a reminder. She also has a job that refreshes an exchange-rate table every ten minutes.

On one laptop, this is a cron line and a script. A platform that runs jobs for thousands of teams like Ana’s is a different thing. It stores ten million jobs. At 09:00 a hundred thousand of them come due in the same second. A worker can freeze in the middle of Ana’s run. The email service can be down when the run starts.

Interviewers like this problem because the easy parts look finished after ten minutes. The rest of the round is about time and failure.

Here is the design in four sentences. Store every job in a database with the time of its next run. A scheduler loads the runs due in the next few minutes into a set ordered by time, and hands each run to a queue at its second. A worker takes a run under a short lease with an attempt number, and records the result only if its attempt still owns the run. A run can be delivered more than once, so the work itself uses the run’s ID to make a repeat harmless.

The rest of this page is about the moments that design has to survive.

Here is the first one. At 09:00:00 worker A takes Ana’s run. At 09:00:12 A’s process freezes, before it has sent anything. Something has to notice and give the run to worker B. Then A wakes up at 09:01:22 and carries on from where it stopped. If nothing stops A, every customer gets two reminders.

Here is the second. Worker B sends all 120 reminders. Its machine dies before it can record that the run succeeded. The run looks unfinished, so worker C runs it again. A design with no answer to that loses the round.

What is the interviewer testing?

Most candidates draw an API, a jobs table, a scheduler that polls it, a queue and some workers in the first ten minutes. That drawing is right. A mid-level answer often stops there.

The interviewer then pushes on six questions. A hundred thousand jobs are due at 09:00: how does each one start on time? A worker freezes halfway: who finishes the run, and what stops the first worker? The work finished, but the worker died before saying so: does the work happen twice? The email service is down: what do thousands of retries do to it? The scheduler itself was down for half an hour: what happens to the runs it missed? One team queues a million runs: does everyone else wait?

A senior answer handles the first three. A staff answer also handles the retry storm, missed runs and time zones, and fairness between teams.

Spend most of the deep-dive time on the 09:00 wall, the frozen worker and the repeated work. Retries and missed runs are the usual follow-ups. Fairness between teams and time zones are where a staff round goes. How to run a round has the time plan for a 45 to 60 minute round and a 15-minute screen.

What should you ask before drawing anything?

Four questions change the design. Ask them in the first two minutes. If the interviewer leaves one open, say your assumption out loud.

What does a job run: our code, or theirs?
A job that calls a URL, or runs a task our workers already know, is a timing problem. A job that runs any code a customer uploads is also a sandbox problem, with images, isolation and resource limits. Assume known tasks and HTTP calls. Uploaded code is out of scope.
How late may a run start?
A reminder email sent at 09:00:40 harms nobody. An order that must go out as a market opens cannot wait a minute. Assume 99% of runs start within 5 seconds of their time, and let a job declare a looser window.
May a run happen twice?
Picture a report written twice: the second copy replaces the first, and nobody notices. Now picture a customer charged twice. Assume any run may be delivered twice. Assume too that a job with side effects accepts a run ID to make a repeat harmless.
Do jobs wait for other jobs?
A job that starts only when three others finish is a workflow, like an Airflow pipeline. Assume independent jobs. Workflows are out of scope. The other-names section says what they change.

Functional requirements

On the board: Functional requirements
1. Create, change, pause, delete a job
2. Once at a time, or cron in a time zone
3. Run it on time; retry, then alert
4. Show every run: status, attempts, error
out: workflows, uploaded code, < 1 s timing

Say it, don’t write it: The rule that never bends is that no accepted job, and no run of it, is ever lost.

The brief is a scheduling service shared by many teams. Two people use it: a team that creates jobs, like Ana’s, and the on-call engineer who hears when a run fails for good.

  1. A team creates a job, changes it, pauses it, resumes it and deletes it.
  2. A job runs once at a given time, or repeats on a cron schedule such as 0 9 1-5. The schedule is read in a time zone the team chooses.
  3. Each run starts at its time, within the promise below. A failed run is retried a limited number of times, then marked failed and reported.
  4. A team sees every run of a job for 30 days: when it was due, when it started, each attempt, and the result or the error. A team can also start a run by hand.

Out of scope

  • Jobs that wait for other jobs (workflows)
  • Running code a customer uploads, which needs a sandbox
  • Timing finer than 1 second
  • Billing and plans, beyond the per-team limits below

Three words need pinning down now. A job is the rule: invoice reminders, every weekday at 09:00. A run is one due time of that job: the reminders for Tuesday 14 April at 09:00. An attempt is one worker’s try at a run. Keeping the three apart is most of this design.

Non-functional requirements

On the board: Non-functional requirements
• 99% start within 5 s of their time
• An accepted job is never lost
• A run may repeat; its effect must not
• 100k due at 09:00 must not stall the rest
• A dead scheduler or worker loses no run
• One team cannot starve the others

Say it, don’t write it: The timing promise is soft and the loss promise is hard. A late run is annoying; a lost one is a bug nobody sees.

A run that starts at 09:00:04 instead of 09:00:00 harms nobody. A run that never happens is the worst failure a scheduler has, because nobody watches for something that did not occur. So the timing promise is a percentile. The promise against loss has no exceptions. The numbers are illustrative interview targets, not measurements of any real service.

  • 99% of runs start within 5 seconds of their due time. Measure it as start time minus due time, for every run.
  • A job the API accepted is never lost. It reaches replicated storage before the API answers.
  • No run is skipped without a record. A dead scheduler or worker loses no run, because an unfinished run becomes available again.
  • A run may be delivered twice. Its effect must not happen twice.
  • 100,000 runs due at 09:00:00 start on time, without delaying the runs due after them.
  • One team’s backlog does not delay another team’s runs.

Suppose the database cannot confirm a write. Then the API refuses the job, rather than saying yes and forgetting it. When two promises conflict, never losing a job wins over starting one on time.

The numbers on this page come from one made-up platform. It stores ten million jobs, which together make 20 million runs a day. The average run keeps a worker busy for 2 seconds. Each deep dive works out the numbers it needs from these.

Out of scope

  • Running any code exactly once; the page shows why no scheduler can promise that
  • Starting within milliseconds
  • Start times for a team that is over its limits

Core entities

On the board: Core entities
Job(id, team, schedule, tz, next_run_at)
Run(job, due_at, status, attempt, lease)
Attempt(run, n, worker, started, error)
unique (job_id, due_at) → one run a time

Say it, don’t write it: A job is the rule, a run is one due time, an attempt is one try. The run ID is what makes a retry safe.

Follow one run through the system. Ana’s job J7 is the rule: invoice reminders, weekdays at 09:00, Lisbon. On Tuesday 14 April the scheduler creates run R for J7 at 09:00. Worker A takes R as attempt 1 and freezes. Worker B takes R as attempt 2 and finishes. R succeeded once, after two attempts.

Four records carry this. The job holds the rule: its team, the cron schedule, the name of its time zone, the task and its arguments, and the next run time. It also holds the job’s policies, such as how many attempts a run gets and what a missed run means.

The run holds one due time of one job. It records the run’s status and its current attempt number. It also records which worker holds it, and when that worker’s lease runs out. A failed run records when its next attempt is due, and a finished one records its result.

The attempt is the history of one try: the worker, when it started and finished, and how it ended. The team and its support engineers read it when something went wrong. The team record holds the limits: how many jobs a team may create, and how many runs it may have going at once.

A run is named by its job and its due time. A unique key on (job_id, due_at) holds that. If two loaders both create the 09:00 run for J7, the second insert does nothing. Every later step names that run.

The attempt number never goes into the run’s ID. A retry is the same run, so it carries the same ID. If each attempt made a new ID, the email service would see each retry as a new request and send again.

A run started by hand is different. Ana presses Run now because she fixed a typo in the email and wants the reminders sent again. That is new work, so it gets a new run with its own ID. A retry of the 09:00 run keeps the old one.

API

On the board: API
POST /jobs {schedule, tz, task, args}
PATCH /jobs/:id · POST /jobs/:id/pause
POST /jobs/:id/runs (run now)
GET  /jobs/:id/runs?cursor=…
DELETE /jobs/:id

Say it, don’t write it: A request ID makes a retried create return the same job instead of a second one.

The API is small. What matters is that a retried request never creates a second job. A long history also has to be readable a page at a time.

RequestResponseRule it enforces
POST /jobs201 with the job and its next three run timesThe same request ID returns the same job; the schedule is checked here
PATCH /jobs/{id}200 with the job and its new next run timesCarries the version the client read, so two edits cannot overwrite each other
POST /jobs/{id}/pause, /resume200Pausing stops new runs; a run already going is not stopped
POST /jobs/{id}/runs202 with a new runA run by hand is new work, with a new run ID
GET /jobs/{id}/runs?cursor=…Runs newest first, with their attemptsA cursor, because history is long
DELETE /jobs/{id}204No new runs are created; history stays for 30 days
Concrete exchangeMeaning
POST /jobs with {"requestId":"c-41","schedule":"0 9 1-5","timeZone":"Europe/Lisbon","task":"invoice-reminders","args":{"daysOverdue":7}}201 {"jobId":"J7","nextRuns":["2026-04-14T08:00:00Z","2026-04-15T08:00:00Z","2026-04-16T08:00:00Z"]}
GET /jobs/J7/runs?limit=1200 {"runs":[{"dueAt":"2026-04-14T08:00:00Z","status":"succeeded","attempts":2}],"cursor":"…"}

Three fields exist for a reason. The request ID makes a create that timed out safe to send again. The time zone is a name, such as Europe/Lisbon, and never an offset such as +01:00. The offset changes twice a year. The name knows when. The next run times in the reply let Ana catch a mistake before it runs. For her 09:00 job, 08:00Z is correct in summer, and 09:00Z would be wrong.

The API refuses a schedule that runs more often than the team’s limit allows, such as every second. A job that fires 86,400 times a day by accident can use up a team’s share before anyone notices.

Step 1: create and manage jobs

Ana sends her job to the Job API. The API checks the cron expression and the time zone, computes the next run time, and stores the job in PostgreSQL. The reply shows her the next three run times.

The next run time is stored in UTC, next to the rule it came from. On 14 April, 09:00 in Lisbon is 08:00 UTC, because Portugal is on summer time. An index on next_run_at lets the scheduler ask for the jobs due soon without reading the other ten million.

Jobs and runs live in PostgreSQL for one reason. A run changes state under a condition: only if it is still waiting, only if this attempt owns it. A relational database does that in one statement. Ten million jobs at 1 KB each is 10 GB, which fits one database.

The interactive version of this example is available when JavaScript loads.

Nothing on this path is urgent. A create that takes half a second is fine, so long as the job is safely stored before the API says yes.

Step 2: run each job at its time

Every second, a scheduler asks the database for jobs whose next run time has come. For each one, it writes a run row, moves the job’s next run time forward, and puts the run’s ID on the ready queue. A worker takes the ID from the queue and claims the run in the database. Then it does the work and records the result.

The queue carries only IDs. The run row in the database is the truth. Suppose the queue loses a message: the run row still says the run is waiting, so the scheduler can queue it again. Suppose the queue delivers a message twice: the second worker finds the run already taken and drops the message.

The interactive version of this example is available when JavaScript loads.

The claim is a guarded update: take the run only if it is still waiting. Two workers handed the same ID both try, and only one changes the row. The second deep dive adds the lease and the attempt number that keep this safe when a worker stops halfway.

Step 3: retry failures, then give up

Ana’s run fails because the email service answers with an error. The worker records the failure on the run row, with a time for the next attempt 20 seconds later. When that time comes, the scheduler finds the run the same way it finds a due job. A retry is a run that is due again, so it needs no new box.

After the last allowed attempt, the run is marked failed. The on-call alert fires with the job, the run and the last error. The list of failed runs is the dead-letter list: someone reads it, fixes the cause, and retries the run by hand under the same run ID.

The interactive version of this example is available when JavaScript loads.

The fourth deep dive shows how to choose the wait between attempts, and how that choice can take down the service being retried.

Step 4: show every run

Ana opens her job and asks whether Tuesday’s reminders went out. The Job API reads the run rows and their attempts for that job, newest first, a page at a time. No new box is needed. The rows the workers already write are the history.

Each run keeps its due time, when it was queued, when each attempt started and finished, and why an attempt failed. Keeping those times apart answers the question every late run raises. Was it found late, queued late, or kept waiting for a worker?

Each run row, with its attempts, takes about 500 bytes. 20 million runs a day × 500 bytes × 30 days is 300 GB. So runs are kept in one table per day. When a day passes thirty, the whole table is dropped in one step, instead of deleting 20 million rows one by one.

A hundred thousand jobs are due at 09:00:00. How does each one start on time?

It is Tuesday 14 April. Ana’s invoice reminders are due at 09:00:00 Lisbon time. So are 99,999 other runs, because people like round times. The promise is that every one of them starts within 5 seconds: a worker has begun it by 09:00:05.

The day as a whole is easy. 20,000,000 runs ÷ 86,400 seconds is about 231 runs a second. Each keeps a worker busy for 2 seconds. More exactly the rate is 231.5, and 231.5 × 2 is 463, so about 463 workers are busy at any moment. Almost any design keeps up with that.

The wall is not easy. Those 100,000 runs are half a percent of the day’s 20 million, and they share one second. Starting them all within 5 seconds needs 100,000 ÷ 5 = 20,000 a second, about 86 times the average. At 2 seconds each, 20,000 a second × 2 is 40,000 workers busy at once.

On one machine, cron keeps a timer for each job in memory. Scaled up, that puts ten million timers in one process. When the process restarts, every timer is gone until it has read all ten million rows again. When the machine dies, nothing runs at all. So the jobs live in the database, and the question is how the 09:00 runs get out of it.

The design from step 2 polls. At 09:00:00 the scheduler asks the index on next_run_at for the jobs due now, and gets back 100,000 rows. Each run then costs two row writes: insert the run, and move the job to its next run time. Then its ID goes on the ready queue, a message queue such as Amazon SQS or RabbitMQ. Say one scheduler gets through 5,000 runs a second, which is 10,000 row writes. 100,000 ÷ 5,000 is 20 seconds, so the last run is queued at 09:00:20. A worker still has to take it after that, so it starts more than fifteen seconds late. The runs due at 09:00:01 wait behind the whole wall, so they are late too.

More schedulers help. Each takes its jobs with FOR UPDATE SKIP LOCKED, which passes over rows another scheduler has locked, so no two take the same job. Four schedulers get through 20,000 runs a second, and the last run is queued at 09:00:05. That is the deadline itself, and a worker still has to take the run and start it. So even four pollers miss the promise for the last runs, by however long that takes. Meanwhile the database takes 200,000 row writes in five seconds, 40,000 a second, on top of everything else it serves.

Look at what those writes depend on. Ana’s 09:00 run row says: job J7, due at 09:00, waiting. Nothing in it needs 09:00 to have arrived. The scheduler could have written it days ago. Every expensive step waited for the deadline, although none of them had to.

So do the writing early. Every few seconds, loaders ask the database for jobs due in the next five minutes. For each one they write the run row, move the job forward, and add the run’s ID to a Redis sorted set, the due-soon set. A sorted set keeps its entries ordered by a number called the score. Here the score is the due time. A job due every minute has five due times inside that horizon, so the loader writes five runs and moves the job past the last one.

The 09:00 jobs enter the horizon at 08:55. To finish by 09:00, the loaders need only about 333 a second, 100,000 runs over 300 seconds. That pace would finish at exactly 09:00:00 with no margin, so it is the floor, not the plan. Say the loaders cap themselves at 1,000 runs a second instead. The 09:00 runs take 100 seconds and are all written by 08:56:40, with 3 minutes 20 seconds to spare. That is 2,000 row writes a second, a twentieth of the four pollers’ 40,000.

At 09:00:00 only one step is left: hand out what is due. A dispatcher asks the set for every entry scored at or before now, removes them, and sends their IDs to the ready queue in batches. No database write happens here. Say one dispatcher hands out 50,000 a second. Both rates on this page are illustrative. Handing out is faster because it touches only Redis and the queue, never the database. 100,000 ÷ 50,000 is 2 seconds, so the last 09:00 run is queued at 09:00:02. That leaves 3 seconds for a worker to take it and start.

The wall still costs some writes in every design here. Each run writes its claim as it starts, and its finished record about 2 seconds later. So about 200,000 row writes land between 09:00:00 and about 09:00:07. Polling would have added the insert and the job update on top, so loading ahead halves the writes at the wall.

The set also tells the platform what is coming. By 08:56:40 it holds all the 09:00 runs, so the platform can count them. It will need about 40,000 busy workers, against 463 on an ordinary second. Nobody keeps 40,000 workers idle all day. A wall that comes every weekday at 09:00 lets the platform book those workers in advance. The count at 08:56:40 then confirms how many.

Guess when the last run leaves, then run 09:00. The Design chips switch between polling at 09:00 and loading five minutes ahead. The Schedulers chips show what four pollers buy.

The interactive version of this example is available when JavaScript loads.

The experiment stops its clock when the last run reaches the queue. A worker still has to start that run, so a design needs room between that moment and 09:00:05. The rates are illustrative, and other rates change the numbers, not which design wins.

The set raises three new questions.

The first is what happens when an entry is lost. Say a Redis failover at 08:59 comes back with an empty set. Or a dispatcher takes a batch of due entries and dies before it puts them on the queue. Either way, the runs are still rows in the database, marked waiting, but nothing hands them out. So the database stays the truth, and the set is only a copy of the next five minutes. After a failover, a loader rebuilds the set from every waiting run eligible up to five minutes from now, overdue ones included. Adding an ID the set already holds only sets its score again, so the rebuild can overlap whatever survived.

A sweep catches the rest. At the wall, tens of thousands of runs wait a few seconds for a worker, and that is normal. Other runs wait on purpose, in their team’s lane or behind a failing service, as later deep dives show. Those stay in the set while they wait. So the sweep measures from when a run became eligible: its due time, or its next attempt time for a retry. It looks only at waiting runs eligible more than 60 seconds ago whose IDs are in no set. Those were lost, and it adds them back. A run that was only slow can still reach the queue twice. The claim settles that: the second worker finds the run already taken, and drops the message. A dispatched time on each row would make the sweep exact, at the price of one more database write per run at the wall.

A run that waits while the scheduler is running is late. A run whose eligible time passed while no dispatcher was running at all is missed. Then the job’s missed-run policy decides what happens, as a later deep dive shows.

The second is two dispatchers handing out the same entry. Each dispatcher takes and removes due entries in one small script, which Redis runs without any other command in between (Redis). So one entry leaves the set once. One set holding 100,000 entries for one second is also one hot key on one Redis node. So the due-soon set is really many sets: one per team, as the fairness deep dive shows. A large team is split further by a hash of the run ID, and each dispatcher owns some of the sets.

The third is who runs the loaders. Many candidates reach for leader election here. One scheduler is active, a standby waits, and a lease in ZooKeeper or etcd decides which is which. It works. But the whole platform then loads only as fast as one machine. The handover also has a gap. A leader that was cut off from the network, not killed, can keep loading for a few seconds after the new leader starts. Both then create the 09:00 run for J7. The unique key on (job_id, due_at) makes the second insert do nothing, so the gap is harmless.

Once a double load is harmless, the leader is not needed at all. Many loaders share the jobs table with SKIP LOCKED, and the platform loads faster by adding loaders. PostgreSQL describes SKIP LOCKED as a way to avoid lock contention between several consumers of a queue-like table. It also warns that this gives an inconsistent view of the data (SELECT). That is the trade wanted here: each loader needs some due jobs, not a consistent list of all of them.

The interactive version of this example is available when JavaScript loads.

The loaders and the set now sit between the database and the queue. The database still holds every job and every run.

Two other structures can do the set’s job. On a standard Amazon SQS queue, each message can carry its own timer that hides it for up to 15 minutes (message timers). A loader could send each run with a timer that ends at its due time, and skip the dispatcher. Other designs keep a timing wheel in each scheduler’s memory: a ring of slots, one per second, each holding the runs due then. All three share one idea. The database knows every job, and a small, fast structure knows only the next few minutes.

Some jobs do not need their exact second. A nightly clean-up is happy anywhere between 02:00 and 02:10. Such a job can say so. The loader then spreads its runs across the window, using the job’s ID to pick a stable second. That flattens the wall before it forms.

The gap: Each run has to be found, written down, handed to the queue and started, and 100,000 runs share one second.

Option 1: A timer per job, in one scheduler’s memory

Load every job into one process and set a timer for each, as cron does on one machine.

Works when: One machine runs a few thousand jobs, and a run missed during a restart can be fixed by hand.

Breaks when: A restart forgets every timer until all ten million rows are read again, and a dead machine runs nothing.

Option 2: Poll for due jobs at the second

At each second, read the due jobs through the index, then write, move forward and queue each run.

Works when: Due times are spread out, as on a platform of a few thousand jobs.

Breaks when: All 100,000 runs are written at 09:00, so one scheduler queues the last at 09:00:20, and even four leave no time to start it.

Option 3: Load five minutes ahead, hand out at the second (start here)

Loaders write the next five minutes of runs and add each to a Redis sorted set by due time, and dispatchers hand out each second’s entries.

Works when: Load arrives in walls at round times: the writes finish minutes early, and the last 09:00 run is queued at 09:00:02.

Watch for: Redis holds only a copy, so a failover at 08:59 or a dispatcher crash can lose entries just before the wall.

Fix within it: The database stays the truth: a loader rebuilds the set, a sweep re-adds lost runs after 60 seconds, and the claim drops duplicates.

In the interview: Open with option 3, earned by option 2’s arithmetic: 100,000 runs at 5,000 a second queue the last one at 09:00:20. Mention option 1 only as the one-machine cron you are replacing. If the interviewer asks who runs the loaders, say many loaders with SKIP LOCKED and no leader. The unique key on (job_id, due_at) makes a double load harmless.

Say this: A hundred thousand runs are due at 09:00, and writing them all at 09:00 takes one scheduler 20 seconds. So loaders write the next five minutes of runs early, with minutes to spare, and add each one to a Redis set ordered by due time. At each second a dispatcher hands out the due entries without touching the database. If Redis loses the set, the loaders rebuild it from the database.

A worker freezes halfway through a run. Who finishes it, and what stops the first worker?

Worker A takes Ana’s 09:00 run and starts building the list of overdue invoices. At 09:00:12 its process stops for 70 seconds, in a long garbage-collection pause or a stalled virtual machine. It has sent nothing yet. A does not know it has stopped. At 09:01:22 it wakes up and carries on from where it stopped.

From outside, that freeze looks exactly like a crash. No messages come from A, and nobody can tell whether it will ever send another.

Start with the claim from step 2. A worker takes a run only if it is still waiting, and sets its status to running. When it finishes, it sets the status to succeeded. The worker acknowledged the queue message when it took the run, so the queue has nothing left to deliver.

Now replay the morning with a worse fault: at 09:00:12 A’s machine loses power. The row says running. Every other worker sees running and leaves the run alone. At 10:00 no customer has a reminder. Nothing has failed, so nothing alerts. The run will still say running tomorrow, waiting for a worker that no longer exists.

So a claim has to run out. The worker takes the run under a lease: a deadline 30 seconds away, stored on the run row. While it works, it renews the lease every 10 seconds. A sweep finds runs whose lease has run out and puts their IDs back on the ready queue. The claim accepts a run that is waiting, or one whose lease has run out. Queues have the same idea under another name: Amazon SQS calls it a visibility timeout.

Replay the freeze. A takes the run at 09:00:00, with a lease until 09:00:30. At 09:00:10 it renews, to 09:00:40. At 09:00:12 it freezes, and misses the renewals due at 09:00:20 and 09:00:30. The lease runs out at 09:00:40. At 09:00:41 worker B takes the run. B sends one reminder to each customer and records success at 09:00:55. The machine that lost power is handled the same way: B takes over at 09:00:41.

Then A wakes at 09:01:22. Nothing has told A that it lost the run. It carries on, sends every reminder again, and writes succeeded over B’s record. Every customer now has two emails. The lease decided when another worker could take over. Nothing decided whether the old owner could still write.

The fix gives every claim a number. Taking a run raises its attempt number by one, in the same statement that takes it. A took the run as attempt 1. B’s takeover made it attempt 2. Every renewal and every result names the attempt that sends it. It changes the row only if that number still matches. A renewal from A says, in effect: extend run R’s lease, if R is still attempt 1.

A well-built worker renews before it starts anything new. So when A wakes at 09:01:22, its first write is a renewal as attempt 1. The row says attempt 2, so no row matches. A learns it has lost the run, and stops before sending anything. Had it reached its final write instead, “succeeded, as attempt 1” would match nothing too. A number that only goes up, which storage checks on every write, is called a fencing token.

Step through the three designs below: marking the run running, a lease alone, and a lease with an attempt number. Watch A and B in each.

The interactive version of this example is available when JavaScript loads.

Picture A’s finish waiting two seconds for a lock on the row while its lease runs out. Suppose the finish compared the lease with a time read before that wait. The check would pass, and a stale result would land. The attempt number cannot go stale that way. A takeover changes the row. PostgreSQL then checks the condition again against the changed row before it writes (read committed). So the finishing statement checks the attempt number, never the clock.

Say A’s own clock runs 5 seconds slow. At 09:00:40 by the database, A’s clock reads 09:00:35. A lease ending at 09:00:40 still looks valid to A, so A would keep writing after B took over. So every lease deadline comes from one clock, the database’s. A worker asks to renew, and the database stamps and checks the deadline with its own time.

Here are the three statements that decide who runs what: loading ahead, taking a run, and renewing and finishing it.

The interactive version of this example is available when JavaScript loads.

Each statement changes one row under a condition, and none holds a lock while the job runs. The job itself runs outside any transaction, however long it takes.

Three practical questions follow.

The first is how long the lease should be. A lease shorter than a normal pause hands healthy runs to a second worker for no reason. A very long lease makes a real crash slow to recover from. With 30 seconds and a renewal every 10, a dead worker costs about half a minute. In the replay, A stopped at 09:00:12 and B started at 09:00:41, 29 seconds later. One missed renewal does not lose the run, because the lease still has 20 seconds left.

The second is what renewals cost. At 09:00 about 40,000 workers are busy. If every one renewed every 10 seconds, that would be 40,000 ÷ 10 = 4,000 writes a second. Most runs take about 2 seconds, though, and finish before their first renewal. Only runs longer than 10 seconds renew at all, such as an hour-long report, so the real load is far lower.

The third is a worker that is stuck but not frozen. Say A waits on a call to a service that never answers. Its renewal loop still runs and still reaches the database, so the lease never runs out. A renewal proves only that the worker can reach the database, not that the work is moving. So each job has a maximum run time. After it, the run is failed, however healthy its worker looks. Failing it moves the run out of running, and every renewal and result requires running. So the stuck worker’s late writes match nothing. The next claim raises the attempt number as usual, so a timed-out run spends one attempt, not two.

Some designs let the queue hold the lease instead. The worker keeps its message hidden while it works, and the queue shows the message to another worker if the timeout passes. That covers the first half: when another worker may take over. It does nothing about the second. The frozen consumer can still finish its work late, so the attempt number has to live wherever the result is written.

The fence protects the run row. It cannot unsend an email. If A had frozen in the middle of sending, it could send a few more before its next renewal told it to stop. That gap belongs to the work itself, and the next deep dive closes it.

The gap: From outside, a frozen worker looks like a dead one, and a frozen worker can wake up.

Option 1: Mark the run as running

Taking a run sets it to running, and finishing sets it to succeeded.

Works when: Workers never stop halfway, which no machine promises.

Breaks when: A worker that dies leaves the run running forever, and nothing alerts.

Option 2: A lease that runs out

The worker holds a 30-second lease, renewed every 10 seconds, and an expired run can be taken again.

Works when: A second run of the work is harmless, like a report that replaces itself.

Breaks when: A wakes at 09:01:22, sends every reminder again and writes over B’s record.

Option 3: A lease and an attempt number (start here)

Taking a run raises its attempt number, and every renewal and result changes the row only if its number still matches.

Works when: Workers can freeze or die at any moment, and the effects carry the keys from the next deep dive.

Watch for: A worker stuck on a call that never returns keeps renewing, so nobody takes the run.

Fix within it: Give each job a maximum run time, after which the run fails however healthy its worker looks.

In the interview: Open with option 3, and give both halves. The lease decides when another worker may take over. The attempt number decides who may still write. Name option 2 as the answer that looks finished, then show A sending every reminder again. If the interviewer pushes on clocks, say the fence checks the attempt number and never the time.

Say this: A frozen worker cannot tell that it has stopped, so every run is held under a 30-second lease that its worker renews every 10 seconds. Taking a run raises its attempt number, and every renewal and result names that number. When the frozen worker wakes, its writes match no row, so it stops. A maximum run time catches a worker that keeps renewing while stuck.

The reminders went out, then the worker died before recording success. Do customers get two?

Take the same morning with a different fault. Worker B holds Ana’s run as attempt 2 and sends all 120 reminders by 09:00:55. Its next statement would record success. At that instant its machine dies. The lease runs out, and worker C takes the run as attempt 3.

The fence from the last deep dive does not help here. It refuses writes from an owner that lost the run. C owns the run fairly, with the current number. The only question is what C does next.

Many candidates reach for a queue that promises exactly-once delivery. Suppose it keeps that promise, and B’s message reached B once. The repeat did not come from the queue. It came from a lease running out on a worker that had already done the work. No queue can see whether an email left B’s machine.

The next idea is to check before acting. C reads the run first, and skips the work if it already succeeded. Replay the crash. B died before its record, so the run says running, with a lease that has run out. C sees an unfinished run and sends all 120. Every customer now has two reminders.

Move the crash earlier, to after 70 of the 120 emails. The run looks exactly the same: unfinished. C sends all 120 again, so 70 customers get two. Move it earlier still, before any email. Now the check is right: nothing was sent, C sends 120, and nobody gets two. The check reads the record, and the gap sits between the send and the record, where the check cannot see.

Some jobs can close that gap outright. Say a job closes last month’s invoices, and the invoices live in the same database as the runs. The job writes its changes and a row saying “run R is done” in one transaction. Both commit, or neither does. A retry that finds the row stops. A retry that finds no row knows nothing happened, and starts again.

The order matters. Written in a second transaction after the changes, the record can miss a crash between the two, and the changes happen twice. Written before the changes, it can claim work that never happened. Only the same transaction closes the gap. An email cannot join it, and neither can a webhook or a card charge.

So accept that a run can be delivered twice, and make the second delivery harmless where the effect happens. The worker passes the run ID along with the work. Before sending, the email service stores the pair (run ID, customer) under a unique key. If the pair is already there, it refuses to send.

Replay the crash after 70. C asks the email service for all 120, under the same run ID that B used. The service already holds 70 of those pairs, so it refuses them and sends the other 50. Every customer has one reminder. Replay the crash after all 120, and C sends nothing new. A payment works the same way. A provider that accepts an idempotency key gets one built from the run ID and the customer, and returns the first result to a repeat.

The first tab below checks the run before sending. The second keys each email by run ID. Pick where the crash lands, then run each.

The interactive version of this example is available when JavaScript loads.

Keys have limits of their own.

The first is how long the target remembers. Say the email service keeps keys for 24 hours. Ana’s run fails for good on Tuesday, and on Friday someone retries it by hand, under the same run ID. The keys have expired, so every customer the first attempts reached gets a second email. So a key has to live longer than the longest retry or replay.

The second is a target that cannot store keys at all. Then the job either accepts a rare duplicate, or checks the target’s own records before acting, such as the list of emails already sent for this run. Pick one, and say which in the interview.

The third is the same gap one level down. The email service stores a key, then hands the message to its provider, and it can crash between the two. If it refused every stored key, that email would be lost for good. So it records each pair as pending, then as sent once the provider accepts it. A retry skips a sent pair. A pending pair is unknown, so the service asks its provider, or sends again and accepts a rare duplicate. Each layer that makes an effect has to close this gap for itself.

A run Ana starts by hand is not a retry. She fixed a typo and wants every reminder sent again. That is new work, so it gets a new run ID, and the email service sends again.

So no honest scheduler promises that each job runs exactly once. It can promise that each run is delivered at least once and recorded once. The work happens once in effect only where the effect remembers the run ID. Kubernetes says the same of its CronJobs: in some circumstances two jobs may be created, or none, so the jobs should be idempotent (CronJob). The idempotency article follows the same key through an API.

The gap: Doing the work and recording it are two steps, and a worker can die between them.

Option 1: Exactly once, from the queue

Use a queue that promises to deliver each run to one worker once.

Works when: Workers never die between the work and the record, which no machine promises.

Breaks when: The queue delivers once, and the retry after B’s crash still sends every reminder again.

Option 2: Check the run, then send

Before the work, read the run, and skip it if it already succeeded.

Works when: The crash came before any work began, or after the record was written.

Breaks when: A crash after 70 of 120 emails leaves the run unfinished, so the retry sends all 120 and 70 customers get two.

Option 3: The work and the record in one transaction

A job that changes our own tables commits its changes and a “run R done” row together.

Works when: The whole effect lives in the run’s own database, such as closing last month’s invoices.

Breaks when: An email, a webhook or a card charge cannot join the transaction.

Option 4: At least once, with the run ID as the key (start here)

The email service stores each (run ID, customer) pair under a unique key, and refuses a pair it has seen.

Works when: Any effect whose target can remember a key: after a crash at 70, the retry sends the other 50.

Watch for: A target that keeps keys for a day sends again when a run is retried by hand three days later.

Fix within it: Keep keys longer than the longest retry, and where the target cannot store keys, check its records first or accept a rare duplicate.

In the interview: Open with option 4, and say the rule first: delivery is at least once, so the effect makes a repeat harmless. Give option 3 for a job that only changes our own tables. Name option 1 in one sentence as the promise no scheduler can keep, and option 2 as the check that cannot see the gap.

Say this: A worker can do the work and die before recording it, so any run may be delivered twice. I pass the run ID to wherever the effect happens. The email service stores each run ID and customer pair under a unique key and refuses a repeat. When the effect is in our own database, the change and a done row commit in one transaction.

The email service goes down and 3,000 runs fail at once. What do their retries do to it?

At 09:00:00 the email service stops answering. Three thousand reminder runs from different teams fail in the same second, Ana’s among them. Each run makes one batch call to the email service, carrying its customers’ emails and their keys. At 09:01:00 the service is back, and it can answer 300 calls a second. Each run gets eight attempts before it is marked failed.

On a quiet day a failed run fails alone, and any wait before its retry works. Here 3,000 runs failed together, and what matters is when their retries arrive.

The simplest policy waits a fixed 10 seconds after each failure. Replay the outage. All 3,000 runs failed at second 0, so all 3,000 retry at 10, then at 20, 30, 40 and 50. The first try and those five retries are 6 × 3,000 = 18,000 calls, all against a service that is down. At 60 the service is back, and the seventh wave arrives: 3,000 calls in one second. It answers 300 and refuses 2,700. At 70 those 2,700 make their eighth and last attempt, and 300 more get through.

Count the result. 600 runs succeeded. The other 2,400 runs used all eight attempts and were marked failed, ten seconds after the service came back. They made 18,000 + 3,000 + 2,700 = 23,700 calls. The outage was over. The retries failed because they arrived all at once.

The next idea doubles the wait: 5 seconds, then 10, 20 and 40, up to a cap of 2 minutes. Replay it. The first four attempts come at 0, 5, 15 and 35 seconds, all while the service is down. That is four waves, 12,000 calls, instead of six. The fifth attempt comes at 75 seconds, after the service is back. The waits then reach 80 seconds and the 2-minute cap, so the last three attempts come at 155, 275 and 395.

Each wave after the outage still gets 300 through. So 1,200 runs succeed instead of 600. The other 1,800 fail. The last success comes at 395 seconds. The total falls a little, to 22,200 calls. The waves are further apart, but each is still 3,000, 2,700, 2,400 and then 2,100 calls in a single second. Every run waits exactly as long as every other, so runs that failed together stay together.

So spread each wait. Keep the doubling, but stretch or shrink each wait by a random amount, anywhere between half and one and a half times its length. A 40-second wait becomes anything from 20 to 60 seconds. The average wait stays the same. What changes is that two runs that failed together no longer come back together. This random spread is called jitter.

Replay the outage. The first wave is still 3,000 calls, at second 0. After it, the retries smear into a stream. Once the service is back, the busiest second sees 92 calls, well under its 300, and every call after it returns is answered. All 3,000 runs succeed by 179 seconds, with 15,409 calls in total.

The wait is not a worker sleeping. The failed attempt records a next attempt time on the run row, and the run goes back to waiting. The loaders also look for runs whose next attempt is due soon, and add them to the due-soon set like any other run. A retry holds no worker while it waits. The claim takes a waiting retry only once its next attempt time has come, so a stale copy of an old message cannot start it early.

The three tabs below are a fixed 10 seconds, doubling, and doubling with jitter. Pick one, then press Break it.

The interactive version of this example is available when JavaScript loads.

The experiment uses a seeded random generator, so it shows the same numbers on every page load. A real fleet draws fresh random numbers, and the waves smear the same way.

Jitter spreads the retries. Three limits keep them from running forever or multiplying.

The first is a service that stays down. Doubling alone would keep a run retrying for hours. So each run has a cap on attempts, eight here, and an overall deadline. Every claim raises the attempt number, whether it is a retry or a takeover after a frozen worker. So a takeover spends one of the eight attempts too, and a run that keeps killing its workers stops eventually. When either limit runs out, the run is marked failed, and the on-call alert fires with the job, the run and the last error. Someone fixes the cause and retries the run by hand, under the same run ID.

The second is an error that will never succeed. A timeout or a 503 may pass, so retry it. Retrying a timeout is safe only because of the keys from the last deep dive. The call that timed out may have sent some emails, and the keys stop the retry sending them twice. The batch answer can also refuse one address as not a valid email, with a 400 for that address. It will be refused every time, so that one email is marked failed and never retried. The run still succeeds, and its result lists the failed address so the team can fix it. A 429 with a Retry-After header says when to come back, so wait at least that long.

The third is retries in two layers. Say the scheduler allows 5 attempts, and the email client inside each attempt tries 5 times. One run can then make 5 × 5 = 25 calls, and the storm is five times larger than it looks. So one layer owns retries, and the other makes a single try.

AWS’s SDKs combine these rules: exponential backoff with jitter, a cap on attempts, and a retry quota, so a failing service cannot draw unlimited retries (retry behavior). A circuit breaker goes one step further. After enough failures from one service, it stops calls to that service for a while. With 40,000 workers, a breaker in each process would still let thousands of calls through while each one learns. So its state is kept once per target service. The loader writes each entry with the service its task calls, such as email:R, so a dispatcher can check that service’s breaker without reading the database.

Replay the outage with a breaker. In the jitter experiment, 12,409 calls hit the email service while it was down. Say the breaker opens once the first wave of 3,000 fails. Dispatchers now leave every email run in its set, rescored to the breaker’s next probe, 30 seconds away. A held run is never claimed, so it spends no attempt. At second 30 one probe call fails, so the breaker stays open. At second 60 the service is back, and the next probe succeeds. That test state is called half-open. The breaker closes, and the held runs are released with jitter across the next minute, not all at once. The calls against the dead service fall to the first wave and one probe.

The gap: Runs that failed together retry together, unless something pulls them apart.

Option 1: Retry every 10 seconds

Wait a fixed 10 seconds after each failure, then try again.

Works when: Failures are rare and unrelated, so two retries seldom land in the same second.

Breaks when: The runs retry in waves of up to 3,000 calls against 300 a second, so 2,400 runs use all eight attempts.

Option 2: Double the wait each time

Wait 5 seconds, then 10, 20 and 40, up to a cap of 2 minutes.

Works when: One job retries against an outage of unknown length.

Breaks when: Every run still waits as long as every other, so the retries still arrive in waves and 1,800 runs fail.

Option 3: Double the wait, spread it, and cap the total (start here)

Spread each doubled wait between half and one and a half times its length, and store it as the run’s next attempt time.

Works when: Any retry against a shared service: after it returns, the busiest second sees 92 calls, and all 3,000 runs succeed.

Watch for: Retries that multiply across layers, and retries of an error that can never succeed.

Fix within it: Let one layer own retries, cap attempts and total time, and retry only timeouts, 503s, and a 429 after its Retry-After.

In the interview: Open with option 3 and its numbers: after the outage, the busiest second sees 92 calls and all 3,000 runs get through. Add the caps and the rule about which errors to retry when the interviewer asks what happens if the service stays down. Bring up retries multiplying across layers if they ask about the client library.

Say this: Runs that failed together retry together, so a fixed wait sends 3,000 calls at once to a service that answers 300 a second. I double the wait and spread each one with jitter, so the retries arrive as a stream. Each run has a cap on attempts and an overall deadline, and only errors that can pass, such as timeouts and 503s, are retried. The wait is a due time on the run row, so no worker sleeps holding a slot.

The scheduler was down from 08:58 to 09:31. What happens to the runs it missed?

A deploy goes wrong at 08:58. Every loader and dispatcher stops for 33 minutes, until 09:31. The loaders had already written the runs due up to about 09:03, so the 09:00 runs exist as rows, waiting. Nothing hands them out. From 09:03 on, nothing is even written. Ana’s exchange-rate job, due every ten minutes, missed its runs at 09:00, 09:10, 09:20 and 09:30. Her invoice reminders, due at 09:00, are one of the waiting rows.

Across the platform the gap is large. 20 million runs a day is 20,000,000 ÷ 24, about 833,000 an hour. At that average rate, about 458,000 runs came due in these 33 minutes and never started. The true number is higher, because the 09:00 wall falls inside them.

At 09:31 the platform finds two kinds of missed run. Some are rows whose due time passed while they waited. Others are due times the loaders never reached, with no row at all. What should each of them become?

The first answer is to start again from now. Anything due before 09:31 is thrown away, and each job’s next run is computed from 09:31. So the exchange-rate job next runs at 09:40. That is quick, and quiet. The waiting rows are dropped, and the later due times never get a row. Nothing records that they were due, so nobody is told. Ana’s 09:00 reminders vanish the same way, and 120 customers are never reminded. Her history shows a gap nobody can explain. The platform promised that no run is skipped without a record, and this answer skips nearly half a million.

The opposite answer runs everything that was missed. The waiting rows go straight out. The loader walks each job’s next run time forward, creating a run for every due time that passed. For the reminders that is right: one run, 31 minutes late, and the customers still get their email. For the exchange-rate job it is waste. Four refreshes run back to back at 09:31, and the first three are overwritten within seconds. A job due every minute, after a day of downtime, would create 1,440 runs at once, since a day has 24 × 60 minutes.

Across the platform it is worse. All the missed runs land at 09:31, on top of the runs actually due at 09:31. The outage has built a wall of its own, and the runs due now are stuck behind it.

The two jobs want different things. The exchange-rate job cares only about the newest rate, so one refresh at 09:31 is enough. A report per hour needs every hour, so it wants all its missed runs. So each job carries a missed-run policy, and it covers the waiting rows and the unwritten due times alike. There are three answers. Skip them, when the next run does the same work anyway. Run only the latest, when the job refreshes current state, like an exchange-rate table. Run them all, when each due time has its own work, like a report per hour.

The exchange-rate job picks the latest. At 09:31 only its 09:30 run happens. 09:00, 09:10 and 09:20 each end as a row marked skipped, with the reason. The reminders pick run them all, with a one-hour window, so Tuesday’s 09:00 reminders go out at 09:31.

A policy alone still lets a long outage flood the platform. So every job also has a catch-up window. A missed run older than the window is skipped, whatever the policy says. Now give the exchange-rate job the run-them-all policy and a 15-minute window, and replay 09:31. 09:00 is 31 minutes old and 09:10 is 21, so both are recorded as skipped. 09:20, 11 minutes old, and 09:30, 1 minute old, both run.

The chips below set the policy and the window. Choose, then play the outage.

The interactive version of this example is available when JavaScript loads.

The policy runs before anything is handed out. Dispatchers write a heartbeat every few seconds, so at 09:31 they know nothing was handed out between 08:58 and 09:31. Every run eligible inside that gap, written or not, is checked against its job’s policy first. The exchange-rate job’s 09:00 entry is marked skipped and removed from the set. The claim would refuse it anyway, because a skipped run is not waiting.

Catching up creates one more problem. Even with windows, the returning loaders and dispatchers find hundreds of thousands of runs at once. Written as fast as possible, they compete with the runs due at 09:31 for the database and the workers. So missed runs are loaded at a limited rate, with room kept for the runs due now. Catch-up also gets at most a set share of the workers, the same limit backfills get in the next deep dive. Every skipped run keeps its row, so the history has no gaps.

Real schedulers make the same choices under other names. A Kubernetes CronJob can set a starting deadline, and skips a run that could not start within it. It also refuses to start a job that missed more than 100 schedules, and logs an error instead. Temporal gives each schedule a catch-up window, one year by default (schedules).

A related question sounds the same and is not. The exchange-rate job normally takes 20 seconds. One day the rate provider is slow, and the 09:00 run is still going at 09:10. That is overlap, not a missed run, and it needs its own policy on the job. The new run can start alongside the old one, be skipped, wait its turn, or replace the old one. Kubernetes calls three of these Allow, Forbid and Replace (CronJob).

The gap: While the scheduler was down, due times passed and nothing started them.

Option 1: Start again from now

On restart, compute each job’s next run from the current time.

Works when: A missed run matters to nobody and needs no record.

Breaks when: Every missed run vanishes without a record, Ana’s 09:00 reminders among them, so nobody is told.

Option 2: Run everything that was missed

On restart, create a run for every due time that passed.

Works when: Every due time has its own work and the outage was short, like an hourly report after ten minutes.

Breaks when: Four refreshes run back to back when only the last matters, and every missed run lands on 09:31 at once.

Option 3: A missed-run policy per job, with a window (start here)

Each job says skip, run the latest or run them all, and runs older than its catch-up window are skipped with a recorded reason.

Works when: Any recurring job: a refresh runs the latest, a report runs them all, and the window stops a long outage becoming a flood.

Watch for: Catching up competes with the runs due at 09:31.

Fix within it: Load missed runs at a limited rate, with room and a share of the workers kept for the runs due now.

In the interview: Open with option 3, and name its parts together: three policies, a catch-up window, and skipped as a recorded status. Options 1 and 2 are worth a sentence each, because one loses runs without a trace and the other floods. If the interviewer asks about a run still going when the next is due, say that is overlap, a separate policy.

Say this: After an outage, each job decides what its missed runs mean: skip them, run only the latest, or run them all. A catch-up window skips anything older, so a long outage cannot become a flood. Every skipped run gets a row saying why. Missed runs are loaded at a limited rate, so the runs due now still start on time.

One team queues a million runs at 09:00. Does everyone else wait?

At 09:00:00 a large customer starts a backfill: a year of hourly reports across its accounts, a million runs, all due now. They land on the ready queue a moment before the dispatchers hand out the 09:00 wall. Ana’s one reminder run arrives right behind them.

On a quiet day one shared queue stays short, so the order of the line hardly matters. Today one team’s work is nearly the whole line.

The simplest design serves one queue, first come first served. Replay 09:00. The platform has about 40,000 workers ready for the wall, and each report takes 2 seconds. A million runs is 2,000,000 worker-seconds, and 2,000,000 ÷ 40,000 is 50 seconds. Every run of the 09:00 wall waits behind the backfill, Ana’s included. They start from about 09:00:50, ten times past the promise. Nothing broke. A big team’s backlog decided how long a small team waited.

Shrink the scene to see it whole. Team A queues eight one-second jobs a moment before teams B and C queue two each, and one worker serves them. First come first served starts B at 8 seconds and C at 10, although each asked for two small jobs.

The next idea is a quota: each team may create so many jobs, and so many runs a day. The API already refuses a schedule that fires too often. But the backfill team is inside its quota. A quota says how much a team may run. It says nothing about the order, so the team can still put a million runs in front of everyone at once.

So give each team its own lane. The lanes live in Redis: the due-soon set is split into one set per team. Dispatchers keep a list of the teams with due runs, and take one run from each in turn. That is one from A, one from B, one from C, then A again. A lane with nothing waiting is passed over. Dispatchers keep only a few seconds of work on the ready queue, so a backlog waits in its own lane, not in front of everyone. With thousands of teams, the list holds only the teams that have something due. Replay the small scene. Taking turns starts B at 1 second and C at 2. A still finishes all eight, at 12 seconds instead of 8. The total work is the same 12 seconds, and only who waits has changed.

Replay 09:00. The backfill’s lane holds a million runs, and Ana’s lane holds one. Her run waits for one turn of each lane that has work, not for the million. The 5-second promise now holds for each team on its own. A team that queues more than its share waits on its own backlog, and only its own runs start late. A paying tier can get weighted turns, such as two runs per round instead of one.

The first tab below is one queue, first come first served. The second takes turns by team. Start the worker in each.

The interactive version of this example is available when JavaScript loads.

Say team D’s jobs each take an hour, and every other team’s take a second. D gets the same number of turns as everyone else. Each of its turns holds a worker for an hour, so D slowly fills the workers anyway. Turns count jobs, and jobs are not all the same size.

So each team also has a cap on runs going at once, the running limit on its team record. When D has that many running, its lane is passed over until one finishes. Backfills and catch-up after an outage get at most a set share of the workers, so runs due now still start on time.

A scheduler can also count worker time instead of turns. Say D has used 10 worker-hours today and B has used 10 seconds. B goes next, and keeps going next until its use catches up. That slows a team of long jobs more fairly than turns do. It does not replace the cap. If time is charged only when a run finishes, D can grab many idle workers before any charge lands.

Priorities inside one team are a separate choice. Say Ana’s team marks its reminders urgent and its reports normal. If urgent always goes first, a steady trickle of urgent runs can hold the reports back all day. So the urgent lane gets a cap of its own, and normal runs still get a share.

The gap: When every team stands in one line, a team’s wait depends on how much others queued ahead of it.

Option 1: One queue, first come first served

All runs go on one queue, oldest first.

Works when: Teams send small, similar amounts of work, so the line stays short.

Breaks when: Ana’s one run waits behind a million, about 50 seconds even with 40,000 workers.

Option 2: A quota on jobs and runs

Each team may create so many jobs and so many runs a day.

Works when: The worry is runaway total use, such as a job that fires every second by accident.

Breaks when: A team inside its quota can still queue a million runs at once, because a quota limits how much, not the order.

Option 3: A lane per team, served in turn (start here)

Give each team its own set of due runs, and hand out one run from each in turn, weighted by plan if needed.

Works when: Any platform shared by many teams: a small team’s run waits one turn of each busy lane, however much a big team queued.

Watch for: Turns count jobs, so a team of hour-long jobs fills the workers anyway.

Fix within it: Cap each team’s runs going at once, and give backfills and catch-up at most a set share of the workers.

In the interview: Open with option 3, with its cap on running work. Say why option 2 does not help: a quota limits how much a team runs, not the order. Add weights by plan, or a set share for backfills, when the interviewer asks about paying tiers or catch-up.

Say this: With one queue, a team with a million runs decides when everyone else starts. I give each team its own lane of due runs, and dispatchers take from the lanes in turn. Turns count jobs rather than hours, so each team also has a cap on runs going at once. Backfills and catch-up get at most a set share of the workers.

That completes the six deep dives. The two sections below are shorter follow-ups that a staff round often adds.

If they push: Ana pauses her job at 08:57, after its 09:00 run is loaded. What stops that run?

At 08:57 Ana pauses her reminders job, because the email template has a mistake. The 09:00 run was loaded at 08:55. It is a row, marked waiting, and its ID sits in the due-soon set.

The pause is one transaction. It marks the job paused, and marks every run of that job that has not started as cancelled. Nothing removes the ID from the set, so at 09:00 a dispatcher hands it out anyway. The claim takes only a run that is waiting, or one whose lease has run out, and a cancelled run is neither. The worker finds a cancelled row, changes nothing, and drops the message. The stale entry costs one wasted message and nothing else.

An edit works the same way. Say Ana moves the job from 09:00 to 10:00. The edit cancels the runs not yet started and computes the new next run time. The loaders load 10:00 when it enters the horizon. A delete cancels them too, and keeps the history for 30 days. A run already going when Ana pauses keeps going to the end, as the API promised. Only a run that has not started can be stopped this way.

If they push: Ana’s job says 09:00 in Lisbon. What happens when the clocks change?

Ana’s reminders run at 09:00 Lisbon time. In winter that is 09:00 UTC. From the last Sunday in March, Portugal is on summer time, and 09:00 in Lisbon is 08:00 UTC. Say the scheduler stored the first run as 09:00 UTC and added 24 hours each day. In summer the reminders would go out at 10:00 local time. A calendar rule is not a fixed interval.

So the scheduler stores the rule and the name of the time zone, never an offset. It computes each next run in that zone, then converts it to UTC. Every due_at is stored in UTC.

Two days a year the local clock does something odd. On the last Sunday in March, Lisbon’s clocks jump from 01:00 to 02:00. A job set for 01:30 has no 01:30 that day, so it runs at 02:00 or skips the day. On the last Sunday in October, the clocks fall back from 02:00 to 01:00, and 01:30 happens twice. The usual choice is to run once, at the first, unless the job asks for both.

Either choice can be right, so the job should say which. If a job runs at both of those 01:30s, they are two different instants in UTC. So they are two runs, with two IDs. That is why the API returns the next three run times when a job is created: Ana can spot a strange one before it runs.

The rules themselves change too. Governments sometimes move their clocks with only weeks of notice, and the time zone database ships an update. Every job in an affected zone then recomputes its stored next run time. Runs already loaded under the old rule are cancelled and loaded again, the way an edit works.

Walk one run through the final design

At 08:55 a loader finds Ana’s job, due at 09:00 Lisbon time, which is 08:00 UTC on 14 April. It creates run R and adds R to her team’s due-soon set, scored at 08:00:00 UTC. The platform counts the 09:00 wall in the set and adds workers.

At 09:00:00 a dispatcher, taking turns across the team lanes, takes R from her team’s set and puts it on the ready queue. Worker A takes R as attempt 1 with a 30-second lease, and freezes. At 09:00:41 worker B takes R as attempt 2. B sends the 120 reminders with R’s ID as the key, and records success as attempt 2. When A wakes, its renewal matches no row, so A stops.

Had the email service been down, B would have recorded a failure and a next attempt time with jitter. R would have come back through the same set. After eight attempts, R would be marked failed. Then the on-call alert would fire.

The interactive version of this example is available when JavaScript loads.

RequirementWhere it is metThe trade-off
FR1 create and manage jobsJob API; jobs in PostgreSQL, with next run times in UTCEach job keeps its time zone, so a rule change recomputes its next runs
FR2 run each job on timeLoaders five minutes ahead, the due-soon set, dispatchers, workers with leasesRedis holds a copy of the next five minutes, and the loaders refill it after a loss
FR3 retry, then give upA retry is a run due again, with backoff and jitter; failed runs page a personA run can be delivered twice, so effects need the run ID
FR4 show every runRun and attempt rows, one table per day, read by the Job APIThirty days are kept, and older days are dropped whole

How does the answer change for distributed cron, delayed jobs or Airflow?

Interview variantWhat carries overWhat changes
Design a distributed cronEverything on this pageEvery job repeats, so time zones and missed runs take more of the round
Design a delayed job queue (send this in 3 days)Runs, leases, attempts and retriesMost jobs run once, so there is no cron rule, and the due-soon set does most of the work
Design Airflow, a workflow schedulerRuns, attempts, retries and historyJobs wait for other jobs, so the scheduler tracks a graph and starts a task only when the tasks before it succeed
Design a reminder or notification schedulerDue times, the 09:00 wall, retriesThe effect is a message to a person, so preferences and quiet hours join the design
Design a job scheduler, as a low-level designThe job, run and attempt entitiesClasses for jobs, triggers and a thread pool inside one program, not machines and failures
Task Scheduler, as a coding questionNothing on this pageA counting puzzle about cooldowns between tasks, not a system

What should an answer reach at each level?

LevelWhat the answer shows
Intern or mid-levelStores jobs with a next run time and an index, polls for due jobs, queues them, and has workers record status. Retries a failure a limited number of times.
SeniorSeparates job, run and attempt. Uses a lease with an attempt number, so a frozen worker cannot write. Says that delivery is at least once, and keys effects by run ID.
StaffLoads the next few minutes ahead and sizes the 09:00 wall. Runs many loaders without a leader. Adds jitter and caps to retries, plus missed-run and overlap policies, time zones, and fairness between teams.
PrincipalSets the promises with the teams that use it: how late is late, what a missed run means, which jobs may repeat. Explains how the design changes for workflows, delayed jobs and uploaded code.

Test yourself with the quiz, then pick another problem from the System Design interview breakdowns.

By GOAT Engineer. Back to all breakdowns. Privacy Policy · Contact.