Run jobs at the right time, exactly when needed, even when machines fail.
“Design a distributed job scheduler.”
It is short on purpose. Your first job is to make it specific.
| What they check | Why 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 efficiently | 10 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 job | This 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 semantics | Exactly once is not on offer. Say at least once, then show leases, retries and idempotency keys that make the effect happen once. |
| Operating it | Top-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. |
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.
| Step | Minutes | What to get done |
|---|---|---|
| 1. Clarify | 4 | One-off or recurring, how precise, at least once or at most once, what a job does, and what a missed run means. |
| 2. Estimate | 3 | Runs per second, the :00 burst, storage for jobs and history, and why a full scan fails. |
| 3. API and data | 5 | Create a job, the jobs and runs tables, the worker lease calls. |
| 4. High-level design | 8 | API, sharded database, timer tier, queue, workers. Follow one run from due to done. |
| 5. Deep dives | 15 | Finding due jobs, then no double fire and no lost job, then worker reliability, then scale and operations. |
| 6. Scale and failures | 7 | The :00 spike, a dead scheduler, a dead worker, an outage and catch-up. |
| 7. Wrap up | 3 | Recap, the at-least-once trade-off, and what you would build next. |
| Ask | Why you ask it | Typical answer | How 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. |
| Assumption | Value |
|---|---|
| Registered jobs | 10 million |
| Runs per day | 40 million |
| Peak rate (busy hours) | about 1,000 runs per second |
| Top-of-the-hour burst | 10,000 runs per second for about 10 seconds |
| Job definition size | about 1 KB (schedule, target, payload, retry policy) |
| Run record size | about 300 bytes |
| Run history kept | 30 days |
| Average run length | 5 seconds (an HTTP call) |
| One worker | 100 concurrent runs |
| Database shards | 16 (by hash of job id) |
| Look-ahead window | 30 seconds |
| What | Maths | Result |
|---|---|---|
| Average runs per second | 40,000,000 ÷ 86,400 | about 460 per second |
| Peak versus average | 1,000 ÷ 460 | about 2 times |
| Runs in one :00 burst | 10,000 per second × 10 seconds | 100,000 runs |
| Job definitions on disk | 10,000,000 × 1 KB | 10 GB (30 GB with 3 copies) |
| Run history per day | 40,000,000 × 300 bytes | 12 GB per day |
| Run history for 30 days | 12 GB × 30 | 360 GB (about 1.1 TB with 3 copies) |
| A naive scan every second (no index) | 10,000,000 rows × about 100 bytes | about 1 GB read per second, to find 460 rows |
| Due jobs per shard at peak and in a burst | 1,000 ÷ 16 and 10,000 ÷ 16 | about 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 × 5 | 5,000 per second at peak, 50,000 in a burst (about 3,100 per shard) |
| Concurrent runs at peak | 1,000 per second × 5 seconds | 5,000 runs, so 5,000 ÷ 100 = 50 workers |
| Draining a :00 burst on 50 workers | 100,000 runs ÷ 1,000 runs per second | about 100 seconds for the last run (too late) |
| Jobs held in memory per 30-second window | 460 × 30 (average) and 100,000 × 200 bytes (burst) | about 14,000 jobs; 20 MB in a burst |
| Method | Path | Request | Response | Notes |
|---|---|---|---|---|
| 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} | none | 200 { 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} | none | 204 | Soft 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}/runs | none | 200 { 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. |
| jobs table (sharded by hash of job id) | Type | Why it is there |
|---|---|---|
| job_id, tenant_id | id | The key, and the owner for quotas and access. |
| schedule (cron, timezone) or run_at | text, timestamp | What the user asked for. |
| next_run_time | timestamp | When the next run is due. Indexed, and the main field the timer reads. |
| status | enum | ACTIVE, PAUSED or DELETED. The timer only reads ACTIVE. |
| version | int | Bumped on every change. Used for compare-and-set. |
| target, payload, retry policy, timeout, misfire policy, priority | json | How to run it and what to do when it fails or is missed. |
| runs table (same shard as its job) | Type | Why it is there |
|---|---|---|
| run_id | id | Unique per run. Includes the attempt number. |
| job_id, scheduled_time | id, timestamp | Together they are the idempotency key. A unique index on them stops a second run row for the same slot. |
| state | enum | PENDING, LEASED, RUNNING, SUCCEEDED, FAILED or DEAD. |
| attempt | int | 1 for the first try, higher for retries. |
| lease_expires_at, worker_id, token | timestamp, id, int | Who owns the run now and until when. The token grows each time a new owner takes over. |
-- 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);
| Component | What it does |
|---|---|
| API service | Validates 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 queues | Receive due runs. Separate queues for priority and for large tenants, so one burst cannot block everything. |
| Worker fleet | Leases a run, calls the target, sends heartbeats, then reports success or failure. Autoscaled on queue depth and lag. |
| Dead-letter queue and history | Runs that keep failing go to the DLQ for a human. Finished runs are copied to cheap history storage. |
| Metrics and alerts | The key number is scheduling lag (actual start minus due time). Also queue depth, failure rate and stuck runs. |
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.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Poll the database with an index | Every 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 heap | Every 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 set | Push (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 wheels | A 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. |
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.
| Misfire policy (outage or lag) | What it does | Good for |
|---|---|---|
| Fire once now | Run one catch-up run, then continue on schedule. | Most jobs. The default. |
| Fire all missed | Run every missed slot, in order, with a limit. | Per-slot work such as hourly billing. |
| Skip | Drop the missed runs and wait for the next slot. | Refresh jobs where only the latest matters. |
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.
| Option | How it works | Good | Bad |
|---|---|---|---|
| One leader fires everything | Elect 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 token | Each 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 database | Any 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 downstream | Fire 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. |
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 dies | State left behind | Recovery |
|---|---|---|
| Before the claim transaction | Job still due, nothing changed | The next owner loads it and fires it. Late by about a lease length. |
| After the claim, before the queue publish | Run row PENDING, no message | The outbox publisher sends it, or a sweeper republishes old PENDING runs. Same run key, so no duplicate row. |
| After the publish | Message on the queue | A worker leases it as normal. |
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;
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.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Fire and forget | Send 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 started | Mark 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 finished | The 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 token | As 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. |
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.
| Policy | What it does | Why |
|---|---|---|
| Forbid overlap | Skip 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 limit | Each tenant may have at most N runs in flight, and gets its own queue share. | A noisy tenant cannot starve the others. |
| Priority queues | High, normal and low queues. Workers take from high first, with a share for low. | Urgent jobs stay on time during a burst. |
| Timeout per run | The worker gives up after the job's timeout and reports a failure. | A hung target cannot hold a worker forever. |
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.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Fixed shards, assigned by hand | A 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 leases | Use 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 schedulers | Hash 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 partitioning | Partition 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. |
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 times | Change |
|---|---|
| 100M jobs | More 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 peak | More 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 traffic | Its own queue and worker pool, and a concurrency limit, so it cannot delay others. |
| A whole zone is lost | Leases expire, other schedulers take the shards, runs are about one lease length late, nothing is lost. |
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.
| Bottleneck | Fix |
|---|---|
| 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 rest | Many 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 shard | An 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 queue | Long polling and batch leasing. Autoscale on queue depth and the age of the oldest message. |
| Failure | How the design copes |
|---|---|
| A shard owner dies | Its 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 up | Its 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-run | Heartbeats 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 minutes | On 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 down | Retries 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 down | Owners keep working until their leases expire, and then stop firing (safe). New owners cannot be chosen. Alert at once. We prefer late over double. |
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.
| Decision | What we gain | What it costs |
|---|---|---|
| At-least-once delivery | No 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 window | Precise timing and easy recovery after a restart. | Two places to keep in step, and a re-check before every fire. |
| Leases with fencing tokens | Safe failover and protection from paused processes. | A lease store to run, and a token check on every write. |
| Short leases | Fast recovery when something dies. | More false expiries on a slow worker, so heartbeats are needed. |
| Jitter on start times | A flat load instead of a spike at :00. | Jobs start a few seconds off their nominal time. |
| Prefer late over double | Safe behaviour when coordination breaks. | Some runs are delayed during a failure. |
Show that you do not scan the table, and that you know where timing error comes from.
The core of the question. Walk through each failure and say what ends up happening.
How a run gets done, how failures are handled, and how one customer is kept from hurting the others.
Where interviewers push once the core is solid.
A change in requirements is a test of whether you understand why your design looks the way it does.
| New requirement | What changes in the design |
|---|---|
| Jobs must run exactly at the second, with no jitter | A 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 once | Ack 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 hours | Long 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-active | Shard 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 billing | Per-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 times | Compute 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. |
| Area | Weak | Good | Great |
|---|---|---|---|
| Requirements | Starts 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. |
| Estimation | No 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. |
| Design | A 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. |
| Correctness | Says 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-offs | Presents 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. |
| Operations | No 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. |
| Mistake | Do this instead |
|---|---|
| A single cron server or one timer thread per job | Shard the jobs, index the due time, and keep a small window in memory. |
| Scanning the whole jobs table every second | Use an index on (status, next_run_time) and read only the next 30 seconds. |
| Promising exactly once | Promise at least once with an idempotency key, and explain the crash window honestly. |
| A claim with no expiry | Use a lease with an expiry and heartbeats, so a dead owner is replaced. |
| Trusting a lease check alone after a pause | Add a fencing token that the database checks, because the pause can happen right after the check. |
| Ignoring the top-of-the-hour spike | Add jitter, priority queues, autoscaling and per-tenant limits, and measure scheduling lag. |
| No plan for missed runs | Give each job a misfire policy and a rate-limited catch-up path. |
| Computing the next run from when the job finished | Compute it from the scheduled time, in UTC, so the schedule does not drift. |
The worker side of this design, and how scheduled jobs fit in.
How due runs travel to workers.
Where runs go after their last failed attempt.
The retry timing and jitter used for failed runs.
How a repeated run is made harmless.
How one owner is chosen for each shard.
What stops a paused scheduler from acting late.
The in-memory structure that holds the next 30 seconds.