SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
  • Design a Chat App
  • Design a News Feed
  • Design a Notification System
  • Design a Web Crawler
  • Design Search Autocomplete
  • Design File Storage (Dropbox)
  • Design Video Streaming (YouTube/Netflix)
  • Design a Distributed Cache
  • Design a Leaderboard
  • Design a Job Scheduler
  • Design a Social Media Platform (Facebook)
System Design/Case Studies/Medium
Interview case study

Design a Job Scheduler

Run jobs at the right time, exactly when needed, even when machines fail.

⏱ 34 min readMedium case studyAdvanced22 cross-questionsHas visualizer
Prompt60-sec answer45-min plan1 Clarify2 Estimate3 API + Data4 Design5 Deep dives6 Scale7 Wrap upCross-questionsVariationsScoringMistakesCheat-sheet

StartThe prompt and what is really being tested

The interviewer says

“Design a distributed job scheduler.”

It is short on purpose. Your first job is to make it specific.

What they checkWhy it matters
Pinning down the problem“Scheduler” can mean cron, delayed tasks, or a workflow engine. A strong candidate asks which one, how precise it must be, and what happens when a job fails.
Finding due jobs efficiently10 million jobs cannot be scanned every second. The interviewer wants an index, partitions, and a look-ahead window, not a thread per job.
No double fire, no lost jobThis is the heart of it. Two schedulers, a crash in the middle, a paused process: you must show how each case ends with the job running at least once, and how you make a repeat harmless.
Honest delivery semanticsExactly once is not on offer. Say at least once, then show leases, retries and idempotency keys that make the effect happen once.
Operating itTop-of-the-hour spikes, noisy tenants, outages and catch-up, and how you would know the scheduler is late. This is where real systems hurt.

TL;DRThe whole design in 60 seconds

A job scheduler turns “run this at 09:00, every day” into a run that really happens, on time, even when machines fail. We store jobs in a sharded database, find the ones that are due with an index, hand each due run to a queue, and let workers pull runs with a lease and a heartbeat. Delivery is at least once, so every run carries an idempotency key.

  • Scale: 10M jobs and 40M runs a day is only about 460 runs a second on average and 1,000 at peak. The hard part is the top-of-the-hour burst (10 times that for a few seconds), not the average.
  • Finding due jobs: a database index on (next run time, status), sharded by job id. Each shard has one owner that loads the next 30 seconds of jobs into an in-memory heap and fires them from there. No sleeping thread per job.
  • No double fire: each shard is owned through a lease with a fencing token, and a run is claimed with an atomic compare-and-set. If an owner dies, its lease expires and another takes over.
  • Reliability: workers lease a run and send heartbeats. If the heartbeats stop, the run goes back on the queue. Retries use backoff with jitter, then a dead-letter queue.
  • Exactly once? No. We promise at least once, plus an idempotency key on (job id, scheduled time) so a repeat does nothing.
  • Operate it: spread the :00 spike with jitter, alert on scheduling lag (actual minus scheduled), and decide up front what a missed run does after an outage: fire once, fire all, or skip.
💡How to use this page
Read the 60-second answer first. Then work through steps 1 to 7 in order, and try each step yourself before reading the model answer. Finish with the cross-questions: say your answer out loud, then open the model one.

PlanA 45-minute plan

4
3
5
8
15
7
3
Minutes per step (total 45). A guide, not a rule: move time to the part the interviewer cares about.
StepMinutesWhat to get done
1. Clarify4One-off or recurring, how precise, at least once or at most once, what a job does, and what a missed run means.
2. Estimate3Runs per second, the :00 burst, storage for jobs and history, and why a full scan fails.
3. API and data5Create a job, the jobs and runs tables, the worker lease calls.
4. High-level design8API, sharded database, timer tier, queue, workers. Follow one run from due to done.
5. Deep dives15Finding due jobs, then no double fire and no lost job, then worker reliability, then scale and operations.
6. Scale and failures7The :00 spike, a dead scheduler, a dead worker, an outage and catch-up.
7. Wrap up3Recap, the at-least-once trade-off, and what you would build next.

Step 1Clarify requirementsabout 4 min

🤔
Pause. Try it yourself first
You have 60 seconds. Write five questions that would change your design. Hint: think about what a job does, how late is too late, what happens if the system is down at the due time, and whether a job may run twice.

Questions to ask, and why

AskWhy you ask itTypical answerHow it changes the design
Are jobs one-off, recurring, or both? Do recurring jobs use cron expressions?Recurring jobs need a next-run calculation after every run. One-off jobs do not.Both. Recurring jobs use cron expressions and time zones.We store next_run_time and recompute it each time a run is created. Cron parsing and daylight saving rules matter.
How precise must the start time be?Seconds and minutes are very different problems. It sets how often we look and how tight the timers are.Within a few seconds of the due time at the 99th percentile.A look-ahead loader and in-memory timers, not a one-minute poll.
What does a job do: call an HTTP endpoint, put a message on a queue, or start a container?It decides how long a run lasts, how we detect failure, and what we must protect.Mostly an HTTP call or a queue message. Runs finish in seconds, a few last minutes.Workers are simple callers. Long runs need a lease with renewal.
May a job run twice, or must it run at most once?At least once and at most once pull the design in opposite directions.It must never be skipped. A rare duplicate is acceptable if the job is safe to repeat.At-least-once delivery, with an idempotency key we pass to the target.
What if the system is down at the due time? Run late, skip it, or run all the missed ones?This is the misfire policy. It is a product decision, and it changes the catch-up logic.Configurable per job. The default is run once as soon as possible.A misfire policy field on each job, and a catch-up path after an outage.
Can jobs be paused, changed or cancelled, even while a run is in progress?Updates race with firing. We need version checks.Yes to all three.A version number on each job, and a claim that checks it.
Do jobs have retries, timeouts and priorities? Is there a limit per tenant?These shape the queues, and they protect us from one noisy customer.Retries with backoff and a timeout per job, three priority levels, and a quota per tenant.Queues by priority, a retry policy in the job, and fairness per tenant.
Do jobs depend on each other, as in a workflow?A dependency graph is a different system.No. Independent jobs only.We leave workflow engines out and mention them as the next step.
How many jobs, and how many runs a second, including the busy moments?The top-of-the-hour burst, not the average, sizes the system.10 million jobs, 40 million runs a day, about 1,000 a second at peak and 10 times that for a few seconds at :00.We shard the database and the timers, and we spread the spike.
One region or several? What availability do we need?Multi-region scheduling can fire a job twice, once from each region.One region, three zones, 99.95% available. Mention multi-region.No cross-region coordination now. We describe it as an extension.

