InterviewDryRun
Lesson 19 · 23 min video · free

Design a Distributed Job Scheduler

Run millions of scheduled and delayed jobs, each one at the right time, and never lose one even when machines die. This lesson designs that scheduler: a durable job store, time-bucketed due queues, a dispatcher that leases work to workers, heartbeats and lease expiry for crash recovery, at-least-once execution with idempotent jobs, retries with backoff, and fairness so one busy tenant cannot starve the rest.

What you will learn

  • Separate the job definition (what and when) from each run (one attempt at one time).
  • Index due work by time bucket so finding what to run now is a cheap range read.
  • Lease work to workers with an expiry; a crashed worker's lease runs out and the job is retried.
  • Exactly-once execution is not possible across failures; promise at-least-once and make jobs idempotent.
  • Retry with exponential backoff and jitter, and move poison jobs to a dead-letter list.
  • Per-tenant queues and quotas keep one noisy customer from delaying everyone else.

In this lesson

  1. The question
  2. Step 1: Clarify the requirements
  3. Step 2: Back-of-the-envelope estimates
  4. Step 3: The API
  5. Step 4: The data model
  6. Step 5: The high-level design
  7. Step 6: Finding due work quickly
  8. Step 7: Leasing work to workers
  9. Step 8: At-least-once and idempotency
  10. Step 9: Retries, backoff and dead letters
  11. Step 10: Recurring jobs
  12. Step 11: Fairness between tenants
  13. Step 12: One job, end to end
  14. Step 13: Scaling and failures
  15. Step 14: The follow-up questions
  16. Recap
Practice this question with Max

The question

Welcome to lesson nineteen of the system design course. Today's question is: design a distributed job scheduler. The interviewer says: build a system that runs millions of scheduled and delayed jobs, with at-least-once execution.

Every serious product has one of these hiding inside it. Send this reminder email in three days. Charge this subscription on the first of the month. Retry this failed webhook in five minutes. Rebuild the search index every night at two. Expire this trial at midnight. Each is a job: some work, and a time when it should run.

On one machine this is easy. A cron table, or a loop that sleeps until the next job. The interview is about what happens when there are millions of jobs, many workers, and machines that crash in the middle of running something. Which job runs when a machine dies? Who notices? Does it run twice? Does it run at all?

Those three questions, does it run, does it run on time, and does it run only once, are the heart of this design. You will see that the honest answer to the last one is: not quite, and the way you handle that honesty is what separates a good answer from a great one.

As always, we will go step by step: requirements, estimates, the API, the data model, finding due work, handing it to workers, surviving crashes, retries, recurring schedules, fairness between customers, and then the follow-up questions the interviewer is likely to ask. Let us start.

Step 1: Clarify the requirements

Functional requirements
  1. 01
    Submit a jobrun once at a time, after a delay, or on a cron schedule
  2. 02
    Cancel or updatebefore it runs
  3. 03
    Run ithand the payload to the right worker at the right time
  4. 04
    Retry on failurewith backoff, up to a limit
  5. 05
    Historyevery attempt, its result and duration

First, what must it do. Clients submit jobs. A job can run once, at a given time or after a delay, or it can recur on a schedule, like every hour or every Monday at nine. The client can look up a job, cancel it, and see its run history.

The payload is opaque to us. It might be a small blob of data plus the name of a handler, like send reminder email, with a user id. Our system does not know what sending an email means. It only promises to deliver that payload to a worker who can run it, at the right time.

Retries are a requirement, not a nice extra. Jobs call other services, and those services fail. The client should be able to say: retry up to five times, with backoff. And they need a history, so when a customer asks why their report did not arrive, an engineer can see every attempt and every error.

Non-functional requirements
  1. 01
    Durablean accepted job is never lost
  2. 02
    On timestarts within a few seconds of its due time
  3. 03
    At-least-oncea job may run twice, never zero times
  4. 04
    Scalablemillions of jobs, tens of thousands due per second at peaks
  5. 05
    Fairone tenant cannot starve the others
  6. 06
    Observablelag, failures and queue depth are visible

