System design case study C18 · Leases · Cron

Design a Distributed Job Scheduler

Run millions of jobs at the right time, at least once, ideally exactly once, and know what happened to every one of them.

What you'll be able to explain
  • Store schedules and find due jobs efficiently
  • Dispatch with leases so crashed workers don't lose jobs
  • Make job execution idempotent
  • Support cron, delays, retries and dependencies
  • Scale the scheduler itself without double-firing

Scope

Functional

  • Submit one-off jobs (run at T or after delay) and recurring jobs (cron expressions).
  • Retries with backoff; timeouts; cancellation; execution history and logs.
  • Optional dependencies (job B after job A succeeds).

Non-functional

  • Jobs start within ~1 s of their scheduled time at p99.
  • No job is lost; duplicates are rare and handled by idempotency.
  • 10M jobs/day, peaks of 50k jobs due in the same second (midnight crons).

Data model

Table Key Notes
job_definitions job_id owner, payload, cron, timezone, retry policy, timeout
job_runs run_id (job_id + scheduled_time) status, attempt, worker, lease_expires_at, result
due index (bucket, next_run_at) time-sorted, partitioned into buckets

run_id = job_id + scheduled_time is a natural idempotency key: the same scheduled occurrence can't be created twice.

The architecture

CLIENTClientssubmit / cancelSERVICEScheduler APIDATABASEJobs DBdue index by bucketWORKERPollersown bucketsQUEUE / LOGReady queueby priorityWORKERWorkerslease + heartbeatOBJECT STORERun history+ logsclaim due runsheartbeat / complete
Scheduler: pollers claim due runs, push them to a queue; workers execute under leases.

The 30-second summary

Say it in the interview

"Job runs are keyed by job ID plus scheduled time, which makes creation idempotent. The due index is split into buckets owned by pollers via leases; they claim due rows with SKIP LOCKED, enqueue them and insert the next cron occurrence atomically. Workers execute under heartbeated leases; expired leases are re-queued, so execution is at-least-once and jobs must be idempotent. Jitter, prefetching and per-tenant fairness handle midnight spikes."

Follow-up questions the interviewer may ask

  1. How do you guarantee a job isn't run twice?
  2. How do you handle millions of jobs due at the same minute?
  3. What about jobs that depend on other jobs?
  4. How do users see what happened?

Model answers to each of these are in the book.