Write the scope on the board

Functional (must do)
  • •Create, read, update, pause, resume and delete one-off and recurring jobs
  • •Fire each run at its scheduled time and deliver it to a target (HTTP call or queue message)
  • •Retry failed runs with backoff, and keep a history of every run
  • •Never lose a due job, and avoid running it twice when we can
  • •Apply a misfire policy after an outage, and support time zones in cron
Non-functional (how well)
  • •Lateness: runs start within 5 seconds of their time at p99
  • •Available: 99.95%, with no single scheduler as a single point of failure
  • •Delivery: at least once, with an idempotency key on every run
  • •Scale: 10M jobs, 1,000 runs a second at peak, 10,000 a second for a few seconds
  • •Fair: one tenant must not delay the others
Out of scope (say it)
  • •Workflows and dependency graphs (that is an orchestrator such as Airflow)
  • •Running the job code itself (we call a target, we do not host the code)
  • •Exactly-once execution (it does not exist; we offer idempotency)
  • •A user interface and billing
🎤
Say it out loud
“Let me confirm the scope. We schedule one-off and recurring jobs, with cron expressions and time zones. Each run calls an HTTP endpoint or puts a message on a queue. A run must never be lost, and an occasional repeat is fine as long as we give the target an idempotency key. I will design for 10 million jobs, 40 million runs a day, 1,000 runs a second at peak and 10 times that for a few seconds at the top of the hour, starting within five seconds of the due time. After an outage the default is to run a missed job once, and that is a setting on the job. Workflows with dependencies are out of scope. Does that match?”

Step 2Estimate the scaleabout 3 min

🤔
Pause. Try it yourself first
On paper: runs per second on average and at peak, the :00 burst, storage for jobs and for run history, and what a full table scan every second would cost.

Assumptions (say them first)

AssumptionValue
Registered jobs10 million
Runs per day40 million
Peak rate (busy hours)about 1,000 runs per second
Top-of-the-hour burst10,000 runs per second for about 10 seconds
Job definition sizeabout 1 KB (schedule, target, payload, retry policy)
Run record sizeabout 300 bytes
Run history kept30 days
Average run length5 seconds (an HTTP call)
One worker100 concurrent runs
Database shards16 (by hash of job id)
Look-ahead window30 seconds

The arithmetic, line by line

WhatMathsResult
Average runs per second40,000,000 ÷ 86,400about 460 per second
Peak versus average1,000 ÷ 460about 2 times
Runs in one :00 burst10,000 per second × 10 seconds100,000 runs
Job definitions on disk10,000,000 × 1 KB10 GB (30 GB with 3 copies)
Run history per day40,000,000 × 300 bytes12 GB per day
Run history for 30 days12 GB × 30360 GB (about 1.1 TB with 3 copies)
A naive scan every second (no index)10,000,000 rows × about 100 bytesabout 1 GB read per second, to find 460 rows
Due jobs per shard at peak and in a burst1,000 ÷ 16 and 10,000 ÷ 16about 63 and 625 per second per shard
Database writes at peak (about 5 per run: claim, create, lease, finish, next time)1,000 × 5, then 10,000 × 55,000 per second at peak, 50,000 in a burst (about 3,100 per shard)
Concurrent runs at peak1,000 per second × 5 seconds5,000 runs, so 5,000 ÷ 100 = 50 workers
Draining a :00 burst on 50 workers100,000 runs ÷ 1,000 runs per secondabout 100 seconds for the last run (too late)
Jobs held in memory per 30-second window460 × 30 (average) and 100,000 × 200 bytes (burst)about 14,000 jobs; 20 MB in a burst
What the numbers tell us about the design
  • •The average is small (460 a second). The :00 burst, 10 times the peak, decides worker counts and lateness. We must spread it or scale for it.
  • •Job definitions are only 10 GB, so the database is not big. We shard for write throughput (50,000 writes a second in a burst) and for a short scan per shard.
  • •A full scan every second reads about 1 GB to find 460 rows. An index on (next run time, status) reads only the due rows, so an index is not optional.
  • •The look-ahead window is tiny (14,000 jobs, or 20 MB in a burst), so holding the next 30 seconds in memory is cheap, and it is what makes timing precise.
  • •Draining a 100,000-run burst on 50 workers takes 100 seconds. So we add jitter, queue by priority, and autoscale workers, and we measure scheduling lag.