Now the non-functional side. Durability first: once we accept a job, we never lose it. Timeliness second: a job should start within a few seconds of its due time. The interviewer may push on how many seconds; a reasonable target is under five seconds at the ninety-ninth percentile.

Third, the execution guarantee. The prompt says at-least-once. Say clearly that this is a deliberate choice: we promise every job runs, and in rare failure cases a job may run twice. Exactly-once is impossible to guarantee when a worker can crash after doing the work but before telling us it finished. We will come back to that.

Finally, scale and fairness. Many teams, or many customers, share this scheduler. At midnight on the first of the month, millions of billing jobs are due at once. One tenant scheduling a million jobs for the same second must not delay another tenant's single urgent job. Write these down; we will design for each.

Step 2: Back-of-the-envelope estimates

Sizing it
Jobs per day100 millionabout 1,200 / s on average
Peak due50,000 / smidnight and top of the hour
Pending jobsabout 1 billionsome scheduled months ahead
Job recordabout 1 KBpayload, schedule, retry policy
Pending storageabout 1 TBplus replicas
Run historyabout 30 TB / yearkeep 30 to 90 days hot

Let us size it. Say one hundred million jobs are scheduled per day. That averages about twelve hundred per second. But scheduled work is very spiky: people pick round times. Midnight, the top of the hour, nine in the morning. So plan for peaks of fifty thousand jobs due in the same second.

How many jobs are waiting at any moment? Many are scheduled days or months ahead, like a renewal in a year. A billion pending jobs is a fair guess. At about a kilobyte each, including payload and retry policy, that is around a terabyte. Large, but a sharded database handles it comfortably.

Run history grows faster. Every attempt writes a record: start time, end time, worker, result, error. One hundred million runs a day at about a kilobyte is a hundred gigabytes a day, roughly thirty terabytes a year. That belongs in cheaper storage, with only the last month or so kept hot.

What does this tell us? Storage is fine. The hard numbers are the peak due rate and the timeliness target. Fifty thousand jobs becoming due in one second, each needing to be found, leased to a worker and started within a few seconds. That is where we spend our design effort.

One more number worth saying out loud: workers. If an average job takes two seconds, fifty thousand jobs per second needs about a hundred thousand concurrent executions at peak. Those are the client teams' workers, not ours, but our dispatcher must feed them that fast.

Step 3: The API

API
POST /v1/jobs
  { handler: "send_reminder", payload: {...},
    run_at: "2026-11-02T09:00:00Z" | delay_s: 300 | cron: "0 9 * * MON",
    retry: { max: 5, backoff: "exp", base_s: 10 },
    timeout_s: 60, idempotency_key: "..." }
→ { job_id }

GET    /v1/jobs/{id}            → job + next run
DELETE /v1/jobs/{id}            → cancel
GET    /v1/jobs/{id}/runs       → attempt history

The API is small. Create a job with a handler name, a payload, and either a run-at time, a delay, or a cron expression, plus a retry policy. Clients pass an idempotency key, so if their create request times out and they retry, they do not get two jobs.

Notice the timeout. Every job declares how long one attempt may take. That number matters more than it looks: it is how we decide a worker has died or hung, and it sets the length of the lease we give that worker. A job with no timeout is a job we can never safely retry.

On the worker side there are two styles. Push, where the scheduler calls the worker's endpoint. Or pull, where workers ask: give me up to ten jobs for handler send reminder. I prefer pull for this design. Workers take only what they can handle, so a slow worker fleet naturally slows its intake instead of being flooded, and we do not need to know the network address of every worker.

Worker API (pull)
POST /v1/lease      { handler, max: 10 }
  → [ { run_id, job_id, payload, lease_until } ]
POST /v1/heartbeat  { run_id }  → { lease_until }
POST /v1/complete   { run_id, ok: true | false, error }

A pulling worker uses three calls: lease, which returns jobs and a lease expiry; heartbeat, which extends the lease for a long job; and complete, with success or failure and an error message. These three calls are the whole contract between the scheduler and the code that does the work.

Step 4: The data model

Jobs and runs
TableKeyHolds
jobsjob_idtenant, handler, payload, schedule, retry policy, timeout, status
runsrun_idjob_id, due_at, attempt, state, worker, lease_until, error
due indextime bucket, shardrun_ids due in that minute
history (cold)job_id, run_idfinished runs, results, durations

