Design a job scheduler
Read first: Queues and logs, Idempotency and the exactly-once myth, Consensus and Raft
A scheduler stores jobs until they are due, then leases each one to a single worker with a fencing token. Execution is at least once. The handler and any side effect have to be idempotent, because a crash after the work and before the ack runs the job again. Exactly-once is the trap. Shard the schedule by job id so one poller is not the whole system.
Someone wants a piece of work to run at 02:00, or in an hour, or every Monday. The honest contract is at least once. A worker will sometimes die after it has done the thing and before it has recorded that fact, and another worker will do the thing again. You make the second run harmless. You do not get a checkbox that makes an email, a charge, or a resize happen exactly once in the outside world.
Requirements
The user is a backend engineer submitting work: send this reminder later, generate this thumbnail, close out invoices on a schedule. They want a status they can read, and they want a failed job to retry without paging them on the first blip.
Functional requirements:
- Accept a job to run at a timestamp, or a schedule that fires repeatedly.
- Run it on a worker, with a lease so two workers do not run it at once.
- Retry failures with backoff, then stop and leave a dead-letter status.
- Show queued, leased, succeeded, retrying, or dead.
Non-goals:
- A workflow engine with a compensation for every branch. That is a saga. One job is one local action.
- Sub-millisecond dispatch. This design thinks in seconds. A trading gateway is a different page.
- Exactly-once side effects in someone else’s system. You can get a single row in your database. You cannot get a single email by wishing.
Estimation
Assumptions:
- 20 million jobs submitted a day. In steady state, 20 million become due a day.
- The top of the hour is lumpy. Assume a peak due-rate of 20× the average for a short window. The 20× is the clump, not a measured trace.
- A job body runs for 200 ms on average. Mixed emails and image work, stated as an assumption.
- A job row is 800 bytes of metadata plus a pointer to any large payload.
- Keep metadata 7 days, three copies. A “fat” payload you might have been tempted to inline is 100,000 bytes.
average due 20e6 / 86,400 ≈ 231 / s
shortcut 20e6 / 1e5 = 200 / s
peak, 20× 231 * 20 ≈ 4,620 / s
concurrency 4,620 * 0.2 s ≈ 924 in flight at that rate
metadata 20e6 * 800 B = 16 GB / day
7 days, 3 copies 16 * 7 * 3 = 336 GB
fat payload 20e6 * 100,000 B = 2 TB / day
A day is 86,400 seconds. About 231 jobs a second average, and a top-of-hour window at the assumed 20× wants about 4,620 a second. Little’s law at that rate is 4,620 × 0.2 seconds, about 924 jobs in flight for as long as the clump holds. One process cannot be those 924 workers and also the thing that decides what is due. Split them.
The 2 TB a day is why the row stores a pointer and the bytes live in object storage. Metadata at a few hundred gigabytes with retention and copies is the store you actually operate. The payload is not a column.
High-level design
The submit API inserts a durable row: run_at, payload pointer, status queued, and a unique job id. It acks the client after that commit. Schedulers are shard owners. Each owner polls only its shard for rows that are due and not validly leased, claims a batch, and hands the batch to a worker pool. Workers do the work, heartbeat the lease, and mark the row succeeded or set a next retry time. A schedule row creates execution rows when it fires. It is not itself the execution.
flowchart LR
client[Job submitter]
api[Scheduler API]
store[Job table]
owner[Shard owner]
worker[Worker pool]
effect[Side effect]
client --> api
api --> store
owner --> store
owner --> worker
worker --> effect
worker --> store
Workers are many and replaceable. Shard owners are few and elected. A job that is not yet due stays in the table. You do not push it onto a worker queue six hours early and hope the queue understands time.
Deep dive
At least once, and the lease
Delivery has three words and only two of them are strategies you can implement by when you send the ack. Ack after the handler returns, and a crash in between runs the job twice: at least once. Ack before the handler runs, and a crash skips it: at most once. There is no third ack timing that reaches into an email provider and retracts a send.
The lease is what keeps “twice” from being “twice at the same time” in the common case. A claim is one conditional update. It sets a lease owner, a deadline, and a fencing token, and it matches only a row that is queued or whose previous lease has already expired. The winner sees one row change. The loser sees zero and must not run the body.
SET status = leased
lease_owner = this worker
lease_until = database now plus 30 seconds
fence = fence + 1
WHERE job id matches
AND the lease is empty or already expired
Assumption: the lease is 30 seconds, and a healthy worker heartbeats every 10 seconds to push the deadline. Use the database clock in that statement. Two app servers’ wristwatches are not a lease. If the worker’s heartbeat stops, the row becomes claimable again and someone else runs it.
A worker that pauses past the deadline and then resumes is the dangerous overlap. It still thinks it holds the job. Every external write has to present the fencing token, the same idea as fencing an old database primary. The token is stale, the write is rejected, and the late worker stops. Replication failover has the same bug if you skip the fence. A wall clock alone will not tell the paused worker that it was replaced.
Idempotent work, or the second run is a second email
The job id is the natural idempotency key for the handler. “Write this thumbnail object” can be the same write twice. “Add one to invoices_sent” cannot. Prefer a handler that sets state. Where the handler has a side effect, store a row for that job id.
Do the side effect in stages. Record that you are about to send, then send with the job id as the provider’s idempotency key if it has one, then record that you sent. A retry continues from the recorded stage. A local transaction can roll back. The send cannot. If the provider has no idempotency key, you can still narrow the window and you cannot honestly promise the mail was unique. Say that. It is the grown-up answer.
Exactly-once is the trap, including when a log system offers it. A log with an idempotent producer can give you effectively-once processing inside that log’s protocol. Kafka is explicit about the boundary: the guarantee stops at the log. The moment the handler sends mail or charges a card, you are back to at least once plus a key. A scheduler that advertises exactly-once because the queue library said so will double-send on the first worker crash after a successful SMTP response.
Delayed jobs and a schedule that is not one machine
A delayed job is a row with run_at in the future and status queued. The owner’s poll is “due now, and not leased,” limited to a batch, ordered by run_at inside the shard. An index on that access path is the difference between a poll and a table scan. Claim in batches. One round trip per job will not clear a 4,620-per-second clump.
Recurring schedules store a next fire time. When it is due, insert an execution whose id is the schedule id plus the nominal fire time, then advance next fire time. Insert first. If you crash, the retry inserts the same id and changes nothing, then advances. If you advance first and crash, that tick never existed. The nominal time is part of the id so daylight-saving jumps and a slow owner do not create a second Monday.
One scheduler process polling one table feels fine at 231 jobs a second and becomes a permanent bottleneck at the clump, and a permanent single failure either way. Partition by hash of job id into a fixed number of shards. Assumption: 32 shards. The peak of about 4,620 claims a second becomes about 4,620 / 32 ≈ 144 claims a second per shard, which a batch update handles. Each shard has an owner, elected with a lease or a consensus term. Clocks alone are a poor election. The bully algorithm is a poor election. When the owner dies, the lease expires and another process takes that shard only. Workers keep running jobs they already hold until those leases expire.
Hash the job id. Do not range-partition by run_at. A time range puts every job that is due “now” on the shard that owns now, which is the hot partition you built on purpose. Order across tenants is not a requirement. If one tenant needs its own jobs in submit order, that is a per-tenant sequence and a known hot key, and you subdivide that tenant when they dominate a shard. Assumption to illustrate: one tenant submits half of the 20 million. Hashing by tenant pins about 10 million a day on one shard. Hashing by job id spreads them. Most jobs do not need to observe each other.
Partitioning the workers is not the same split. Any worker can run any claimed job. The shard owner is the only thing that is pinned to a slice of the table. You can put 32 owners on a handful of machines and run the 924 workers as a pool that scales with the peak. The owner must not also be the worker if you want that pool to grow.
Tradeoffs
| Choice | What you gain | What you spend |
|---|---|---|
| Ack the submit after the row commits | An accepted job survives a crash | The client waits for a database commit |
| At-least-once execution with a lease | A dead worker’s job gets run by someone else | Handlers and side effects must tolerate a second run |
| At-most-once, ack before the body | No duplicates | A crash silently skips the job |
| Lease of 30 seconds with a fence | Two live workers rarely run one job, and a paused worker cannot keep writing | Heartbeat traffic, and a job can start late by about a lease period |
| Hash shard by job id | The top-of-hour clump spreads, and owners can fail independently | You give up a global due-time order across shards |
| Range shard by run_at | The “next to fire” scan looks tidy | The shard that owns now takes the entire clump |
| Insert the cron execution, then advance | A crash retries the same tick | You store executions as rows, one per fire time |
| Dead-letter after a small attempt budget | A poison job cannot occupy a worker forever | A human has to look, or the work never happens |
Failure modes
Dependency down. The database that holds the leases is down. Stop claiming. Do not run from a cached list of due jobs, or you will run them with no fence and run them again when the database returns. Workers whose side-effect provider is down should release the job with a retry time, not spin. The schedule being late is acceptable. The schedule double-applying is the bug you built the lease to prevent.
Retry storm. A bad deploy makes every job throw. If they retry immediately, the 924 workers fill with the same failures and the next hour never starts. Retries need exponential backoff, full jitter, and a max attempt count. Assumption: 8 attempts, then dead-letter. A job that fans out a million children in one transaction will time out and retry the fan-out. Enqueue children in batches, each child its own idempotent id.
Hot partition. The top of the hour on a time-ranged shard, or a single tenant hash. You will see one owner’s poll fall behind while the other 31 are idle. Move the split to job id, and split a tenant that still dominates. A global “next job” row that every owner locks is a hot key you added for convenience. Each shard already knows its next due row.
Consistency. Two workers both read a row as queued and both run it, because the claim was a read followed by a blind write. The conditional update is what makes the second one see zero rows. A worker that ignores a rejected fencing token is the same bug after a pause. Exactly-once as a status flag, with no lease, fails the same way: both workers pass the check before either writes the flag.
Durability. Acking the submitter before the insert commits loses the job on a crash while the client believes it is scheduled. Do the insert, then ack. The execution side is deliberately not exactly-once. Durability of the row plus at-least-once delivery is the contract. A dead-letter row has to be durable too, or a poison job vanishes and looks like success.
In the interview
First five minutes: at least once, a lease with a fencing token, handlers that can run twice, delayed rows polled by shard owners, workers as a separate pool. The numbers, under the assumptions: about 231 a second average, a 20× clump around 4,620, about 924 in-flight workers if a job runs 200 ms. The bottleneck at the clump is claim rate on an unpartitioned table, then worker slots. The tradeoff is duplicates against lost jobs, and you pick duplicates with idempotency.
Skip a workflow DSL and a debate about cron syntax. Mention exactly-once in order to reject it, in one breath: inside a log protocol it can be real, and it ends at the side effect.
The question that usually follows is “two workers take the same job.” Walk the conditional claim and the fence after a long pause. The next one is “how is this not a single scheduler forever?” Thirty-two hash shards, an owner lease per shard, workers unpinned.
Check yourself
A worker sends the email, then crashes before it marks the job succeeded. What runs, and what did you not promise?
The lease expires and another worker runs the job. That is at-least-once. You did not promise the email was unique. The handler has to record a stage and pass an idempotency key so the second run does not send a second mail if the provider cooperates. If the provider cannot dedupe, you say so.
Both workers read the row as queued and both start the body. Which claim shape stops that, and what does the loser see?
One conditional update that sets the lease and the fencing token only while the lease is empty or expired. The winner sees one row change. The loser sees zero rows and does not start. A read of status followed by an unconditional write lets both pass the check.
Why do you insert a cron execution row before you advance next fire time?
The execution id is the schedule id plus the nominal fire time, so the insert is idempotent. A crash after the insert retries cleanly and then advances. A crash after an early advance skips that tick forever. The order is the difference between a duplicate you can ignore and a hole you cannot see.
The top of the hour makes about 4,620 jobs due in a second under the lesson assumptions. Why is a shard per time range the wrong split?
Every one of those jobs has a run_at in the hot window, so they all land on the shard that owns now. The other shards sit idle. Hashing by job id spreads the same clump. With 32 shards that is about 144 claims a second each, which a batch claim can do. You did not need a global order of due times.
A queue library says it is exactly-once. A job sends email. What is the boundary?
Effectively-once processing can hold inside the log protocol, for the records the log itself stores. It does not extend to SMTP. The scheduler’s contract stays at least once, the job id is the key, and a fencing token stops a replaced worker from completing a late write. Advertising exactly-once past that boundary is how a duplicate mail becomes a surprise.
Based on: Designing Data-Intensive Applications, Kleppmann and Riccomini; Alex Xu, ByteByteGo volumes; Kafka, Jay Kreps, Neha Narkhede, and Jun Rao.