🎤
Say it out loud
“Let me do the maths. 40 million runs a day is about 460 a second on average, 1,000 at peak, and a burst of 10,000 a second for ten seconds at the top of the hour, which is 100,000 runs. Job definitions are only 10 gigabytes, so the database is small. We shard it for write throughput: five writes per run is 50,000 writes a second in a burst. A full scan every second would read about a gigabyte to find 460 rows, so we need an index on next run time. And 50 workers would take 100 seconds to drain a burst, so the burst is the real design problem.”

Step 3Define the API and the data modelabout 5 min

🤔
Pause. Try it yourself first
Write the call that creates a recurring job, then the two tables you need: one for the job and one for each run. Which columns let you find due work fast, and which let a worker prove it owns a run?

Endpoints

MethodPathRequestResponseNotes
POST/v1/jobs{ schedule: { cron, timezone } or { runAt }, target, payload, retry, timeoutSec, misfire, priority }201 { jobId, nextRunTime }Send an Idempotency-Key header so a retried create does not make two jobs. Validate the cron and the target. The tenant comes from the credential.
GET/v1/jobs/{id}none200 { job, nextRunTime, state }Reads from the primary or a recent replica. Tenant-scoped, so another tenant gets 404.
PATCH/v1/jobs/{id}{ version, schedule?, status? }200 { version }Update, pause or resume. The version makes it a compare-and-set, so it cannot clash with a firing run. 409 on a stale version.
DELETE/v1/jobs/{id}none204Soft delete: mark it so the timer drops it. A run already in flight is allowed to finish, or is cancelled if the job says so.
GET/v1/jobs/{id}/runsnone200 { runs, nextCursor }Paginated run history with state, attempt and times. Reads the history store, not the hot tables.
POST/internal/runs/lease{ workerId, queues, max }200 { runs: [{ runId, jobId, scheduledTime, token, leaseUntil, idempotencyKey }] }Worker side. A worker leases runs, then calls heartbeat to extend the lease and complete or fail to finish. Complete and fail carry the token, and are ignored if it is stale.

Data model

jobs table (sharded by hash of job id)TypeWhy it is there
job_id, tenant_ididThe key, and the owner for quotas and access.
schedule (cron, timezone) or run_attext, timestampWhat the user asked for.
next_run_timetimestampWhen the next run is due. Indexed, and the main field the timer reads.
statusenumACTIVE, PAUSED or DELETED. The timer only reads ACTIVE.
versionintBumped on every change. Used for compare-and-set.
target, payload, retry policy, timeout, misfire policy, priorityjsonHow to run it and what to do when it fails or is missed.
runs table (same shard as its job)TypeWhy it is there
run_ididUnique per run. Includes the attempt number.
job_id, scheduled_timeid, timestampTogether they are the idempotency key. A unique index on them stops a second run row for the same slot.
stateenumPENDING, LEASED, RUNNING, SUCCEEDED, FAILED or DEAD.
attemptint1 for the first try, higher for retries.
lease_expires_at, worker_id, tokentimestamp, id, intWho owns the run now and until when. The token grows each time a new owner takes over.
The two queries that matter
-- find due jobs in one shard (served by an index on (status, next_run_time))
SELECT job_id, next_run_time, version
  FROM jobs
 WHERE status = 'ACTIVE' AND next_run_time <= now() + interval '30 seconds'
 ORDER BY next_run_time
 LIMIT 1000;

-- claim one due job and create its run, in one transaction (compare-and-set on version)
UPDATE jobs SET next_run_time = :next, version = version + 1
 WHERE job_id = :id AND version = :seen AND next_run_time = :due;   -- 1 row means we won
INSERT INTO runs (job_id, scheduled_time, state, attempt) VALUES (:id, :due, 'PENDING', 1);
📝Which store, and why
Job definitions and run state are small, need transactions (claim a job and create its run together) and secondary indexes (find what is due), so a sharded relational database, or a store with transactions and an ordered index, fits. We shard by hash of job id so a job and its runs live together and a claim is a single-shard transaction. Old run history is not needed on the hot path, so it is copied to cheap storage partitioned by day and dropped after 30 days. A key-value store alone would make the due-time index and the claim transaction hard.
🎤
Say it out loud
“Creating a job is a POST with a cron and time zone or a single run time, the target, a retry policy and a misfire policy, with an idempotency key. I keep two tables in a sharded relational database, by job id. The jobs table has next run time and a version, with an index on status and next run time. The runs table has one row per run, with a unique key on job and scheduled time, which is also our idempotency key, plus a lease with an expiry and a growing token. Firing a job is one transaction: compare-and-set the job's next run time and insert the run.”

Step 4Draw the high-level designabout 8 min