The key modelling idea: separate the job from its runs. The job is the definition: what to run, the schedule, the retry policy. A run is one attempt at one time. A one-off job has one run, or a few if it retries. A cron job has a new run every hour, forever.

Run states
SCHEDULED ──due──▶ QUEUED ──lease──▶ LEASED ──ok──▶ SUCCEEDED
                     ▲                  │
                     └── lease expired ─┤
                                        └─fail─▶ FAILED
                                                  │ retries left
                                                  ▼
                                        new run: SCHEDULED at now + backoff

A run moves through a small state machine. Scheduled, then queued when it is due, then leased when a worker picks it up, then succeeded, or failed. A failed run with retries left creates a new scheduled run for later. A run whose lease expires goes back to queued. Draw that state machine; interviewers like seeing it.

Jobs and runs
TableKeyHolds
jobsjob_idtenant, handler, payload, schedule, retry policy, timeout, status
runsrun_idjob_id, due_at, attempt, state, worker, lease_until, error
due indextime bucket, shardrun_ids due in that minute
history (cold)job_id, run_idfinished runs, results, durations

Why a separate due index? Because the one question we ask constantly is: what is due now? Scanning a billion rows for due at less than now is far too slow. So we keep an index keyed by time bucket, say one row per minute per shard, listing the runs due in that minute. Finding due work becomes reading one small bucket.

Which database? The job and run tables need durable writes and conditional updates, like: set state to leased only if the state is still queued. That compare-and-set is what stops two dispatchers handing out the same run. Any sharded relational database, or a distributed key-value store with conditional writes, works. Shard by job id, so each job's runs live together.

Step 5: The high-level design

The scheduler
writepoll dueenqueueleasecompleteexpired leasesCLIENTClientsSERVICEJob APIcreate, cancelSTOREJob storejobs + runs, shardedSTOREDue indextime bucketsSERVICEDispatchersone per shardQUEUEReady queuesper handler, per tenantWORKERWorkersclient codeSERVICELease sweeper

Here is the overall shape. Clients call the job API, which writes the job and its first run to the job store, and adds the run to the due index.

Dispatchers own shards of the due index. Every second, each dispatcher reads the buckets that have come due for its shards, and moves those runs into ready queues. Ready queues are split by handler and by tenant, which matters for fairness later.

Workers lease runs from the ready queues, do the work, heartbeat if it is long, and report completion, which updates the run in the job store.

And a lease sweeper watches for leases that expired without completion: the worker crashed, hung, or lost its network. Those runs go back to queued and are leased again. That loop, lease, expire, retry, is what turns crashing machines into a slightly late job instead of a lost one.

Say why the parts are separate. The API scales with clients creating jobs. Dispatchers scale with the due rate. Workers scale with the actual work and belong to the client teams. The store is the single source of truth, and every other component can crash and restart without losing anything, because the truth is in the store.

Step 6: Finding due work quickly

Due index buckets
key  = (due_minute, shard)
     = (2026-11-02T09:00, 42)
value = [ (due_at, run_id), ... ]  sorted by due_at

dispatcher for shard 42, every second:
  read bucket(now_minute, 42) where due_at <= now
  for each run: CAS state SCHEDULED → QUEUED
  push run_id to ready queue

Let us go deeper on the due index, because timeliness lives here. Each run is placed in a bucket by its due time, rounded down to the minute, and by a shard number, hashed from the job id. So a bucket key looks like: two thousand twenty-six, November second, nine o'clock, shard forty-two.

Why the shard number? Without it, everything due at nine o'clock would sit in one bucket: one hot key, one machine. Spreading each minute across, say, a thousand shards splits that midnight spike across a thousand dispatchers, each handling fifty jobs per second at peak instead of fifty thousand.

Why minute buckets and not second buckets? It is a trade-off. Smaller buckets mean more keys and more reads, even when they are empty. Larger buckets mean each read returns more runs, most not yet due. A minute is a good default. Inside the bucket, runs are sorted by due time, so the dispatcher reads only the ones due by now.

