What it is
A distributed job scheduler runs work at a given time or on a recurring schedule: "send invoices every day at 09:00", "retry this webhook in five minutes", "expire this trial in 14 days". Owners register jobs through an API; the system guarantees each run happens, close to its time, even when machines fail.
Why it exists
Plain cron on one machine is a single point of failure and cannot grow beyond that machine. Once jobs number in the millions, come from many teams, or must survive restarts, you need durable storage for schedules, a way to decide what is due without scanning everything, and a worker pool that scales separately from the clock.
How it works
Requirements. Functional: create, update, pause and delete jobs (one-off and recurring); run each due job; expose status and history. Non-functional: every due run executes at least once; runs start within seconds of their time (not exactly on the millisecond); no single machine failure loses or blocks jobs; dispatch capacity grows with the number of jobs.
Estimates (illustrative). 50 million schedules producing 10 million runs per day is about 115 runs per second on average. Storage is small: a few hundred bytes per schedule row is on the order of tens of gigabytes, plus run history. The average is not what sizes the system: people write 0 * * * * and 0 9 * * *, so a large share of runs fall on the first second of the hour. If 20% of daily runs fall on the 24 hourly boundaries, each top of the hour brings about 80 000 runs at once.
Schedule store. Each job is a row with its definition and a next_run_at. An index on next_run_at makes "what is due now?" a range scan over due rows only. Sharding by job id spreads the rows; each scheduler shard owns a set of partitions.
Scheduler. A loop that, every second or so, claims due rows and advances next_run_at to the next occurrence in the same transaction (in PostgreSQL, SELECT … FOR UPDATE SKIP LOCKED lets several pollers claim disjoint rows). It then enqueues one message per run. It does no work itself, so it stays small.
Queue and workers. Workers take jobs from the queue, run them and acknowledge afterwards. Unacknowledged jobs become visible again after the visibility timeout (SQS's term; other brokers use leases or ack deadlines). This gives at-least-once execution. Jobs are made idempotent with a run key such as job_id + scheduled_time, stored with the job's side effects or checked before them.
Retries and DLQ. A failed attempt is retried after a delay (the visibility timeout, or better, exponential backoff with jitter). After a fixed number of attempts the job goes to a dead letter queue for inspection and replay.
One active scheduler. Two schedulers dispatching the same partition would duplicate every run. The active one holds a lease in a coordination service (etcd, ZooKeeper, Consul, or a database row with an expiry) and renews it well before it expires. A standby takes over when the lease lapses. Each new lease comes with a higher fencing token; the store or queue rejects writes carrying an older token, so a leader that was paused (GC, VM migration) and wakes up after losing its lease cannot dispatch.
Jitter. Jobs that tolerate it get a random offset added to each run (seconds to minutes), which turns the hourly spike into a gentle slope. Jobs that need exact timing opt out and get reserved capacity.
When to use it
Recurring and delayed work across many tenants or teams: billing runs, reminders, report generation, data pipelines, retries with long delays, TTL expiry. Anywhere cron on a single box has become a risk.
When not to
- A handful of jobs on one service: a managed cron (Kubernetes CronJob, cloud schedulers) is simpler.
- Millions of short timers per second (session timeouts, game ticks): an in-memory hierarchical timing wheel inside the service fits better than polling a store.
- Multi-step workflows with branches and compensation: use a workflow engine (Temporal, Step Functions) that includes scheduling.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Single leased scheduler per partition | Simple, no duplicate dispatch | Failover gap up to the lease length; one partition's dispatch rate is capped |
| Short lease | Faster failover | More renewals, more false failovers on brief network hiccups |
| At-least-once + idempotent jobs | Simple, robust | Every job must handle duplicates |
| Jitter by default | Flat load, smaller worker pool | Runs are seconds or minutes off their nominal time |
| Polling the store | Durable, easy to reason about | Latency of the polling interval; load on the store at scale |
Alternatives
- Broker-native delays: delayed messages in RabbitMQ, SQS delay queues (up to 15 minutes), Redis sorted sets keyed by run time. Good for one-off delays; recurring schedules still need a store.
- Workflow engines: Temporal, Airflow or Step Functions own both timing and execution, with history and retries built in.
- Timing wheels: in-memory buckets per tick, very cheap per timer, but you must persist and recover them yourself.
Failure modes
- Worker crash mid-job: the job reruns after the visibility timeout; non-idempotent side effects happen twice.
- Visibility timeout shorter than the slowest normal run: healthy jobs are redelivered while still running, causing duplicates.
- Thundering herd at round times: backlog, late runs and a spike on every system the jobs call.
- Split brain: two schedulers both think they lead and both dispatch. Leases plus fencing tokens prevent the effects.
- Poison jobs retried forever: cap attempts, use a DLQ, alert on its size.
- Catch-up storm: after a long outage the new leader dispatches hours of missed runs at once. Decide per job whether to run all missed occurrences, only the latest, or none (a "misfire policy").
In production
Alert on scheduling delay (actual start minus scheduled time), queue age of the oldest message and DLQ depth rather than CPU. Keep run history (start, end, attempt, outcome) for owners to debug their jobs. Rate-limit per tenant so one team's million jobs cannot starve others. Partition the job space so several leased schedulers share dispatch when one is not enough. Store times in UTC and handle daylight-saving transitions explicitly (a 02:30 local job may run zero or two times on transition days).
Common misconceptions
- "Exactly-once execution is achievable with the right queue." Delivery can be deduplicated; side effects in other systems cannot be made exactly-once by the queue. Idempotent jobs are the practical answer.
- "A standby scheduler means no gap." Failover takes at least until the lease expires; the store makes the gap recoverable, not zero.
- "The average rate sizes the worker pool." For schedulers, the peak at round times does.
- "A bigger queue fixes backlog." It only stores more of it; jobs still run late.
Interview angle
Start with requirements and the at-least-once guarantee, then draw store → scheduler → queue → workers. Interviewers probe: how the scheduler finds due jobs cheaply (index on next run time, partitioning), how you prevent two schedulers (lease, fencing), what happens when a worker dies (visibility timeout, idempotency), how you handle the top-of-hour spike (jitter, autoscaling, reserved capacity) and missed runs after an outage (misfire policy). Quoting the peak instead of the average ("80 000 runs in the first second of each hour") stands out.
Model assumptions
The simulation is a simplified model, not a benchmark. The active scheduler is modelled as a source that enqueues due jobs at a set rate (Poisson); it is not driven by real rows in a store. Each of three workers has 10 slots and a mean of 333 ms per job (lognormal, cv 0.4), about 30 jobs per second per worker. The queue's visibility timeout is 2 s and a job is dead-lettered after 3 deliveries; in this model a failed attempt keeps its worker slot reserved until its visibility timeout ends, which is why the retry step uses a quiet 15 jobs per second. Registration, polling the store and the lease handshake (renewals, expiry, fencing token) are scripted illustrations; the engine does not model databases being polled, leases or fencing. The jitter window is compressed to 10 simulated seconds. All numbers show behaviour and orders of magnitude only.