🤔
Pause. Try it yourself first
Draw the boxes that take a job from 'due' to 'done'. Where does the clock live? Which part may exist twice, and which must have exactly one owner?
Job scheduler: high-level design
👤Clientscreate, pause, list
→↓HTTPS
🚪API servicevalidate, auth, quotas
→↓write
Metadata DB (16 shards)
🗄️jobs + runsindex on next_run_time
📋Replicas
Timer tier
⏱️Shard ownerlease + token per shard
🧮In-memory heapnext 30 s of jobs
Dispatch
📨Priority queueshigh, normal, low
☠️Dead-letter queue
Workers (autoscaled)
⚙️Worker fleetlease, heartbeat, call target
🌐TargetsHTTP or queue
Control
🗳️Lease storeetcd or ZooKeeper
📈Metricslag, depth, failures
Each shard has one timer owner. Due runs go to priority queues. Workers lease runs and send heartbeats. Results update the same shard.
ComponentWhat it does
API serviceValidates a job, checks the tenant quota, writes it, and computes the first next run time. It never fires jobs.
Metadata DB (sharded)Holds jobs and runs. An index on (status, next_run_time) makes finding due work cheap. A job and its runs live on one shard.
Timer tier (shard owners)One owner per shard, chosen with a lease. It loads the next 30 seconds of due jobs into a heap and fires each at its time.
Lease store (etcd or ZooKeeper)Gives each shard to one owner at a time with a lease and a growing token. A dead owner loses its lease when it expires.
Priority queuesReceive due runs. Separate queues for priority and for large tenants, so one burst cannot block everything.
Worker fleetLeases a run, calls the target, sends heartbeats, then reports success or failure. Autoscaled on queue depth and lag.
Dead-letter queue and historyRuns that keep failing go to the DLQ for a human. Finished runs are copied to cheap history storage.
Metrics and alertsThe key number is scheduling lag (actual start minus due time). Also queue depth, failure rate and stuck runs.
Write path (follow one request)
  1. A client sends POST /v1/jobs with a cron expression, a time zone, the target and a retry policy.
  2. The API service validates it, checks the tenant quota and the idempotency key, and computes the first next_run_time in UTC.
  3. It writes the job to its shard (chosen by hash of job id) with status ACTIVE and version 1.
  4. It returns 201. If the new next_run_time is inside the owner's 30-second window, the owner is nudged to load it, or the next loader pass picks it up.
  5. Changing or pausing a job is a PATCH that bumps the version, so a firing run that read the old version fails its compare-and-set and re-reads.
Read path (follow one request)
  1. The shard owner's loader reads the next 30 seconds of ACTIVE jobs from its shard and puts them in an in-memory min-heap by due time.
  2. When the clock reaches a job's time, the owner runs one transaction: compare-and-set the job (new next_run_time, version + 1) and insert the PENDING run.
  3. It publishes the run to a priority queue (through an outbox, so the run row and the message cannot disagree).
  4. A worker leases the run with a token and a short lease, calls the target with the idempotency key, and sends heartbeats while it works.
  5. On success the worker reports it with its token. On failure the run is retried with backoff and jitter, and after the last attempt it goes to the dead-letter queue.
  6. If a worker dies, its heartbeats stop, the lease expires, and the run goes back on the queue with a higher token.
🎤
Say it out loud
“Here is the picture. Clients create jobs through an API that writes to a sharded database. Each shard has one timer owner, picked with a lease from etcd or ZooKeeper. The owner loads the next 30 seconds of due jobs into an in-memory heap and, when a job is due, does one transaction: advance the job's next run time and insert a run. The run goes through an outbox to priority queues. Workers lease a run, call the target with an idempotency key, and send heartbeats. If a worker dies, the lease expires and the run is queued again. Failures retry with backoff and then land in a dead-letter queue.”

Step 5Deep dive into the hard partsabout 15 min

🧠The pattern for every deep dive
Problem → options → pick one → say why → say what it costs. Interviewers score the reasoning more than the choice.
5.1

Finding the due jobs, on time

The problem: We have 10 million jobs and must start each within seconds of its time. Scanning the table every second reads about 1 GB to find a few hundred rows, and one sleeping thread per job is impossible. And a thousand jobs set for 09:00:00 all become due in the same second.

OptionHow it worksGoodBad
Poll the database with an indexEvery second, run SELECT ... WHERE status = ACTIVE AND next_run_time <= now() on each shard, using an index on (status, next_run_time).Simple. The database is the source of truth. The index reads only the due rows.Precision is limited by the poll interval. Many polls per second add load. Every miss shows up as lateness.
Look-ahead loader + in-memory heapEvery 10 seconds, load the next 30 seconds of due jobs into a min-heap (or a timing wheel). A timer pops the heap at the right moment and fires each job.Precise to the millisecond. One cheap indexed read per 10 seconds. Handles bursts smoothly.State in memory: a restart must reload. A job created or changed inside the window must be noticed.
Delay queue or Redis sorted setPush (time, job) into a store where the score is the due time. A poller takes items whose score is at or before now.Easy and fast. Good for one-off delayed tasks and retries.Memory limited and a second source of truth to keep in sync with the database. Native delays in cloud queues have a maximum.
Hierarchical timing wheelsA wheel of buckets by second, with coarser wheels for minutes and hours. Inserting and firing are constant time.Very cheap with millions of timers. Used inside kernels and brokers.More complex to build. Rarely needed once the heap holds only 30 seconds of jobs.
Pick
A look-ahead loader per shard, with an in-memory heap, backed by the database index

The database stays the source of truth, and memory only holds the next 30 seconds: about 14,000 jobs on average, or 20 MB in a burst. The loader does one cheap indexed read every 10 seconds, the heap fires each job at its exact time, and a restart simply reloads the window. Plain polling is fine to start with, but it makes timing depend on the poll interval and puts steady read load on the database.

A job that is created or edited inside the window is handled by a small re-check: the API tells the owner, or the next loader pass notices a new version. Before firing, the owner always re-reads the job's version, so a job that was paused a moment ago is not fired.