Far-future jobs need a little care. A renewal due in a year should not sit in the hot index for a year. Keep the near-future index, say the next hour, in fast storage, and let a background loader move runs from the main store into the hot index as their hour approaches. This is the timing-wheel idea, used in operating system timers, applied at the scale of a database.

And the dispatcher always looks slightly backwards as well as at now. If a dispatcher was down for thirty seconds, it reads the overdue part of the previous bucket too, so nothing is skipped. Each run moves to queued with a compare-and-set, so if two dispatchers read the same bucket during a handover, only one wins each run.

Step 7: Leasing work to workers

Leases
  1. 01
    Leaserun is yours until lease_until
  2. 02
    Heartbeatlong jobs extend the lease every few seconds
  3. 03
    Completewrite the result, release the lease
  4. 04
    Expireno heartbeat, no completion: back to QUEUED
  5. 05
    Fencing tokenattempt number rejects late writes from a zombie worker

Now the most important mechanism: the lease. When a worker takes a run, it does not get it forever. It gets it until a time, say now plus the job's timeout plus a margin. The run's state becomes leased, with the worker id and the lease-until time, again written with a compare-and-set.

Long jobs heartbeat. A report that takes ten minutes sends a heartbeat every thirty seconds, each one pushing the lease forward. If heartbeats stop, the worker is presumed dead, the lease expires, and the sweeper puts the run back in the queue for another worker.

Here is the subtle failure interviewers probe. A worker pauses, perhaps a long garbage collection or a network partition. Its lease expires. Another worker takes the run and starts. Then the first worker wakes up and tries to report: I finished. Now two workers ran it, and the stale one is trying to overwrite the result.

The fix is a fencing token. Each lease carries the attempt number. When a worker completes, it sends its attempt number, and the store accepts the write only if that matches the current attempt. The zombie's late completion is rejected. It cannot undo what it already did in the outside world, but it cannot corrupt our state.

Choosing the lease length is a balance. Too short, and healthy but slow workers lose their leases, so jobs run twice. Too long, and a crashed worker's job waits a long time before anyone retries it. Using the job's own declared timeout, plus heartbeats for long jobs, gets the best of both.

Step 8: At-least-once and idempotency

Why not exactly-once
  1. 01
    The gapwork done, crash before reporting
  2. 02
    Scheduler seeslease expired, no result
  3. 03
    Choiceretry (maybe twice) or drop (maybe never)
  4. 04
    We chooseretry: at-least-once
  5. 05
    So jobs must beidempotent: running twice = running once

Now let us be honest about exactly-once. Picture this: a worker sends the email, then crashes before it can report complete. From the scheduler's side, the lease expired and there is no result. It cannot know whether the email went out. It must choose: retry and maybe send twice, or do nothing and maybe send zero times.

We choose retry, which gives at-least-once. The cost is that the job may run twice, so the job's effect must be idempotent. Running it twice must have the same effect as running it once.

How do job authors make that true? Give them a stable key: the job id plus the scheduled time, which stays the same across retries. The charge-subscription handler passes that key to the payment provider, which refuses a second charge with the same key. The email handler records the key in a sent table and skips if it is already there.

Say this clearly in the interview: the scheduler provides at-least-once delivery and a stable idempotency key; the handler uses the key to make the effect happen once. Exactly-once effect is a partnership between the two, never a promise the scheduler can make alone. That sentence alone earns a lot of credit.

Step 9: Retries, backoff and dead letters

Retry policy
AttemptDelayWith jitter
110 s7 to 13 s
220 s14 to 26 s
340 s28 to 52 s
480 s56 to 104 s
5give upmove to dead letters

When a run fails, the retry policy decides what happens. If retries remain, we create a new run, scheduled at now plus a backoff delay. Exponential backoff doubles the delay each time: ten seconds, twenty, forty, eighty.

Add jitter, a random spread around each delay. Why? If a downstream service fails at nine o'clock, ten thousand jobs fail together. Without jitter, they all retry together at ten past, twenty past, forty past, hammering the service just as it tries to recover. Jitter spreads them out.

