Course contents

17. Real-World System Design Lesson 6 of 20

Job Scheduler

Design a distributed job scheduler: schedule store, leased scheduler, queue and workers, at-least-once runs, retries and DLQ, and jitter for hourly spikes.

25 minAdvanced9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • The scheduler only decides what is due; a queue and a worker pool execute the jobs.
  • The schedule store is the source of truth, indexed by next run time, so a scheduler crash delays jobs but loses none.
  • Acknowledge after the work: execution is at-least-once, so jobs must be idempotent.
  • Cap retries and park permanent failures in a dead letter queue.
  • Schedules cluster at round times; jitter flattens the spike.
  • One leader at a time via a lease; fencing tokens stop a stale leader.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

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.

The lesson as textEvery step of the simulation, written out.
  1. 1. What the scheduler must do

    Teams register jobs through an API: “run send-invoices every day at 09:00”, “retry this webhook in 5 minutes”. Each job is a row in the schedule store with its next run time. Watch one registration travel to the store and back.

    Requirements: every due job runs at least once, close to its time (seconds late is fine, hours is not); jobs survive crashes; the system scales with the number of jobs. Illustrative estimate: 50 million schedules producing 10 million runs a day is only about 115 runs per second on average. The average is not the problem. Humans write 0 9 * * *, so runs pile up at round times.

    Scene: A job owner registers a job through the Jobs API, which stores it in the Schedule Store with its next run time and confirms. Scripted illustration.

    Key idea: For schedulers the average rate is easy; the peaks at round times and the guarantee of running every job are the design problem.

  2. 2. The scheduler only finds due jobs

    A scheduler process does not run jobs itself. Every second or so it asks the store for jobs whose next_run_at has passed, claims them, and moves next_run_at forward to the next occurrence, in one transaction.

    An index on next_run_at keeps that query cheap however many jobs exist. Claiming and advancing in the same transaction (for example SELECT … FOR UPDATE SKIP LOCKED) means a job is handed out once per run even if the scheduler retries. This step is a scripted illustration: the engine does not model the store being polled.

    Scene: Scheduler A polls the Schedule Store once a second: it claims the due jobs, then advances their next run time. Scripted illustration.

    Key idea: Separate deciding *when* (the scheduler) from doing the work (workers). The scheduler’s query is index-driven and transactional.

  3. 3. A queue and workers execute the jobs

    The scheduler now enqueues each due job on a job queue, and a pool of workers takes jobs off it and runs them. Here the scheduler dispatches about 40 jobs per second; three workers can run about 90 per second together.

    The workers sit around 45% busy and the queue stays nearly empty. The queue is what lets the scheduler stay small and fast: it only decides what is due, and execution capacity is scaled separately by adding workers.

    Scene: Scheduler A enqueues about 40 jobs per second on the Job Queue; Workers 1 to 3 take them off and run them. Workers are about 45% busy and the queue stays nearly empty.

    Key idea: The queue decouples dispatching from executing: a slow job never delays the scheduler, and workers scale independently.

  4. 4. A worker dies mid-job

    One second in, Worker 1 crashes while running jobs. The jobs are not lost: a worker acknowledges a job only after finishing it, and until then the queue merely hides it. After the 2-second visibility timeout the queue delivers those jobs again and Workers 2 and 3 run them.

    That is at-least-once execution. If Worker 1 had already charged a card or sent an email before dying, the retry does it a second time. So jobs must be idempotent: key each run by job_id + scheduled_time and skip work that is already recorded as done.

    Scene: Worker 1 goes offline. Its unacknowledged jobs reappear on the queue after the visibility timeout and Workers 2 and 3 run them. No job is lost.

    Key idea: Acknowledge after the work, never before. The price is duplicates, so every job must be safe to run twice.

  5. 5. Failing jobs: retry, then park them

    Worker 1 is back, and it is a quiet hour: 15 jobs per second. Now a downstream API the jobs call becomes flaky: in this run 35% of job attempts fail. A failed job is not acknowledged, so it comes back after the visibility timeout, which doubles as the retry delay.

    Most jobs succeed on the second or third try. A few fail three times in a row and the queue moves them to a dead letter queue instead of retrying forever. Somebody (or an alert) looks at the DLQ, fixes the cause, and replays them. Without the cap, permanently broken jobs would circulate and steal capacity from healthy ones.

    Scene: At 15 jobs per second, about a third of job attempts fail. Failed jobs come back after the visibility timeout and are retried; jobs that fail three times move to the dead letter queue.

    Key idea: Cap the attempts and park the rest in a DLQ: retries absorb transient errors, the DLQ isolates permanent ones.

  6. 6. Everyone picked 09:00

    The downstream API is healthy again. One second in, the clock hits the top of the hour and every 0 * * * * job becomes due at once: for one second the scheduler dispatches 340 jobs per second instead of 40, a thundering herd.

    The workers can only run about 90 per second, so roughly 250 jobs pile up in the queue. Nothing fails, but the backlog takes several seconds to drain and the last jobs of the burst start seconds late. Scaled up to real numbers, the same shape makes jobs minutes late and hammers whatever the jobs call, all at the same instant.

    Scene: For one second the scheduler dispatches 340 jobs per second. The queue backlog jumps to about 250 jobs, all workers are fully busy, and the backlog drains over the following seconds.

    Key idea: Schedules cluster at round times. Capacity sized for the average turns every top of the hour into a backlog.

  7. 7. Spread the herd with jitter

    Most “hourly” jobs do not care whether they run at 09:00:00 or 09:00:07. The scheduler adds a random jitter to each run of those jobs (here 0–10 seconds of simulated time; in production often minutes), so the same 300 extra jobs arrive over ten seconds instead of one.

    The dispatch rate peaks around 70 per second, below what the workers can do. The queue stays nearly empty and no job waits more than a moment. Jobs that really need the exact second opt out of jitter and get reserved capacity.

    Scene: The same burst of jobs is spread over ten seconds. The dispatch rate peaks around 70 per second, the queue stays nearly empty and workers stay below full load.

    Key idea: Jitter trades a little timing precision for a flat load curve. Make it the default; let the few precise jobs opt out.

  8. 8. One scheduler, elected and fenced

    Two schedulers dispatching the same jobs would run everything twice, so only one may be active. Scheduler A holds a lease in a coordination service (etcd, ZooKeeper or a database row) and renews it every 500 ms; Scheduler B waits.

    One second in, Scheduler A crashes: no jobs are dispatched and the workers go idle. Its lease expires after 2 s; B acquires it with a higher fencing token, re-runs the due-jobs query and catches up the jobs that became due during the gap (a burst of 120 per second for one second), then continues at 40. Nothing is lost because the store, not the scheduler’s memory, is the source of truth. The lease handshake is a scripted illustration; the dispatch gap and catch-up are simulated.

    Scene: Scheduler A renews its lease, then crashes. Dispatching stops and the workers go idle. After the lease expires, Scheduler B acquires it with fencing token 8, queries the store and catches up the missed jobs, then dispatches normally.

    Key idea: A lease bounds the failover gap; the store makes the gap recoverable; the fencing token stops a paused old leader from dispatching after it lost the lease.

  9. 9. The design and its trade-offs

    Scheduler A restarts as the new standby: it dispatches nothing unless it wins the lease again. The finished design: a durable schedule store indexed by next run time, one leased scheduler that only decides what is due, a queue, a horizontally scaled worker pool, retries capped by a DLQ, and jitter by default.

    Trade-offs to discuss: one active scheduler is simple but caps dispatch rate (shard the job space across several leased schedulers when it is not enough); at-least-once plus idempotent jobs is cheaper than chasing exactly-once; jitter costs precision; and a hierarchical timing wheel in memory beats polling a database when you need millions of short timers.

    Scene: The complete scheduler: Jobs API and Schedule Store, Scheduler B as leader and Scheduler A as standby on the coordination service, the Job Queue, three workers and a dead letter queue.

    Key idea: Durable store + single leased dispatcher + queue + idempotent workers: each piece handles one failure, and jitter handles the clock itself.