💡Spreading the :00 burst
Do not let 100,000 runs hit the same second. Add a small random jitter (a few seconds) to jobs that do not need exact timing, offer a fixed "start within the next minute" option, and place new cron jobs on a random second inside the minute when the user did not ask for one. Then queue by priority and autoscale workers.
Misfire policy (outage or lag)What it doesGood for
Fire once nowRun one catch-up run, then continue on schedule.Most jobs. The default.
Fire all missedRun every missed slot, in order, with a limit.Per-slot work such as hourly billing.
SkipDrop the missed runs and wait for the next slot.Refresh jobs where only the latest matters.
🎤
Say it out loud
“Polling the whole table is too slow, and a thread per job is impossible. I would keep the database as the source of truth with an index on status and next run time, and have each shard owner load the next 30 seconds into an in-memory heap every 10 seconds. A timer pops the heap and fires each job at its time. That is one cheap indexed read per ten seconds and precise timing. I would add jitter for the top-of-the-hour spike, and a misfire policy per job: fire once, fire all, or skip.”
5.2

No double fire, no lost job

The problem: We run several scheduler instances for availability. Two of them may both think a job is theirs. One may pause or die right after claiming it. If both fire, the job runs twice. If the claimer dies, the job may never run.

OptionHow it worksGoodBad
One leader fires everythingElect a single leader (ZooKeeper or etcd). Only the leader fires jobs.No races between schedulers. Simple to reason about.One machine is the bottleneck at 10,000 runs a second. A paused old leader can still act after a new one is elected.
One owner per shard, with a lease and fencing tokenEach shard is owned by one scheduler through a lease. The token grows with each new owner, and the database rejects writes with an older token.Scales by shard. A paused old owner is stopped by its stale token.Needs a lease store and a token check on every claim. Shard moves must be handled carefully.
Optimistic claim in the databaseAny scheduler may try. UPDATE jobs SET next_run_time = :next, version = version + 1 WHERE job_id = :id AND version = :seen. One row changed means we won. Or use SELECT ... FOR UPDATE SKIP LOCKED to take a batch.No lease service needed. Exactly one winner per claim, even with many schedulers.Every scheduler reads the same due rows and most claims fail. A claim with no expiry would lose a job if the claimer died (here the claim is the transaction, so it commits or not).
Allow duplicates, remove them downstreamFire from anywhere, and rely on a unique key on (job_id, scheduled_time) to make a second run row, and the target, ignore the repeat.Simplest. Always safe, even when other layers fail.Wasted work and load. The target must honour the idempotency key.
Pick
Shard ownership with a lease and fencing token, a compare-and-set claim, and an idempotency key as the last line of defence

Use all three layers, because each covers a hole in the others. Shard ownership keeps contention low. The compare-and-set claim (job version plus the unique run key) guarantees that, even if two owners overlap for a moment, only one inserts the run for a given scheduled time. And the idempotency key goes to the target, so a retry or a late duplicate is harmless.

The nasty case is a paused owner: it claimed a job, froze for 20 seconds, and its lease expired. A new owner took the shard. When the old one wakes, it still believes it owns the shard. The fencing token fixes this: the old owner's writes carry token 1, the database has seen token 2, and it rejects them. See the visualizer below to play with this.

Moment the scheduler diesState left behindRecovery
Before the claim transactionJob still due, nothing changedThe next owner loads it and fires it. Late by about a lease length.
After the claim, before the queue publishRun row PENDING, no messageThe outbox publisher sends it, or a sweeper republishes old PENDING runs. Same run key, so no duplicate row.
After the publishMessage on the queueA worker leases it as normal.
Claim a due job (one transaction, one winner)
BEGIN;
UPDATE jobs SET next_run_time = :next, version = version + 1
 WHERE job_id = :id AND version = :seen AND next_run_time = :due AND :token >= shard_token;
-- 0 rows: someone else won, or our token is stale. Stop.
INSERT INTO runs (job_id, scheduled_time, state, attempt)
VALUES (:id, :due, 'PENDING', 1)
ON CONFLICT (job_id, scheduled_time) DO NOTHING;   -- the idempotency key
INSERT INTO outbox (run_id, queue) VALUES (:run, :queue);
COMMIT;
🎤
Say it out loud
“I would layer three defences. First, each shard has one owner, chosen with a lease in etcd or ZooKeeper, which keeps contention low and scales by shard. Second, firing a job is one transaction: a compare-and-set on the job's version and next run time, plus an insert into runs with a unique key on job and scheduled time. Only one scheduler can win that. Third, the lease has a growing fencing token, so a scheduler that froze and woke up late is rejected. Last, the run carries that key to the target, so a repeat does nothing. A dead owner loses its lease and another loads the shard.”
5.3

Running jobs reliably: leases, heartbeats and retries

The problem: A worker takes a run and then crashes, hangs, or is cut off by the network. We cannot tell a slow worker from a dead one, and a worker that looks dead may still be running. Failures also come in waves: a broken target makes every run fail, and retrying them all at once makes it worse.

OptionHow it worksGoodBad
Fire and forgetSend the run to the target and mark it done.Simplest.A lost call or a crashed worker means a lost job, and nobody knows.
Ack when startedMark the run done when the worker picks it up.Fast to implement.A crash after the ack loses the run. This is at-most-once.
Lease + heartbeat, ack when finishedThe worker leases the run for a short time and renews it while it works. Mark it done only when the target answers. If the lease expires, put the run back.No lost runs. Quick detection of a dead worker (a missed heartbeat or two).At least once: a worker that only looked dead may still finish, so the run can happen twice. Needs idempotent targets.
Lease + heartbeat + fencing tokenAs above, but each lease carries a growing token. Complete, fail and heartbeat calls with an old token are ignored.A zombie worker cannot overwrite the new owner's result.A few more fields, and the target must still be idempotent for its own side effects.
Pick
A lease with heartbeats and a fencing token, retries with backoff and jitter, and a dead-letter queue

