Design a distributed job scheduler that runs millions of scheduled and delayed jobs

    A distributed job scheduler runs work at a time: cron-style recurring jobs, delayed one-off jobs (send this email in 3 days) and retries. The hard parts are finding due jobs cheaply among hundreds of millions, making sure a job runs even when nodes die, and making sure it does not run twice in harmful ways.

    Infrastructure, 9 components, about 45 min

    1. Scope

    In scope

    • • Create, update and cancel one-off and recurring jobs
    • • Run jobs at their due time within a few seconds
    • • Retries with backoff and a dead-letter queue
    • • Run history and status

    Out of scope

    • • Workflow DAG orchestration (mention only)
    • • Resource scheduling of containers on machines
    • • The job code itself

    2. Functional requirements

    Must have

    • • Schedule a job to run at a time or on a cron expression
    • • Execute each due run at least once, within seconds of its due time
    • • Retry failed runs with configurable backoff
    • • Query the status and history of a job

    Nice to have

    • • Priorities and per-tenant concurrency limits
    • • Time-zone-aware cron
    • • Pause and resume

    3. Non-functional requirements

    Scheduling accuracyp99 start delay < 5 s
    DurabilityAn accepted job is never lost
    Availability99.99% for scheduling; runs continue through node failures
    ExecutionAt-least-once; handlers idempotent

    4. Back-of-envelope estimation

    Assumptions

    • • 100M jobs stored (mostly delayed one-offs), 1 KB each
    • • 50M runs per day
    • • Top-of-the-hour cron spike: 20x average for a minute
    • • Run history kept 30 days, 500 bytes per attempt

    Derived numbers

    Average run rate~580/s— 50M / 86,400
    Peak run rate~12K/s— 20x at :00
    Job store~100 GB— 100M × 1 KB
    History~750 GB— 50M × 500 B × 30 days

    5. API design

    POST/jobs

    Body { type, payload, run_at | cron, tz, retry_policy, idempotency_key } → { job_id }

    DELETE/jobs/{id}

    Cancel future runs

    GET/jobs/{id}/runs

    Run history with status and attempt count

    6. High-level design

    What each box in the reference diagram is responsible for:

    Scheduler API — Validates and stores jobs; computes next_run_at in UTC from cron and time zone.
    Job Store — Durable store of jobs partitioned by time bucket of next_run_at, so a scheduler scans only the current bucket.
    Coordinator — etcd or ZooKeeper; assigns job-store partitions to scheduler nodes with leases.
    Scheduler Nodes — Each scans its partitions for due jobs every second, enqueues them and advances next_run_at in the same transaction.
    Ready Queue — Buffers due runs per job type so workers pull at their own pace.
    Worker Fleet — Leases a run, executes it with a fencing token, records the result and acknowledges.
    Dead-letter Queue — Runs that exhausted retries, for inspection and replay.
    Run History — Attempts, timings, errors and logs per run.

    7. Data model

    Job Store: jobs(job_id PK, bucket, next_run_at, cron, tz, type, payload, retry_policy, version)— Index (bucket, next_run_at); bucket = minute of next_run_at
    Runs: runs(run_id PK, job_id, scheduled_for, attempt, state, lease_until, fencing_token, error)— Unique (job_id, scheduled_for) prevents duplicate runs

    8. Deep dives

    Finding due jobs without scanning everything

    Store next_run_at and a coarse bucket (for example the minute). A scheduler queries WHERE bucket = current_minute AND next_run_at <= now, which touches only due jobs. Partition buckets across scheduler nodes by hash(job_id) mod P so each node owns P/N partitions. For very short delays a timing wheel in memory works too, but the durable store remains the source of truth.

    Exactly one scheduler per job

    Partitions are owned through leases in the coordinator. If a scheduler dies its lease expires and another node takes the partition. Enqueueing a run and advancing next_run_at happen in one transaction with a unique (job_id, scheduled_for) run row, so a takeover that re-scans the same window cannot create a second run.

    Leases and fencing tokens for workers

    A worker leases a run with lease_until and receives a monotonically increasing fencing token. If it stalls (long GC pause) past the lease, another worker may take the run. When the first worker wakes and tries to commit, the store rejects its stale token. This is why at-least-once is the honest guarantee: the job may start twice, but only one result commits; side effects outside the store need idempotency keys.

    The top-of-the-hour spike

    Humans write 0 * * * *, so many jobs fire at :00. Smooth it: let tenants opt into jitter, spread recurring jobs within a tolerance window, and size the ready queue and workers for the spike rather than the average.

    9. Bottlenecks

    • Hot time bucket at :00 → jitter, more partitions per bucket
    • Job store write load from next_run_at updates → batch updates, partition by job id
    • Slow job types blocking others → separate queues and worker pools per type

    10. Trade-offs

    Polling a database or an in-memory timer wheel

    Choose: Durable store polled by time bucket every second; an in-memory wheel only as an optimization for the next minute.

    Instead of: Only in-memory timers: precise and cheap, but lost on crash.

    Durability of accepted jobs is the core requirement.

    Exactly-once or at-least-once

    Choose: At-least-once execution, with idempotent handlers and a unique run row so duplicates are rare and harmless.

    Instead of: Promise exactly-once: impossible once a job touches an external system.

    Honest guarantees plus idempotency are safer than false ones.

    Push to workers or pull

    Choose: Workers pull from a ready queue at their own pace.

    Instead of: Scheduler pushes to specific workers: needs worker health tracking and causes overload.

    Pull gives natural backpressure.

    11. Failure modes

    Scheduler node dies holding partitions

    Due jobs in its partitions are delayed.

    Mitigation: Short partition leases (seconds); the new owner scans from the last committed watermark so nothing is skipped.

    Worker stalls past its lease

    Run picked up twice.

    Mitigation: Fencing tokens reject the stale worker's commit; handlers use idempotency keys for external effects.

    Poison job fails forever

    Retries burn capacity.

    Mitigation: Max attempts with exponential backoff, then the dead-letter queue with an alert.

    12. What interviewers probe

    Answer each one yourself before opening it.

    How do you handle daylight saving time for a job at 2:30 AM local time?Show a strong answer

    Store the IANA zone with the cron and compute next_run_at with a time-zone library; define behaviour for skipped (spring forward) and repeated (fall back) times explicitly, for example run once at the first occurrence.

    How do you cancel a job that is already enqueued?Show a strong answer

    Cancellation bumps the job version; workers check the version before executing and skip stale runs.

    How do you limit a tenant to 10 concurrent runs?Show a strong answer

    A per-tenant semaphore (counter with leases) checked when dequeuing; over-limit runs are re-queued with a delay.

    How would you add workflows (job B after job A)?Show a strong answer

    A workflow table of DAG nodes; completion of A enqueues ready successors in the same transaction as recording A's result.

    Sign in to track this guide in your curriculum progress.