{}DSA Atlas

Design a Distributed Job Scheduler (cron at scale)

Run millions of scheduled and delayed jobs reliably — job definitions and cron parsing, storing next-run times efficiently (time-bucketed tables, sorted sets, timing wheels), leasing and visibility timeouts so each run executes once, worker pools and queues, retries and idempotency, priorities and fairness across tenants, long-running workflows, and observability.

Advanced5 interview questions

1. Requirements

Functional

  • Create jobs: one-off at a time (run_at), delayed (in 15 min), or recurring (cron expression + timezone).
  • Execute job payloads (HTTP callback, queue message, or container task) on workers.
  • Retries with backoff, timeouts, cancellation, pause/resume; execution history.

Non-functional

  • 100M scheduled jobs; peak 50k executions/s (top-of-hour spikes!).
  • Run within ~1–2 s of scheduled time.
  • At-least-once execution, no lost jobs; duplicate runs rare and safe.
  • Highly available, horizontally scalable.

2. Data model

SQL
CREATE TABLE jobs (
  id            UUID PRIMARY KEY,
  tenant_id     BIGINT NOT NULL,
  schedule      TEXT,                 -- cron expr, NULL for one-off
  timezone      TEXT DEFAULT 'UTC',
  payload       JSONB NOT NULL,       -- target + args
  next_run_at   TIMESTAMPTZ,
  status        TEXT NOT NULL,        -- ACTIVE | PAUSED | DONE
  max_attempts  INT DEFAULT 5,
  timeout_s     INT DEFAULT 300,
  misfire       TEXT DEFAULT 'RUN_ONCE'
);
CREATE INDEX due_jobs ON jobs (next_run_at) WHERE status = 'ACTIVE';

CREATE TABLE runs (
  job_id        UUID,
  scheduled_for TIMESTAMPTZ,          -- logical time; (job_id, scheduled_for) = idempotency key
  attempt       INT,
  status        TEXT,                 -- QUEUED | RUNNING | SUCCEEDED | FAILED | TIMED_OUT
  worker_id     TEXT,
  lease_until   TIMESTAMPTZ,
  started_at    TIMESTAMPTZ, finished_at TIMESTAMPTZ, error TEXT,
  PRIMARY KEY (job_id, scheduled_for)
);

3. High-level design

clients job API jobs DBsharded, next_run_at idx pollers1 per shard (leased) ready queue: critical ready queue: default ready queue: bulk worker poolslease · heartbeat · execute runs history + metricsretries / DLQ claim due (SKIP LOCKED)
Storage of schedules is separate from execution; queues decouple the two.

Flow: API stores the job with next_run_at → the poller for each shard claims due jobs in batches, inserts a runs row (unique per (job_id, scheduled_for) — duplicates impossible), enqueues to the right priority queue, and advances next_run_at (computing the next cron occurrence) in the same transaction → workers pull, take a lease, execute with timeout, heartbeat, and record the result → failures are retried with backoff (re-enqueued with delay) until max_attempts, then DLQ + alert.

4. Deep dives

Claiming due jobs

SQL
WITH due AS (
  SELECT id, next_run_at
    FROM jobs
   WHERE status = 'ACTIVE' AND next_run_at <= now()
   ORDER BY next_run_at
   LIMIT 500
   FOR UPDATE SKIP LOCKED              -- concurrent pollers never grab the same rows
)
UPDATE jobs j
   SET next_run_at = next_occurrence(j.schedule, j.timezone, due.next_run_at)   -- NULL for one-off
  FROM due
 WHERE j.id = due.id
RETURNING j.id, due.next_run_at AS scheduled_for, j.payload, j.tenant_id;

Timing wheels for short delays

0 1 2 3 4 5 6 7 tick · array of N slots, each a list of timers · timer due in d ticks → slot (now + d) mod N, with rounds = d div N · each tick: fire timers in the current slot with 0 rounds · O(1) insert/cancel; hierarchical wheels for long delays
Timing wheels schedule millions of short timers with O(1) operations.

Top-of-the-hour spikes

Many cron jobs use 0 * * * *. Mitigate: encourage/auto-apply jitter (H syntax like Jenkins), pre-fetch due jobs a few seconds early into an in-memory delay queue, autoscale workers on a schedule, and prioritise latency-sensitive jobs.

Cron correctness

Parse cron with a library supporting timezones; compute occurrences in the job's timezone and store UTC; handle DST gaps/overlaps explicitly; validate expressions at creation; show "next 5 runs" in the UI.

5. Trade-offs

DecisionChoice
StorageSQL with SKIP LOCKED (simple, ~10k/s per shard) → shard by job ID; Cassandra time buckets for higher scale
Deliveryat-least-once + idempotency key (job_id, scheduled_for)
Executionqueue + worker leases with heartbeats; fencing via attempt number
Long jobscheckpoints or a workflow engine (Temporal)
Fairnesspriority queues + per-tenant concurrency limits

Interview questions

0 / 5 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.