The only honest guarantee is at least once. A worker can do the work and die before reporting it, and from the outside that looks the same as dying before doing it. So we retry, and we make the retry safe by sending the same idempotency key (job id plus scheduled time) to the target. For long jobs the heartbeat extends the lease, so a 25-second job does not lose its lease at 10 seconds.

Retries follow the backoff rules: wait 5 seconds, then 20, then 80, with random jitter so that a thousand failed runs do not all retry at the same instant. After the last attempt, the run goes to the dead-letter queue and an alert fires. A "poison" run that always fails must not block the queue.

PolicyWhat it doesWhy
Forbid overlapSkip or delay a new run while the previous run of the same job is still running.Stops a slow job from piling up copies of itself.
Per-tenant concurrency limitEach tenant may have at most N runs in flight, and gets its own queue share.A noisy tenant cannot starve the others.
Priority queuesHigh, normal and low queues. Workers take from high first, with a share for low.Urgent jobs stay on time during a burst.
Timeout per runThe worker gives up after the job's timeout and reports a failure.A hung target cannot hold a worker forever.
🧠Play with it
The visualizer below lets you break the schedulers and the worker, switch the claim style, and turn the idempotency key and the heartbeat on and off. Watch whether the job ran once, twice or never.
🎤
Say it out loud
“A worker leases a run for a short time and renews it with heartbeats while it works. We only mark it done when the target answers. If the heartbeats stop, the lease expires and the run goes back on the queue with a higher fencing token, so a zombie worker cannot overwrite the new result. That gives us at least once, never exactly once, so we send an idempotency key made of the job id and the scheduled time. Failed runs retry with exponential backoff and jitter and then go to a dead-letter queue. We also forbid overlap for a job, and limit concurrency per tenant.”
5.4

Scaling out and running it day to day

The problem: The design must grow from 10 million to 100 million jobs, survive a lost zone, handle one huge tenant, and tell us when it is late. Moving shards between owners is exactly when double firing is most likely.

OptionHow it worksGoodBad
Fixed shards, assigned by handA static map of shard to scheduler.Simple.A dead scheduler means a dead shard until a human acts. Hard to rebalance.
Many small shards, assigned with leasesUse many more shards (for example 256) than schedulers. Each scheduler holds leases on a few shards and picks up more when others die.Automatic failover and balancing. A hot shard can move alone.A lease store to run, and shard moves need the fencing token to be safe.
Consistent hashing of jobs onto schedulersHash job id onto a ring of schedulers.Adding a scheduler moves only a part of the jobs.Ownership is implicit, so overlap is harder to prevent without leases on top.
Time-bucket partitioningPartition by the due minute instead of by job.Easy to find everything due now. Easy to drop old data.A burst at :00 lands on one partition. Hot partition by design.
Pick
Many small shards (for example 256) owned through leases, with hash of job id as the shard key and time-based history tables

More shards than schedulers makes balancing and failover easy: when a scheduler dies, its shards' leases expire and the others take them, and a hot shard can be moved on its own. Because ownership changes come with a bigger fencing token, a slow old owner cannot fire twice. Run history is partitioned by day, so deleting 30-day-old data is a quick drop of a partition, not a huge delete.

Watch scheduling lag (actual start minus due time) as the main health number, with queue depth, failure rate and the age of the oldest PENDING run. For multi-region, keep each shard active in one region only (active-passive per shard) so the same job is not fired from two regions. Protect HTTP targets: block internal addresses (SSRF), sign callbacks, and keep target secrets out of job payloads.

If the interviewer asks to scale 10 timesChange
100M jobsMore shards (the data is 100 GB), same design. The loader reads still hit an index, so cost stays flat.
10,000 runs a second at peakMore workers, more queue partitions, and a database per shard group sized for 50,000 writes a second per 16 shards.
One tenant is 50% of trafficIts own queue and worker pool, and a concurrency limit, so it cannot delay others.
A whole zone is lostLeases expire, other schedulers take the shards, runs are about one lease length late, nothing is lost.
🎤
Say it out loud
“To scale and operate it, I would use many more shards than schedulers, say 256, each owned through a lease. When a scheduler dies, its leases expire and others pick up its shards, and the fencing token stops a slow old owner from firing. History is partitioned by day so cleanup is a partition drop. The number I watch is scheduling lag, actual start minus due time, plus queue depth and the age of the oldest pending run. For multi-region I would keep each shard active in one region only, so a job never fires from two places. And I would block internal addresses for HTTP targets.”
VisualizerTwo schedulers, one due job: who runs it, and how many times?Pick how the schedulers claim the job, then break something: freeze one, kill one, kill the worker, or run a long job. Turn the idempotency key and the heartbeat on and off and watch the outcome change.
How do the schedulers claim job J?
What goes wrong?
Idempotency key on the target
Heartbeat renews the lease
Timeline for job J (due at second 0). Times are seconds after it was due.
  1. t+0 sS1reads job J: state PENDING.
  2. t+0 sS2reads job J: state PENDING.
  3. t+0 sS1dispatches the run.
  4. t+0 sS2dispatches the run.
  5. t+4 sTargetapplies the job's effect.
  6. t+4 sTargetapplies the job's effect again (run number 2).
Outcome
Ran twice
what the target saw
Dispatches
2
times a run was sent
Times it ran
2
effects applied
Duplicates stopped
0
by key or token
Started late by
0 s
first run that counted
Ran twice. Both schedulers read PENDING before either changed it, so both dispatched. Nothing stopped the duplicate.

A simplified model with fixed numbers (a normal job takes 4 s, the long job 25 s, a crashing worker dies at second 3, heartbeats every 2 s) and no random numbers. The heartbeat only matters when the claim is a lease. A frozen or dead process cannot send heartbeats.