After the last attempt, the run goes to a dead-letter list for that tenant, and an alert fires if the list grows. A human looks, fixes the bug, and can replay those runs with one call. Never silently drop a failed job, and never retry forever: a poison job that always fails would burn worker time forever.

Distinguish error types too. A timeout from a downstream service is worth retrying. A payload that fails validation will fail every time, so the handler should report it as permanent, and we skip straight to dead letters instead of wasting five attempts.

Step 10: Recurring jobs

Next run for a cron job
job: cron "0 9 * * MON", tz "Asia/Kolkata"

when run for Mon 09:00 is created:
  next = next_fire_time(cron, tz, after = this run's due_at)
  create run(job_id, due_at = next)  # same transaction

Recurring jobs, the cron jobs, are simpler than they look if you keep the job and run split. A cron job is a job definition with a schedule. We never create all its future runs. We create just the next one.

When a cron job's run becomes due, in the same transaction that queues it, we compute the next fire time and create the next run. So a job that runs every minute always has exactly one pending future run, and cancelling the job is just marking it cancelled and deleting that one run.

Compute the next time from the scheduled time, not the actual start time. Otherwise, if one run starts five seconds late, every future run drifts five seconds later, and after a year your nine o'clock job runs at ten past.

Time zones and daylight saving cause real bugs. Nine a.m. in a time zone that changes its clocks sometimes happens twice, or not at all. Store the schedule with its time zone, compute in that zone, and decide a rule: skip the missing hour, run once in the repeated hour. Mentioning this shows you have run schedulers in production.

Also decide the catch-up policy. If the whole system was down for an hour, an every-minute job has sixty missed runs. Do we run all sixty? Usually no. Most cron jobs want only the latest: run once now and move on. Make it a per-job setting, with run-latest-only as the default.

Step 11: Fairness between tenants

Fairness
  1. 01
    Queue per tenantper handler too
  2. 02
    Round-robinlease from tenants in turn, weighted by plan
  3. 03
    Quotasmax running and max due per second per tenant
  4. 04
    Prioritya separate lane for urgent jobs
  5. 05
    Spread advicenudge clients off exact round times

Many teams share this scheduler. At midnight, the billing team has five million jobs due. The security team has one job due: rotate a key. With a single queue, that one job waits behind five million. That is the noisy neighbour problem.

The fix is separate ready queues per tenant, and a leasing policy that takes from tenants in turn: weighted round-robin. Billing still gets most of the capacity, because it has the most work, but the security job is picked up within a second, because its tenant's turn comes round quickly.

Add quotas: a maximum number of concurrently running jobs per tenant, and a maximum due rate. A tenant who exceeds them is not rejected; their jobs simply wait a little. And offer a priority lane for urgent jobs, with a strict quota so everyone does not mark everything urgent.

Finally, gently help clients avoid the spike in the first place. Many jobs scheduled for exactly midnight do not need exactly midnight. Offer a window option, run any time between midnight and one, and spread those runs across the window. It costs nothing and flattens the biggest peak of the day.

Step 12: One job, end to end

Let us follow one job all the way through. A user's free trial ends in seven days, so the product creates a job: handler expire trial, payload with the user id, run at a time seven days from now, retry up to five times, timeout thirty seconds.

The job API checks the idempotency key, writes the job row and its first run row to the shard for that job id, in one transaction. The run is a week away, so it goes to the main store, not the hot index. The API returns a job id in a few milliseconds.

Six days and twenty-three hours later, the loader moves the run into the hot due index, in the bucket for its minute and its shard. At the due second, the dispatcher for that shard reads the bucket, flips the run from scheduled to queued with a compare-and-set, and pushes it onto the ready queue for the billing tenant's expire-trial handler.

A worker in the billing fleet leases it, getting attempt number one and a lease of forty-five seconds. It calls the account service, which marks the trial expired. Then the worker crashes before reporting complete. Forty-five seconds pass; the sweeper sees the expired lease and moves the run back to queued, with attempt number two.

Another worker leases it, calls the account service again, with the same idempotency key, job id plus due time. The account service sees the trial is already expired for that key, does nothing, and returns success. The worker reports complete with attempt number two, the store accepts it, and the run is recorded as succeeded after two attempts, about a minute late. No data was lost, and the effect happened exactly once. That is the whole design working together.

Step 13: Scaling and failures

What can fail
  1. 01
    Dispatchershard lease moves; reads overdue runs; seconds late
  2. 02
    Workerjob lease expires; retried with a new attempt
  3. 03
    Store shardreplicas take over; writes pause briefly
  4. 04
    Whole regionjobs replicated; fail over, accept some duplicates
  5. 05
    Downstream outagebackoff with jitter; dead letters after the limit

Let us check each failure. A dispatcher crashes: its shards are reassigned to another dispatcher through a lease of its own on the shard, and the new owner reads the overdue part of the bucket, so runs are a few seconds late, not lost.

A worker crashes: we just covered that, the lease expires and the run is retried. A store shard's primary fails: a replica is promoted, and writes to that shard pause for a few seconds. Because every component keeps its truth in the store, nothing else needs special recovery.

A whole region fails: replicate jobs to a second region. When failing over, some runs that had already started may run again in the new region. That is acceptable, because we promised at-least-once and our jobs are idempotent. You can see how that one decision keeps paying off.

And watch the right metrics: scheduling lag, the time between due and started, as a percentile per tenant; ready queue depth per handler; lease expiries, since a spike means workers are crashing or timeouts are too short; and dead-letter growth. Lag is the number that tells you whether the scheduler is keeping its main promise.

Step 14: The follow-up questions

Now the follow-up questions. Here are the ones interviewers ask most often.

Max asks

“How do you make sure only one dispatcher handles a shard at a time?”

Each dispatcher holds a lease on its shards in a small, strongly consistent coordination store, renewed every few seconds. If a dispatcher dies, its shard leases expire and another dispatcher claims them. And because each run moves from scheduled to queued with a compare-and-set, even a brief overlap during the handover cannot queue the same run twice.

Max asks

“Could you just use a message queue with delayed delivery?”

For small delays, yes, and it is a fine answer for minutes. But queues are not built to hold a billion messages for months, to cancel one specific message, to update its time, or to show history. A scheduler is really a database of future work, with a queue at the very end for work that is due now. That is exactly our design.

Max asks

“How do you cancel a job that is already running?”

Mark the job cancelled. Running work cannot be stopped from outside safely, so the next heartbeat returns a cancelled flag, and well-behaved handlers stop at their next checkpoint. Runs not yet leased are simply removed from the queue.

Max asks

“What if a client schedules a million jobs for the same second?”

Sharding spreads them across dispatchers, per-tenant queues stop them crowding others out, and the tenant's quota caps how fast they start. Their jobs finish over the next minute or so, and we report the lag to them so they can spread their schedule.

Max asks

“How would you support jobs that depend on other jobs?”

That is a workflow, a graph of steps. Store each step as a job with a list of parents, and when a run succeeds, check its children: any child whose parents are all done gets a run created. The same leases and retries apply to each step. Keep it as a layer on top, so simple jobs stay simple.

Recap

Recap
  1. 01
    Jobs vs runsdefinition vs one attempt
  2. 02
    Due indexminute bucket × shard
  3. 03
    Leasesexpiry, heartbeats, fencing tokens
  4. 04
    At-least-onceplus idempotency keys
  5. 05
    Retriesexponential backoff, jitter, dead letters
  6. 06
    Fairnessper-tenant queues, round-robin, quotas

Let us recap. Split the job from its runs. Index due runs by minute bucket and shard, so finding work due now is a cheap read and the midnight spike is spread across many dispatchers. Keep only the next hour hot.

Lease runs to workers with an expiry, extend with heartbeats, and reject zombie writes with fencing tokens. Promise at-least-once, and give handlers a stable key to make the effect happen once.

Retry with exponential backoff and jitter, send poison jobs to dead letters, compute cron times from the schedule, not the start time, and keep tenants fair with separate queues and quotas.

A scheduler is about honest guarantees under failure. Explaining the crash after the work and before the report, out loud and calmly, is the moment that wins this interview. You can practice this exact question with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in lesson twenty.

Now say it out loud

Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.

Practice with Max

Free: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.