Step 6Scale, bottlenecks and failuresabout 7 min

🤔
Pause. Try it yourself first
Run the day. What happens at 09:00:00 when 100,000 jobs are due? What if a whole zone goes down? What if the scheduler is down for 20 minutes? What if one tenant creates a million jobs?

What breaks first, and the fix

BottleneckFix
The top-of-the-hour burst (100,000 runs in seconds)Jitter for jobs that allow it, priority queues, autoscaled workers, and a per-tenant concurrency limit. Alert on scheduling lag, not on CPU.
Database writes (about 5 per run)Shard by job id, batch the outbox publisher, and keep history writes off the hot tables. Reads for due jobs use the index.
A shard that is much busier than the restMany small shards, so a hot one can move alone. Split a large tenant across shards by adding its tenant id to the shard key.
The loader scan on a very large shardAn index on (status, next_run_time) with a LIMIT, and a 30-second window. Reads stay proportional to the due rows, not the table size.
Lease store load (etcd or ZooKeeper)Leases are per shard, not per job, so only hundreds of keys. Keep heartbeat intervals reasonable and never put job data in the lease store.
Run history growth (360 GB for 30 days)Partition by day, copy to cheap storage, and drop old partitions. Keep only a summary after 30 days.
Many workers polling the queueLong polling and batch leasing. Autoscale on queue depth and the age of the oldest message.

What if a part fails?

FailureHow the design copes
A shard owner diesIts lease expires (about 10 seconds), another scheduler takes the shard with a higher token, loads its window, and fires anything due. Runs are late by about one lease length.
A scheduler pauses, then wakes upIts token is stale, so the claim and the writes are rejected. It must re-check its lease before acting after any long pause.
A worker dies mid-runHeartbeats stop, the lease expires, the run is re-queued with a higher token. The target sees the same idempotency key and skips a repeat.
The scheduler is down for 20 minutesOn return it finds jobs whose time has passed and applies each job's misfire policy: fire once, fire all missed (with a limit), or skip. It drains oldest first and prefers high priority.
The target is downRetries with backoff and jitter, a circuit breaker per target so we stop hammering it, then the dead-letter queue and an alert to the owner.
The lease store is downOwners keep working until their leases expire, and then stop firing (safe). New owners cannot be chosen. Alert at once. We prefer late over double.
What to monitor
  • •Scheduling lag (actual start minus due time), at p50, p99 and max, per shard
  • •Age of the oldest PENDING run, and queue depth by priority
  • •Run outcomes: success, retry, failed and dead-lettered, by tenant and target
  • •Runs stuck in LEASED or RUNNING longer than their timeout
  • •Lease changes per shard (a shard flapping between owners is a warning sign)
  • •Duplicate dispatches caught by the unique key (a rising number means a problem upstream)
Security and abuse
  • •Tenant isolation on every read and write, and quotas on the number of jobs and the run rate
  • •Block private and internal addresses for HTTP targets (SSRF), and limit redirects
  • •Sign callbacks so a target can tell a real run from a forged one
  • •Keep credentials for targets in a secrets store, never in the job payload or in logs
  • •Rate-limit job creation, and cap the cron frequency (for example no faster than once a minute)

Step 7Wrap upabout 3 min

A sharded jobs-and-runs database, a timer owner per shard chosen with a lease and a fencing token, an in-memory heap of the next 30 seconds, a compare-and-set claim that creates a run through an outbox, priority queues, and workers that lease runs with heartbeats. Delivery is at least once with an idempotency key on every run. We spread the top-of-the-hour burst, apply a misfire policy after outages, and watch scheduling lag.

Trade-offs you made

DecisionWhat we gainWhat it costs
At-least-once deliveryNo lost jobs, even when workers and schedulers fail.A job can run twice, so targets must be idempotent.
Database as the source of truth, with an in-memory windowPrecise timing and easy recovery after a restart.Two places to keep in step, and a re-check before every fire.
Leases with fencing tokensSafe failover and protection from paused processes.A lease store to run, and a token check on every write.
Short leasesFast recovery when something dies.More false expiries on a slow worker, so heartbeats are needed.
Jitter on start timesA flat load instead of a spike at :00.Jobs start a few seconds off their nominal time.
Prefer late over doubleSafe behaviour when coordination breaks.Some runs are delayed during a failure.
If we had more time, we would…
  • •Workflows: dependencies between jobs, which is what orchestrators such as Airflow add.
  • •Multi-region: each shard active in one region, with a tested failover and a fenced hand-over.
  • •A simulated clock and failure injection so we can test lateness, pauses and overlaps.
  • •Per-tenant dashboards, and a dry-run that shows the next 10 run times for a cron expression.
  • •Adaptive concurrency that slows down when a target starts returning errors.
🎤
Say it out loud
“To recap: jobs and runs in a sharded database, one timer owner per shard through a lease with a fencing token, an in-memory heap of the next 30 seconds, and a claim that is a single compare-and-set transaction that creates the run and an outbox row. Workers lease runs with heartbeats, and we promise at least once with an idempotency key for the target. We prefer late over double, spread the top-of-the-hour burst, and watch scheduling lag. Given more time I would add workflows, multi-region and failure injection.”

Q&ACross-questions (22)

💡How to practise
Cover the answer. Say yours out loud in 30 to 60 seconds. Then open the model answer, the follow-up, and the weak answer to see what to avoid. Use Open all at the top for a quick read.
Warm-upProbingCurveballWarm-up = basics. Probing = tests depth. Curveball = changes the problem.

Finding and firing jobs

Show that you do not scan the table, and that you know where timing error comes from.

Double fire and lost jobs

The core of the question. Walk through each failure and say what ends up happening.

Workers, retries and fairness

How a run gets done, how failures are handled, and how one customer is kept from hurting the others.

Scale, outages and curveballs

Where interviewers push once the core is solid.

What ifIf the interviewer changes the problem

A change in requirements is a test of whether you understand why your design looks the way it does.

New requirementWhat changes in the design
Jobs must run exactly at the second, with no jitterA dedicated priority tier with its own queue and reserved workers, pre-warmed before the hour, and a shorter loader window. We say the cost clearly: reserved capacity.
Jobs depend on each other (A then B then C)Add a workflow layer: a DAG definition, a run per node, and dependencies checked when a run finishes. This is where an orchestrator such as Airflow comes in.
At most once instead of at least onceAck when the worker starts the run, never re-queue after a lease expiry, and accept that a crash loses a run. Fine for non-critical work, with an alert on stuck runs.
Runs can take hoursLong leases with heartbeats, progress checkpoints so a retry resumes rather than restarts, and a tighter policy against overlap.
Sub-second timers (one-shot delays, such as a payment timeout)A delay queue or a timing wheel in memory per node, backed by the database for durability. Cron features are not needed.
Multi-region active-activeShard ownership still lives in one region at a time. Add per-region job placement, and a fenced failover so a job never fires from two regions.
Strict per-tenant priority and billingPer-tenant queues, weighted fair scheduling, usage metering on every run, and quotas that reject new jobs before they hurt others.
Customers want to see the next 10 run timesCompute them from the cron expression and time zone on demand, with the same library the scheduler uses, so what we show is what will run.

ScoreHow answers are judged

AreaWeakGoodGreat
RequirementsStarts drawing at once. Never asks about missed runs, precision or repeats.Asks about one-off or recurring, precision and at least once, and writes the scope down.Also settles misfire policy, overlap, time zones and tenant fairness, and says what is out of scope.
EstimationNo numbers, or only a total.Gets runs per second and the database size, and sees that the average is small.Finds the :00 burst as the real constraint, shows why a full scan fails, and ties numbers to shards and workers.
DesignA cron daemon on one server, or a thread per job.Sharded database, an index on due time, a queue and workers.Look-ahead window with a heap, shard ownership with leases, an outbox, and a clear path from due to done.
CorrectnessSays exactly once, or never mentions two schedulers.At least once with idempotency, and a lease with heartbeats.Walks through paused and dead schedulers and workers, uses fencing tokens and the unique run key, and shows no lost job and no double effect.
Trade-offsPresents one solution as obviously right.Compares polling with an in-memory heap and gives a reason.Prefers late over double on purpose, states the cost of every choice, and offers what to do if the numbers change.
OperationsNo monitoring or failure plan.Mentions retries, a dead-letter queue and basic metrics.Watches scheduling lag, plans catch-up after an outage, limits noisy tenants, and covers security of HTTP targets.

AvoidCommon mistakes on this question

MistakeDo this instead
A single cron server or one timer thread per jobShard the jobs, index the due time, and keep a small window in memory.
Scanning the whole jobs table every secondUse an index on (status, next_run_time) and read only the next 30 seconds.
Promising exactly oncePromise at least once with an idempotency key, and explain the crash window honestly.
A claim with no expiryUse a lease with an expiry and heartbeats, so a dead owner is replaced.
Trusting a lease check alone after a pauseAdd a fencing token that the database checks, because the pause can happen right after the check.
Ignoring the top-of-the-hour spikeAdd jitter, priority queues, autoscaling and per-tenant limits, and measure scheduling lag.
No plan for missed runsGive each job a misfire policy and a rate-limited catch-up path.
Computing the next run from when the job finishedCompute it from the scheduled time, in UTC, so the schedule does not drift.

Revise60-second revision sheet

  • ✔Scale: 40M runs a day is about 460 a second, but the :00 burst can be 10,000 a second.
  • ✔Find due jobs: index on (status, next_run_time), a loader for the next 30 seconds, an in-memory heap.
  • ✔Fire a job: one transaction: compare-and-set the version, insert the run (unique on job and scheduled time), insert the outbox row.
  • ✔Who fires: one owner per shard through a lease with a fencing token. Many small shards.
  • ✔Workers: lease a run, send heartbeats, report with the token. No heartbeat means the run goes back on the queue.
  • ✔Delivery: at least once. Idempotency key = job id + scheduled time.
  • ✔Failures: retry with backoff and jitter, then a dead-letter queue and an alert.
  • ✔After an outage: misfire policy per job: fire once, fire all (capped), or skip.
  • ✔Operate it: watch scheduling lag, queue depth and the oldest pending run. Prefer late over double.
  • ✔One line: “Index the due time, own the shard with a lease, claim with compare-and-set, and make a repeat harmless.”

Read these topics next

Task Queues, Workers and Scheduled Jobs→

The worker side of this design, and how scheduled jobs fit in.

Message Queues→

How due runs travel to workers.

Dead Letter Queues→

Where runs go after their last failed attempt.

Retries with Backoff→

The retry timing and jitter used for failed runs.

Idempotent Consumer and Inbox Pattern→

How a repeated run is made harmless.

Leader Election→

How one owner is chosen for each shard.

Fencing Tokens→

What stops a paused scheduler from acting late.

Heap and Priority Queue→

The in-memory structure that holds the next 30 seconds.

← Previous
Design a Leaderboard
Next →
Design a Social Media Platform (Facebook)